Search code examples
androidandroid-activitysharedpreferences

show activity only once with Onclick button


i'm trying to show an activity only once with Onclick button firstly i have an activity useheadphone contains button when user click in this button mainactivity will start

my useheadphone.java :

public class useheadphone extends Activity {
    Button skip;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        requestWindowFeature(Window.FEATURE_NO_TITLE);
        getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,
                WindowManager.LayoutParams.FLAG_FULLSCREEN);
        setContentView(R.layout.activity_useheadphone);
        final SharedPreferences pref = getSharedPreferences("ActivityPREF", Context.MODE_PRIVATE);
        hide();
        skip = (Button)findViewById(R.id.skip);
        skip.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if(pref.getBoolean("activity_executed", false)){
                    Intent toMain = new Intent(getApplicationContext(),MainActivity.class);
                    startActivity(toMain);
                    finish();
                } else {
                    SharedPreferences.Editor ed = pref.edit();
                    ed.putBoolean("activity_executed", true);
                    ed.commit();
                }
            }
        });
    }

my manifest :

<activity
            android:name=".useheadphone"
            android:configChanges="orientation|keyboardHidden|screenSize"
            android:label="@string/title_activity_useheadphone"
            android:screenOrientation="portrait"
            android:theme="@style/FullscreenTheme">
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />
                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>

Solution

  • Add this code inside of the onCreate method at the Bottom of onCreate method (dont delete the original I have just copied and paste).:

    if(pref.getBoolean("activity_executed", false)){
                    Intent toMain = new Intent(this,MainActivity.class);
                   startActivity(toMain);
    }
    

    You should also consider using smaller context here:

    Change this line:

    Intent toMain = new Intent(getApplicationContext(), MainActivity.class);
    

    To:

    Intent toMain = new Intent(useheadphone.this, MainActivity.class);