Question

My application requires connection to a server, hence it will not work without set preferences. The preferences are set using SharedPreferences. What I am looking for is a pattern to direct the user to the settings activity. What is common?

Currently I am checking on onCreate and onResume whether all preferences are set, otherwise I start the settings activity. The problem is:

  1. the activity is started twice (through onCreate and onResume)
  2. the user might not know that he/she can go back to the main activity with the back hardware key

Any suggestions to implement this?

Was it helpful?

Solution

create a LauncherActivity class where you can make the decision which Activity should start - PreferenceActivity, or MainActivity: check this advice also

public class LauncherActivity extends Activity {

    SharedPreferences settings;

    public void onCreate(Bundle savedInstanceState) {

        settings = getSharedPreferences(PREFS_NAME, 0);

        if (settings.getBoolean(PREFS_REG, false)) {
            startActivity( new Intent(this, MAinActivity.class) );
            finish();
        } else {
             Intent enableBtIntent = new Intent(this, PreferenceActivity.class);
         startActivityForResult(enableBtIntent, SETTINGS);
        }
    }

    protected void onActivityResult(int requestCode, int resultCode, Intent data) {

        if(requestCode == SETTINGS ) {
             startActivity( new Intent(this, MAinActivity.class) );
             Editor editor = settings.edit();
             editor.putBoolean(PREFS_REG, true);
             editor.commit();
             finish();
        }

    }
}

And if user "registered" then set the PREFS_REG to true in onActivityResult()

OTHER TIPS

I suggest you show a Popup Dialog with a message like "set preferences first" with a button to open your Settings Activity. The check for SharedPreferences and opening the Dialog can be done in onResume.
And close the Settings Activity automatically when user finishes editing settings (and presses save-Button).

  1. onResume will always be called after onCreate, therefore you only need to perform the check and start the new activity in the onResume method.

  2. You could display a Toast when the SettingsActivity loads, such as:

    Toast.makeText(context, "Press back to return.", Toast.LENGTH_SHORT).show();
    

You may also wish to show a Toast or AlertDialog when the SettingsActivity starts telling the user that they must enter these settings before they can use the app.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top