当我想在 android 中制作自定义列表视图时遇到问题。
MyListView 类:
public class MyListView extends ArrayAdapter<Quotes> {
Context context;
int resource ;
private final List<Quotes> items;
public MyListView(Context context,int resourse , List<Quotes> items){
super(context, resourse,items);
this.resource = resourse;
this.items = items;
}
public View getView(int position, View convertView, ViewGroup parent) {
try {
View v = convertView;
if (v == null) {
LayoutInflater vi = (LayoutInflater) context
.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
v = vi.inflate(R.layout.list_item, null);
}
Quotes item = items.get(position);
TextView text = (TextView) v.findViewById(R.id.listItemText);
TextView id = (TextView) v.findViewById(R.id.listItemId);
text.setText(item.getText());
id.setText(item.getID());
} catch (NullPointerException e) {
e.printStackTrace();
Log.e("Error Saeed", e.getMessage());
}
return convertView;
}
}
并在 onCreate 方法的 MainActivity 中:
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
DatabaseHandler db = new DatabaseHandler(this);
final ListView lv = (ListView)findViewById(R.id.listView1);
MyListView adapter = new MyListView(this, R.layout.list_item, db.getAllQuotes());
lv.setAdapter(adapter);
}
DatabaseHander 类
public class DatabaseHandler extends SQLiteOpenHelper {
....
....
public List<Quotes> getAllQuotes(){
SQLiteDatabase db = getWritableDatabase();
Cursor c = db.rawQuery("select * from "+TABLE_QUOTE,null);
List<Quotes> quotes = new ArrayList<Quotes>();
if(c.moveToFirst()){
do{
Quotes q = new Quotes(Integer.parseInt(c.getString(0)),c.getString(1),c.getString(2));
quotes.add(q);
}while(c.moveToNext());
}
db.close();
c.close();
return quotes;
}
...
...
}
当我运行应用程序时,它会出错并关闭。
哪里有问题?