从数据库获取数据到listview android

时间:2013-05-29 17:39:44

标签: android database sqlite

您好,我正在尝试从我的sqlite数据库获取数据到listview。我已经尝试了几种方法,但总是给我错误。 (是的,我已经尝试修复该行的代码,但未成功)。 守则:

        Cursor cursor = db.getAllmeds();

        String[] list = null;
        int i = 0;
        cursor.moveToFirst();
        for (cursor.moveToFirst();!cursor.isAfterLast();cursor.moveToNext()){
            list[i]=cursor.getString(cursor.getColumnIndex("medicamentos_desig"));
            i+=1;
        }

        int to[] = {R.id.listView1};

        db.close();
        final ListView listview = (ListView) findViewById(R.id.listView1);
        SimpleCursorAdapter adapter = new SimpleCursorAdapter(this, R.layout.medicamentos,cursor,list,to,0);
        listview.setAdapter(adapter);

        listview.setOnItemClickListener(new OnItemClickListener() {

            public void onItemClick(AdapterView<?> arg0, View arg1, int arg2,long arg3) {

                Cursor listCursor = (Cursor) arg0.getItemAtPosition(arg2);

                String id = listCursor.getString(listCursor.getColumnIndex("medicamentos_id"));

                Intent passIntent = new Intent(arg1.getContext(),Editar.class);
                passIntent.putExtra("id", id);
                passIntent.putExtra("tipo", tipo);
                passIntent.putExtra("accao", "update");
                startActivity(passIntent);
            }

        });

错误日志:

     05-29 18:33:32.653: E/AndroidRuntime(341): java.lang.ClassCastException: java.lang.String
     05-29 18:33:32.653: E/AndroidRuntime(341):     at admed.Listar$1.onItemClick(Listar.java:55)

1 个答案:

答案 0 :(得分:0)

在这里:

String[] list = null;  //<<<

在添加元素之前,您需要初始化list数组。

 cursor.moveToFirst();
 list=new String[cursor.getCount()];//<<<initialize Array here with cursor Count
 .....