I am writing an Android application, there is a list of contacts that I receive from the server and write to the database. And when I display the data on the screen, they are not displayed in the order in which they were received (always in different), and not all data.

Method for writing to the database

public void addRec(final String firstName, final String lastName, final String image) { new Thread(new Runnable() { @Override public void run() { ContentValues cv = new ContentValues(); cv.put(COLUMN_FNAME, firstName); cv.put(COLUMN_LNAME, lastName); cv.put(COLUMN_URL, image); sql.insertOrThrow(TABLE_FRIENDS, null, cv); } }).start(); } 

called in a loop

 public static void updateBase (final Context context){ Contract contract=new Contract(context); contract.openDB(); contract.delete(); for(int i=0;i<friends.size();i++) { contract.addRec(friends.get(i).first_name, friends.get(i).last_name, friends.get(i).photo); } } 

Why is the data order broken? How to fix?

    1 answer 1

    In the relational data model, the order of the rows does not matter. SQLite, in turn, being a relational database, does not guarantee the order of adding rows. You specify the order of the rows explicitly with the ORDER BY in the query. If you need to preserve the order of addition, add a column with the id INTEGER PRIMARY KEY AUTOINCREMENT , and in the query specify ORDER BY id ASC .

    Details here: http://sqlite.org/autoinc.html and here: https://www.sqlite.org/lang_select.html#orderby

    • The fact is that the lines are not added correctly, and not all. Those. of the 84 contacts, only 70 are recorded in the table, or even less. And when I look at the table after adding, they are in random order. - Pavel_dev
    • Just now noticed. You have to add a new thread to add each record. Why do you need this? And are you sure that insertOrThrow () is really thread safe? - tse
    • Removed the launch of a new thread, the order is preserved, but some records are missing. Apparently with the threads namudril something. If I put the stream to sleep in a cycle for 10ms, then it records everything. - Pavel_dev