简体   繁体   中英

How can i get the specific data from array

My question is when i store the data into array from sqlite database, how can i get it from specific position let say, my database contain "food, drinks,snack" how can i get the string "snack" from array.

 String CatNameQuery = "SELECT * FROM Category";
    db = new DBController(MainActivity.this);
    SQLiteDatabase db3 = db.getReadableDatabase();
    final Cursor cursor2 = db3.rawQuery(CatNameQuery, null);
    {
        List<String> array = new ArrayList<String>();

        while(cursor2.moveToNext()){
            String uname = cursor2.getString(cursor2.getColumnIndex("CategoryName"));
            array.add(uname); 

    }

You need to iterate through the list in order to find the item you are looking for.

For example:

for (String s : array) {
    if (s.equals("snack")) {
        System.out.println("Found snack");
    }
}

You can also use the contains method to check if the list contains "snack."

if (array.contains("snack")) {
    System.out.println("Found snack");
}

Resource: ArrayList

List<String> array = new ArrayList<String>();
array.add("food");
array.add("drinks");
array.add("snack");
String result="";
if (array.contains("snack"))   // avoid null pointer exception
{
int index =array.indexOf("snack") //find the index of arraylist

result=array.get(index); 
}

Use the WHERE clause within your SELECT query. For example:

"SELECT * FROM Category WHERE CategoryName='snacks'"

This will fill your array with only items under the category 'snacks'.

You can find it by looping the array

List<String> arrobj= new ArrayList<String>();
arrobj.add("food");
arrobj.add("drinks");
arrobj.add("snack");  
for (String value : arrobj) {
if (value.equals("snack")) {
    System.out.println("Here is the snack");
}
}  
if (array.size() > 0) {
    int index = 0;
    if (array.contains("Snacks")) {
        index = array.indexOf("Snacks");
        System.out.println(array.get(index));
    }
}

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