How to get database value into String array in android (sqlite database)

I have a database name of "CUED" (sqlite Android), it has a HELLO table that contains a column NAME. I can get the String value from this column. Let me show you my section of code

myDB =hello.this.openOrCreateDatabase("CUED", MODE_PRIVATE, null); Cursor crs = myDB.rawQuery("SELECT * FROM HELLO", null); while(crs.moveToNext()) { String uname = crs.getString(crs.getColumnIndex("NAME")); System.out.println(uname); } 

It will print the value one by one. Now I need me to get the column values ​​from the database and store it in an array of rows.

+6
source share
3 answers

You have already done the hard part ... the material of the array is pretty simple:

 String[] array = new String[crs.getCount()]; int i = 0; while(crs.moveToNext()){ String uname = crs.getString(crs.getColumnIndex("NAME")); array[i] = uname; i++; } 

Be that as it may, I always recommend using collections in such cases:

 List<String> array = new ArrayList<String>(); while(crs.moveToNext()){ String uname = crs.getString(crs.getColumnIndex("NAME")); array.add(uname); } 

To compare arrays you can do things like this:

 boolean same = true; for(int i = 0; i < array.length; i++){ if(!array[i].equals(ha[i])){ same = false; break; } } // same will be false if the arrays do not have the same elements 
+25
source
  String[] str= new String[crs.getCount()]; crs.movetoFirst(); for(int i=0;i<str.length();i++) { str[i] = crs.getString(crs.getColumnIndex("NAME")); System.out.println(uname); crs.movetoNext(); } 

Enjoy it

0
source

This is my code that arraylist returns contains the value of a field:

 public ArrayList<String> getAllPlayers() { SQLiteDatabase db = this.getReadableDatabase(); Cursor cur = db.rawQuery("SELECT " + serailnumber + " as _id, " + title + " from " + table, new String[] {}); ArrayList<String> array = new ArrayList<String>(); while (cur.moveToNext()) { String uname = cur.getString(cur.getColumnIndex(title)); array.add(uname); } return array; } 
0
source

Source: https://habr.com/ru/post/906857/


All Articles