我需要我的自定義列表視圖適配器的一些幫助。我使用vogella.de的適配器示例,但我需要找到一種方法來設置來自sqlite數據庫的文本和圖像。下面是我使用的適配器代碼:Android listview adapter顯示來自sqlite的文本
import android.app.Activity;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.ImageView;
import android.widget.TextView;
public class MyArrayAdapter extends ArrayAdapter<String> {
private final Activity context;
private final String[] names;
Cursor cursor;
public MyArrayAdapter(Activity context, String[] names) {
super(context, R.layout.main_listview, names);
this.context = context;
this.names = names;
}
// static to save the reference to the outer class and to avoid access to
// any members of the containing class
static class ViewHolder {
public ImageView imageView;
public TextView textView,textView2;
}
@Override
public View getView(int position, View convertView, ViewGroup parent) {
// ViewHolder will buffer the assess to the individual fields of the row
// layout
ViewHolder holder;
// Recycle existing view if passed as parameter
// This will save memory and time on Android
// This only works if the base layout for all classes are the same
View rowView = convertView;
if (rowView == null) {
LayoutInflater inflater = context.getLayoutInflater();
rowView = inflater.inflate(R.layout.main_listview, null, true);
holder = new ViewHolder();
holder.textView = (TextView) rowView.findViewById(R.id.main_name);
holder.textView2 = (TextView) rowView.findViewById(R.id.main_info);
holder.imageView = (ImageView) rowView.findViewById(R.id.main_img);
rowView.setTag(holder);
} else {
holder = (ViewHolder) rowView.getTag();
}
final Bitmap b = BitmapFactory.decodeFile("/sdcard/52dde26940e0d3081f6a086d4b54cd1c.jpg", null);
holder.textView.setText("");
holder.textView2.setText("");
holder.imageView.setImageBitmap(b);
return rowView;
}
public String[] getNames() {
return names;
}
}
而且我想將文本設置爲這樣的文本視圖:
String sql = "SELECT title FROM collections";
Cursor cursorTitle = userDbHelper.executeSQLQuery(sql);
if(cursorTitle.getCount()==0){
Log.i("Cursor Null","CURSOR TITLE NULL");
} else if(cursorTitle.getCount()>0){
cursorTitle.moveToFirst();
String text = cursorTitle.getString(cursorTitle.getColumnIndex("title"));
Log.i("title text","title text : "+text);
String[] names = new String[] { text };
listView.setAdapter(new MyArrayAdapter(this, names));
}
,但是當我運行的代碼我不因此,我的listview中沒有任何東西。
所以任何人都可以建議我如何在我的活動中使用此適配器在imageview和textview中設置文本和圖像。
非常感謝!
logcat中的任何錯誤?遊標是否爲空?你的sqlite表中有數據嗎?您將文本設置爲「」。該圖像可能不存在於您的SD卡... –
我沒有在我的Logcat中發現任何錯誤,圖像在SD卡中,我沒有問題。我在我的表中有數據,並且遊標不是空的。 –