Mario
Mario

Reputation: 145

Checking sharedpreference before App starts

I want to check SharedPreferences before my app starts. I want to check whether a value in is true or false and depending on that I want to start different activities (if value is true, I want to start one activity; if it is false, I want to start second activity). How to check it before showing my apps first screen?

Upvotes: 3

Views: 2077

Answers (4)

Ranjit
Ranjit

Reputation: 5150

In onCreate method first get the sharedpreference value .

if its true then set the content view i.e

 if(sharedpreference_value == true) { 
   setContentView(R.layout.your_layout);
 }

 else {
   finish();
 }

Upvotes: 0

Rohan Kandwal
Rohan Kandwal

Reputation: 9326

In your onCreate() method check if the value in the shared Preference is true of false

SharedPreferences sharedPreferences= PreferenceManager.getDefaultSharedPreferences(getActivity());
boolean check = sharedPreferences.getBoolean("Check",false);
Intent intent;       
if(check){
intent = new Intent(this, First.class);
else
intent = new Intent(this, Second.class);
startActivity(intent);
finish();

But keep in mind that the boolean value check should exist in the Shared Preferences otherwise it will always return false.

Upvotes: 0

CommonsWare
CommonsWare

Reputation: 1006654

i want to check shared preference before my app starts

By definition, that is not possible. If your app has not started, your code is not running, and so your code cannot check SharedPreferences.

If value is true i want to start one activity if it is false i want to start second activity.how to check it before showing my apps first screen?

Have your activity handle one case (e.g., true) itself. In onCreate(), check SharedPreferences, and if the value is false, call startActivity() to launch the other activity, then finish() to get rid of the current one (since it is no longer needed).

Or, have only one activity, but two different fragments, and load the proper fragment based upon the SharedPreferences.

Upvotes: 6

marcinj
marcinj

Reputation: 49986

You can do it in your starting activity, do your decision in onCreate, and excute appropriate activity.

Upvotes: 1

Related Questions