簡體   English   中英

android中Sqlite的ListView

[英]ListView From Sqlite in android

當我搜索整個網絡時,ListView From Sqlite 仍然存在問題。 在搜索了這么多之后,我正在 android hive 示例鏈接上嘗試我的項目。 所以在這個數據庫處理程序類中,他們給出了一個函數,即 List getAllContacts() 以列表格式獲取所有 sqlite 數據。 我已經在我的項目中實現了這個,我在 ViewContact.class 中使用了上面的函數。 問題是我不明白如何使用這種類型的方法或任何其他方法獲取 ListView 中的所有數據。

查看我的代碼(ViewContact.class):

public class ViewContact extends Activity {
DatabaseHandler helper = new DatabaseHandler(this);
String a;
@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.row);
    ListView listContent = (ListView)findViewById(R.id.listView1);
    }
public List<Contact> getAllContacts() {
    List<Contact> contactList = new ArrayList<Contact>();
    // Select All Query
    String selectQuery = "SELECT  * FROM contacts";
    SQLiteDatabase db = helper.getWritableDatabase();
    Cursor cursor = db.rawQuery(selectQuery, null);
    // looping through all rows and adding to list
    if (cursor.moveToFirst()) {
        do {
        Contact contact = new Contact();
        contact.setID(Integer.parseInt(cursor.getString(0)));
        contact.setName(cursor.getString(1));
        contact.setPhoneNumber(cursor.getString(2));
        // Adding contact to list
        contactList.add(contact);
    } while (cursor.moveToNext());
}// return contact list
return contactList;}}

編輯:


請參閱@GrIsHu 回答后,輸出為:

嘗試將數據綁定到列表視圖中,如下所示:

 List<Contact> contact = new ArrayList<Contact>(); contact=getAllContacts(); ArrayAdapter adapter = new ArrayAdapter(this, android.R.layout.simple_list_item_1, contact); listContent.setAdapter(adapter);

下面是一個代碼,我想你可以使用它來滿足你的要求。 在下面的代碼中,我將獲取保存在我的數據庫中的聯系人並將其顯示在listView 如果用戶想從數據庫中刪除一個聯系人,那么他可以長按該項目,使用出現的對話框,他可以刪除該聯系人。 下面是代碼:

    public class viewContacts extends ListActivity {

        private static final String TAG = "MYRECORDER";

        @Override
        protected void onCreate(Bundle savedInstanceState) {
            // TODO Auto-generated method stub
            super.onCreate(savedInstanceState);
            setContentView(R.layout.showcontacts);

            //Creating a List View
            ArrayList<String> listItems = new ArrayList<String>();
            ArrayAdapter<String> adapter = new ArrayAdapter<String>(this, 
                    android.R.layout.simple_list_item_1, listItems);
            ListView mylist=(ListView) findViewById(android.R.id.list);
            mylist.setAdapter(adapter);


//Creating or opening an eisting database
            SQLiteDatabase db=openOrCreateDatabase("MYDB", Context.MODE_PRIVATE, null);

//Getting a cursor to fetch data from the database
              Cursor c=db.rawQuery("SELECT Number,Name FROM myTbl", null);
              Log.d(TAG, "Cursor reference obtained...");
              c.moveToFirst();
              Log.d(TAG, "Cursor Moved to First Number....");
              if(c!=null){
//If there are contents in the database, then c!=null, so using do-while loop access data // in database
                do{
                    String num=c.getString(c.getColumnIndex("Number"));
                    String name=c.getString(c.getColumnIndex("Name"));
                    String Name_num=name+" : "+num;
                    listItems.add(Name_num);
                    c.moveToNext();
                }while(!c.isAfterLast());

//update the list
                adapter.notifyDataSetChanged();

//closing the database after use
                db.close();

//Below is the code to delete items in data base
                mylist.setOnItemClickListener(new OnItemClickListener() {
                    String str=null;    
                    public void onItemClick(AdapterView<?> arg0, View view,
                            int arg2, long arg3) {

                        // TODO Auto-generated method stub
                        String item = ((TextView)view).getText().toString();
                         str=item.substring(item.lastIndexOf('+'));
                         Toast.makeText(getBaseContext(), str, Toast.LENGTH_LONG).show();
                        //Creating an Alert Dialog
                        AlertDialog .Builder builder=new AlertDialog.Builder(viewContacts.this);
                        builder.setMessage("Are you sure you want to delete the contact "+str+" ?");
                        builder.setCancelable(false);
                        builder.setPositiveButton("Yes", new DialogInterface.OnClickListener() {

                            public void onClick(DialogInterface dialog, int which) {
                                // TODO Auto-generated method stub
                                SQLiteDatabase db=openOrCreateDatabase("MYDB", MODE_PRIVATE, null);
                                Toast.makeText(getBaseContext(), "The contact: "+str+" was successfully deleted", Toast.LENGTH_LONG).show();
                                String table="myTbl";
                                String whereClause = "Number = ?";
                                String[] whereArgs = new String[] { str };
                                db.delete(table, whereClause, whereArgs);
                                db.close();
                            }
                        });
                      builder.setNegativeButton("No", new DialogInterface.OnClickListener() {

                        public void onClick(DialogInterface dialog, int which) {
                            // TODO Auto-generated method stub
                            dialog.cancel();
                        }
                    } );
                      AlertDialog alert=builder.create();
                      alert.show();
                    }           
                });
        }
        }
    }

在這種情況下只需使用SimpleCursorAdapterhttp : //www.java2s.com/Code/Android/UI/UsingSimpleCursorAdapter.htm

我解決了將函數 toString 添加到我的類對象的問題。

在您的情況下,將該功能添加到類聯系人

public String toString(){
    return name;
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM