Ali Khoshraftar
Ali Khoshraftar

Reputation: 542

sqlite android create unique column that no need to check availability when have to store

I developing news app that store all of news in sqlite database. It will be a big database during time. When i get data from API, check database to have every news and if doesn't exist store them to it. it takes 3-10 sec on every time when app run by user ( will take more during days ). Is there anyway to store my data to database in an asynctask that doesn't freeze my app ? or another efficient way ? every news has unique id. can i change my id column to unique that i don't have to check every time and store directly to database and database don't save it when it's available ?

for (int i = 0; i < jsonArrayAll.length(); i++)
   if (!db.isNewsExist(news.getNews_id()))
      db.addNews(news);

public boolean isNewsExist(String news_id) {
    boolean exist;
    SQLiteDatabase db = this.getReadableDatabase();
    Cursor cursor =
            db.query("news", COLUMNS_NEWS, " news_id = ?",
                    new String[]{news_id}, // d. selections args
                    null, // e. group by
                    null, // f. having
                    null, // g. order by
                    null); // h. limit

    if (!cursor.moveToFirst()) {
        return false;
    }
    exist = cursor.getString(1) != null;
    cursor.close();
    db.close();
    return exist;
}

Upvotes: 0

Views: 207

Answers (1)

Gabe Sechan
Gabe Sechan

Reputation: 93613

Yes- just put the update code in the doInBackground of an AsyncTask. SQLite can handle being called from multiple threads. As for improvements- don't query and then add. Just try to insert- if the column has a unique constraint that's violated it will throw an exception you can catch and ignore.

Upvotes: 1

Related Questions