简体   繁体   中英

sqlite database android get all column values into string array

I have a sqlite database in android , for example :

Table 1 person:

  • column 1: id
  • column 2: name
  • column 3: friends

Table 2 friends:

  • column 1: id
  • column 2: allFriends

the id is the same in both tables, id in table1 == id in table2 i want to get all the values from table2 in specific column "allFriends" by the id and insert all the String values from the column into String array / arrayList.

Try this,

  public ArrayList<String> getAllFriends(int id) {
    ArrayList<String> friendsNames = new ArrayList<>();
    SQLiteDatabase sqLiteDatabase = null;
    try {
        String query = "select * from person P join friends F on F.id = P.id where P.id = " + id;
        Cursor cursor = sqLiteDatabase.rawQuery(query, null);
        while (cursor.moveToNext()) {
            friendsNames.add(cursor.getString(cursor.getColumnIndex("allFriends")));
        }
    }catch(Exception ex){
        Log.e(TAG,"Erro in geting friends "+ex.toString());
    }
    return friendsNames;
  }

Your SQL query:

SELECT allFriends FROM friends where id == Id_from_person

Id_from_person - id of person who friends you want to recieve from DB.
For executing query read this .

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