ListView来自Android中的Sqlite

时间:2013-08-16 06:02:50

标签: android android-listview android-sqlite

因为我搜索整个网仍然存在ListView来自Sqlite的问题。经过如此多的搜索,我在android hive示例Link here上尝试我的项目。所以在这个数据库处理程序类中,他们给出了一个函数,即List getAllContacts()来获取List格式的所有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之后回答输出是:

4 个答案:

答案 0 :(得分:3)

尝试将数据绑定到listview中,如下所示:

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

答案 1 :(得分:1)

下面是一个代码,我想你可以满足你的要求。在下面的代码中,我将获取保存在我的数据库中的联系人,并将其显示在 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();
                    }           
                });
        }
        }
    }

答案 2 :(得分:0)

在这种情况下,只需使用SimpleCursorAdapterhttp://www.java2s.com/Code/Android/UI/UsingSimpleCursorAdapter.htm

答案 3 :(得分:0)

我解决了将函数toString添加到我的类对象。

在您的情况下,将该功能添加到班级联系人

public String toString(){
    return name;
}