Darshan Kodkany
Darshan Kodkany

Reputation: 69

Execute a piece of code once

I am currently developing an app that requires the data to be fetched from server and stored in my local data base.To ensure that the piece of code runs only once I am doing the following thing.

      SharedPreferences settings = getSharedPreferences(PREFS_NAME, 0);
        boolean dialogShown = settings.getBoolean("dialogShown", false);


        if (!dialogShown) {
            //Asyntask executed here

            if (haveNetworkConnection()) {

                new xyz().execute();



            } else {
                Toast.makeText(getApplicationContext(), "Sorry... No Internet Connection", Toast.LENGTH_LONG).show();
            }

            SharedPreferences.Editor editor = settings.edit();
            editor.putBoolean("dialogShown", true);
            editor.apply();
        }

Above I am setting the shared preference so that it gets executed only once.Now the Problem is in case if there is no internet connection the shared preference will be executed and the data will not be loaded how can I overcome this situation.Any help Appreciated

Upvotes: 1

Views: 76

Answers (2)

SeahawksRdaBest
SeahawksRdaBest

Reputation: 886

You can check for the network connection first.

    if (haveConnection()){
       if(!dialogShown){
        new xyz().execute
        dialogShown = true;
    }else
     //already done
    }
   }

The above code should check for a connection first then check for a dialogShown variable being false. The con of this approach is the constant pinging of the connection to check if it exists. Depending on how you are using the enclosing method this might cause a design decision review. You can always use onPostExecution() instead.

Upvotes: 0

ρяσѕρєя K
ρяσѕρєя K

Reputation: 132982

Now the Problem is in case if there is no internet connection the shared preference will be executed and the data will not be loaded how can I overcome this situation.

Instead of updating value when dialogShown is false, update value in SharedPreferences when Network connection is available otherwise make it false:

if (haveNetworkConnection()) {         
    new xyz().execute();
    // update value in SharedPreferences for dialogShown to true
} else {
    // update value in SharedPreferences for dialogShown to false              
}

Or use onPostExecute method of xyz class for updating flag value when all operation is successful

Upvotes: 1

Related Questions