简体   繁体   中英

ListView From Sqlite in android

As I searched whole net still in problem with ListView From Sqlite. After searching so much i am trying my project on android hive example Link here . So in this in Database Handler class they have given that a function ie List getAllContacts() to get all sqlite data in List format. I have implemented this in my project my using above function in ViewContact.class. The PROBLEM is that I am not understanding how to get all data in ListView by using this type of method or by any other method.

See my code (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;}}

EDIT:


See After @GrIsHu answer the output is :

Try to bind the data into the listview as below:

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

Below is a code using which i suppose you can meet your requirements. In the below code i would fetch contacts saved in my database and display it in a listView . If the user wants to delete a contact from the database, then he shall long press on the item, and using the dialog that appears, he can delete the contact. Below is the code:

    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

I solve that adding the function toString to my class object.

In your case, add that function to the class contact

public String toString(){
    return name;
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM