0

我想将数据库的所有行显示为列表视图。但我只有一个。我怎样才能得到所有的行?这是我的MainAcitvity.class。我对光标了解不多。我想这可能是原因。

SQLiteDatabase db=openOrCreateDatabase("PhoneBook.db",MODE_PRIVATE, null);

    db.execSQL("CREATE TABLE IF NOT EXISTS PhoneBook(NAME VARCHAR,PHONE_NO VARCHAR,EMAIL VARCHAR);");


    Cursor c =db.rawQuery("SELECT * FROM PhoneBook" ,null);

    totalcontact=c.getCount();

    if (totalcontact==0) {

       final  Dialog d =new Dialog(MainActivity.this);
        d.setContentView(R.layout.popup);

        d.setCancelable(true);


        Button b =(Button)d.findViewById(R.id.button1);
       b.setOnClickListener(new OnClickListener() {

            @Override
            public void onClick(View v) {

                setContentView(R.layout.helpmenu);

                 d.dismiss(); 
            }

        });
       d.show();
    }
    else
    {
        c.moveToFirst();

        while(totalcontact!=0)
        {

         pName=c.getString(c.getColumnIndex("NAME"));
         pPhone=c.getString(c.getColumnIndex("PHONE_NO"));
         pEmail=c.getString(c.getColumnIndex("EMAIL"));

    List<PhoneBook> listPhoneBook = new ArrayList<PhoneBook>();
    listPhoneBook.add(new PhoneBook(
            BitmapFactory.decodeResource(getResources(), R.drawable.e2),
            ""+pName+"", ""+pPhone+"", ""+pEmail+""));
    PhoneBookAdapter adapter = new PhoneBookAdapter(this, listPhoneBook);
    lvPhone.setAdapter(adapter);
    c.moveToNext();
    totalcontact=totalcontact-1;
          }
    c.close();


    }
    db.close();

请帮助我了解我的代码有什么问题。

4

1 回答 1

3

List在每次迭代中创建一个新的。

在循环外声明它:

c.moveToFirst();
List<PhoneBook> listPhoneBook = new ArrayList<PhoneBook>();

while(totalcontact!=0){    
         pName=c.getString(c.getColumnIndex("NAME"));
         pPhone=c.getString(c.getColumnIndex("PHONE_NO"));
         pEmail=c.getString(c.getColumnIndex("EMAIL"));    
         listPhoneBook.add(new PhoneBook(
            BitmapFactory.decodeResource(getResources(), R.drawable.e2),
            ""+pName+"", ""+pPhone+"", ""+pEmail+""));
         c.moveToNext();
         totalcontact=totalcontact-1;
 }
 c.close();
 PhoneBookAdapter adapter = new PhoneBookAdapter(this, listPhoneBook);
 lvPhone.setAdapter(adapter);
于 2013-06-19T07:04:44.017 回答