sid.s
sid.s

Reputation: 315

opening activity only once NOT WORKING

i followed some other questions on stack overflow and created a basic project to open an activity only once.However its not working.what wrong? After opening once, i close it. However on reopening it starts with the first activity again.

my first activity:

public class MainActivity extends AppCompatActivity {
private Button button;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    button = (Button)findViewById(R.id.buttonid);
    button.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {

            startActivity(new Intent(MainActivity.this,Main2Activity.class));
        }
    });
    SharedPreferences pref = getSharedPreferences("ActivityPREF",    Context.MODE_PRIVATE);
    if(pref.getBoolean("activity_executed", false)){

    } else {
        Intent intent = new Intent(this, Main2Activity.class);
        startActivity(intent);
        finish();
        SharedPreferences.Editor ed = pref.edit();
        ed.putBoolean("activity_executed", true);
        ed.commit();
    }
}
}

my second activity:

public class Main2Activity extends AppCompatActivity {

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main2);
}
 }

Upvotes: 0

Views: 1167

Answers (2)

Ricardo
Ricardo

Reputation: 9676

This is how I do it, hope it helps:

First activity inside onCreate

if (pref.getString("someConstant",null) == null){
    //This is my first time, no value in sharedpref for "someConstant"
    //Feel free to do any logic here if needed
}else{
    //not my first time
    Intent intent = new Intent(this, Main2Activity.class);
    startActivity(intent);
    finish();   
}

Now in your second activity, once it opens just set the shared preference inside onCreate

SharedPreferences.Editor ed = pref.edit();
ed.putString("someConstant","some random string, does not make difference").commit();   

On first start your app won't have any value, therefore it will stay in the first activity because "someConstant" returns null. Once you enter the second activity the value in shared preferences will be stored, so in any new app launch after that you will go straight to the second activity

Upvotes: 0

6155031
6155031

Reputation: 4327

change your code . save first then open activity .

 SharedPreferences.Editor ed = pref.edit();
        ed.putBoolean("activity_executed", true);
        ed.commit();
 Intent intent = new Intent(this, Main2Activity.class);
        startActivity(intent);
        finish();

Upvotes: 1

Related Questions