简体   繁体   中英

Android studio sqlite to listview

On create method;

     db = openOrCreateDatabase("messages", MODE_PRIVATE, null);
     db.execSQL("CREATE TABLE IF NOT EXISTS message(msg TEXT);");
     db.execSQL("INSERT INTO message values('example');");
     listeview1 = (ListView) findViewById(R.id.listview);
     ArrayList<String> dbArray = myArrayListTodatabase();
     ListAdapter mylistadapter = new ArrayAdapter<String>(this,android.R.layout.simple_list_item_1, dbArray);
        listview.setAdapter(mylistadapter);

Myarraylisttodatabase code;

public ArrayList<String> myArrayListTodatabase() {
    db = openOrCreateDatabase("messages", MODE_PRIVATE, null);
    db.rawQuery("Select * from message", null);
    Cursor c = db.rawQuery("Select * from message", null);
    c.moveToFirst();
    String dbString = "";
    while (!c.isAfterLast()) {
        if (c.getString(c.getColumnIndex("msg")) != null) {
            dbString += c.getString(c.getColumnIndex("msg"));
            dbString += "\n";

        }
        c.moveToNext();
    }
    db.close();
    return myArraylist;
}

Global variables

SQLiteDatabase db = null;
public ArrayList<String> myArraylist = new ArrayList<String>();

Im using these but there is no output in listview when i run the app

You are not adding content to the ArrayList at all. Add myArraylist.Add(dbString) or something to fill your ArrayList for your ListView to use.

You forgot to insert into ArrayList. Update your function with below one:

public ArrayList<String> myArrayListTodatabase() {
    myArraylist.clear();
    db = openOrCreateDatabase("messages", MODE_PRIVATE, null);
    db.rawQuery("Select * from message", null);
    Cursor c = db.rawQuery("Select * from message", null);
    String dbString = "";
    while (c.moveToNext()) {
        if (!c.getString(c.getColumnIndex("msg")).equals("")) {
            myArraylist.add(c.getString(c.getColumnIndex("msg")));
        }
    }
    c.close();
    db.close();
    return myArraylist;
}

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