简体   繁体   English

我如何从数组中获取特定数据

[英]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. 我的问题是,当我将数据从sqlite数据库存储到数组中时,如何从特定位置获取数据,比如说,我的数据库包含“食物,饮料,小吃”,如何从数组中获取字符串“小吃”。

 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." 您还可以使用contains方法检查列表中是否包含“小吃”。

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

Resource: ArrayList 资源: 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. 在SELECT查询中使用WHERE子句。 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));
    }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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