在android

时间:2016-11-05 16:19:20

标签: android sqlite cursor

我想在android中的sqllite数据库中找到一些信息。但我不知道是什么。 我的代码是:



 public Cursor getData() {
        String myPath = DB_PATH + DB_NAME;
        db = SQLiteDatabase.openDatabase(myPath, null,
                SQLiteDatabase.OPEN_READONLY);
        Cursor c = db.rawQuery("SELECT text,_id from tbl_laws where parent_id = 0",null);
        // Note: Master is the one table in External db. Here we trying to access the records of table from external db.


        Cursor c1 = db.rawQuery("SELECT text,_id from tbl_nokte where parent_id = 0",null);
        // Note: Master is the one table in External db. Here we trying to access the records of table from external db.
        return c;
        return c1;
    }




任何人都可以帮助我吗?

1 个答案:

答案 0 :(得分:1)

解决方案是调整SQL-Select-Query。

您已经使用rawQuery来获取信息,但是对于两个不同的Cusors。这不起作用。

使用单个游标获取所需信息的解决方案可能是:

public Cursor getData() {
    String myPath = DB_PATH + DB_NAME;
    db = SQLiteDatabase.openDatabase(myPath, null,
            SQLiteDatabase.OPEN_READONLY);

    String query = "SELECT laws._id, laws.text," +
                          " nokt._id,nokt.text" +
                   " FROM tbl_laws AS laws, tbl_nokte AS nokt" +
                   " WHERE laws.parent_id = 0 AND nokt.parent_id = 0";


    Cursor c = db.rawQuery(query, null);

    return c;
}

用法是:

public List<YourObject> getDataForYourObjects(Cursor c){
    List<YourObject> yourObjects = new ArrayList<>();
    if(c != null){
       while(c.moveToNext(){
          //law results
          long lawsID = c.getLong(0);
          String lawsText = c.getString(1);

          //nokt results
          long noktID = c.getLong(2);
          String noktText = c.getString(3);

          YourObject yo = new YourObject();
          yo.addLaw(lawID, lawText);
          yo.addNokt(noktID, noktText);
          yourObjects.add(yo);
       }
       c.close();
    }
    return yourObjects;
}

(上面的示例代码未经过测试!)

希望它有所帮助。

Additonal,您可以查看SQLite教程,例如: http://www.tutorialspoint.com/sqlite/让他熟悉sqlite。

另请参阅Android SQLite教程,如: https://www.tutorialspoint.com/android/android_sqlite_database.htm 获取有关Anroids-SQLite和游标对象的更多信息。