Is it safe to execute a new SQLite query while still repeating the cursor for an earlier query? (Android)

I call SQLiteDatabase.query and get the cursor. Although I am still repeating this cursor, is it safe to issue other requests from the same thread?

+4
source share
2 answers

Yes. You can have several outstanding queries from the same stream and access each of the cursors independently.

I added the following code to the test activity and it works as expected:

SQLiteDatabase connection = getApplicationContext().openOrCreateDatabase("foo.db", MODE_PRIVATE, null); try { connection.execSQL("drop table if exists person"); connection.execSQL("create table person (id integer, name string)"); ContentValues cv = new ContentValues(); cv.put("id", 1); cv.put("name", "leo"); connection.insert("person", null, cv); cv = new ContentValues(); cv.put("id", 2); cv.put("name", "yui"); connection.insert("person", null, cv); Cursor rs = connection.query("person", new String[] {"id", "name" }, null, null, null, null, null); while(rs.moveToNext()) { System.out.println("name = " + rs.getString(1)); System.out.println("id = " + rs.getString(0)); Cursor rs2 = connection.query("person", new String[] {"id", "name" }, null, null, null, null, null); while (rs2.moveToNext()) { System.out.println("name = " + rs2.getString(1)); System.out.println("id = " + rs2.getString(0)); } } } catch (Exception e) { System.out.println("Exception " + e); } 
+2
source

There are no two queries in the same column at the same time. . This is a built-in synchronized method, so it will only execute one request at a time. The second request will be pending until it completes its execution.

+3
source

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


All Articles