0

当我想在 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;
    }

...
...
}

当我运行应用程序时,它会出错并关闭。

在这个链接中你可以看到 log.txt

哪里有问题?

4

1 回答 1

1

您可能有一个NullPointerException,因为您没有ViewHoldergetView方法中初始化 when convertViewis null

ViewHolder holder = null;
Quotes item = items.get(position);
if(convertView == null){
        convertView = inflater.inflate(R.layout.list_item, null);
        holder = new ViewHolder();
        holder.txtTitle = (TextView) convertView.findViewById(R.id.listItemText);
        holder.txtID = (TextView)convertView.findViewById(R.id.listItemId);
        convertView.setTag(holder); 
} else {
        holder = (ViewHolder) convertView.getTag();
}

您的代码中可能存在其他问题。

于 2012-09-23T13:48:09.590 回答