S.Claire S.Claire - 2 months ago 20
Java Question

How to call method in Activity only once if database holds existing data?

I have made an app, which allows users to add favourites to a SQLite database which in turn loads the information into a favourites arraylist, which is displayed in the favourites activity. When the user clicks 'add to favourites button', this function is executed:

public void loadFavourites() {

SQLiteDatabase db = dbHelper.getReadableDatabase(); //Get the database from which to read values

//Get columns and create a cursor database query
String[] columns = {"favouriteId", "title", "owner", "url_m", "ownerPic", "description", "dateTaken"};
Cursor cursor = db.query("favourites", columns, null, null, null, null, "favouriteId");

Log.d("FavouritesDB", "" + cursor.getCount()); //Displays cursor count in the logcat


while (!cursor.isAfterLast()) {

favID = cursor.getInt(0);
title = cursor.getString(1);
owner = cursor.getString(2);
url_m = cursor.getString(3);
ownerPic = cursor.getString(4);
description = cursor.getString(5);
date = cursor.getString(6);

ImageInfo favourite = new ImageInfo();

favourite.dateTaken = date;
favourite.description = description;
favourite.ownerPic = ownerPic;
favourite.url_m = url_m;
favourite.owner = owner;
favourite.title = title;

cursor.moveToNext(); // Move to next entry

This successfully adds the image to the favourites arraylist and displays it when the user visits the favourites activity page.

However, every time the app is closed and reopened, the favourites activity is empty, and does not show favourites already added to the database, as the loadFavourites method hasn't been called.

However, if I call the loadFavourites method in the favourites activity onCreate(), every time the page is loaded, the favourites from the database are all added again to the arraylist, so this creates duplicates of each favourite item.

Please could someone suggest how I could fix my loop so that when my app launches, only existing favourite items from the database are added, and are not added again to the arraylist each time the activity is loaded?

Answer Source

Clear favourites arraylist just before calling loadFavourites() or add favouritesarraylist.clear in the first line of loadFavourites()

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download