我创建了一个包含列(id,title,…)的数据库和表(categories)
我想从数据库中读取类别并将类别列表显示为列表视图。
这是Y代码:

   public class MainActivity extends listActivity{

    private ArrayAdapter arrayAdapter;
    ArrayList results = new ArrayList();
    ListView catlist;
    Cursor cur;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        catlist = getListView();

        int parentid = getIntent().getIntExtra("catid", 0);
        openAndQueryDatabase(parentid);

        displayCatListView();




    }

    private void displayCatListView() {

        setListAdapter(new ArrayAdapter<String>(this,
                android.R.layout.simple_list_item_1, results));


        catlist.setOnItemClickListener(new OnItemClickListener() {

               @Override
               public void onItemClick(AdapterView<?> parent, View v,
                 final int position, long id) {


                Toast.makeText(MainActivity.this,
                  "List View Clicked:" + position, Toast.LENGTH_LONG)
                  .show();
               }
              });

    }

    private void openAndQueryDatabase(int parentid) {
        DataBaseHelper db = new DataBaseHelper(this);

        SQLiteDatabase dbr = db.getReadableDatabase();
        cur = dbr.rawQuery(
                "SELECT _id, title, has_sub FROM categories where parent_id=?",
                new String[] { String.valueOf(parentid) });


        if (cur != null) {
            while (cur.moveToNext()) {

                int cat_id = cur.getInt(cur.getColumnIndex("_id"));
                String cattitle = cur.getString(cur.getColumnIndex("title"));
                int has_sub = cur.getInt(cur.getColumnIndex("has_sub"));
                results.add(cat_id + cattitle + has_sub);
            }
            cur.close();
        }

        db.close();

    }
}

1)我可以得到位置。但我想买一个分类。请帮助
2)我是新来的。我的密码有错误吗?
谢谢

最佳答案

而不是

int cat_id = cur.getInt(cur.getColumnIndex("_id"));
String cattitle = cur.getString(cur.getColumnIndex("title"));
int has_sub = cur.getInt(cur.getColumnIndex("has_sub"));
results.add(cat_id + cattitle + has_sub);

创建一个category类来包含这些值,并使用参数化的arraylist。有点像
class Category {
    public int cat_id;
    public String cattitle;
    public int has_sub;

    public Category(int cat_id, ...) {
        // constructor logic here
    }
}


results.add(new Category(cat_id, cattitle, has_sub));

使用此选项,可以将OnEmClickListener设置为:
        catlist.setOnItemClickListener(new OnItemClickListener() {

           @Override
           public void onItemClick(AdapterView<?> parent, View v,
             final int position, long id) {
                 Category clickedCategory = results.get(position);
                 int id = clickedCategory.cat_id;

                 // do something with id
           }
          });

ArrayList是ArrayAdapter的数据源,并且position对应于其中单击的类别的索引。

10-04 12:40