1

I have an app which uses a login using Google+. I want the login screen to appear only for the first time, and then when the user logs out of the app. What should I do for this? I'm using this as the firstActivity for the app.

import android.content.Intent;
import android.support.v7.app.ActionBarActivity;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;


public class firstActivity extends ActionBarActivity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_first);
        findViewById(R.id.sign_in_button).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent i = new Intent(getApplicationContext(), LoginActivity.class);
                startActivity(i);
                finish();
            }
        });
    }
}

Now I do not know how to create a variable which can be assigned a value and be stored on the device, which will only be changed on logging out. How should I proceed?

Ayush Gupta
  • 1,589
  • 3
  • 13
  • 23

3 Answers3

1

Add the value in a SharedPreference and change it during Log in and Log out. Refer this link. After Log In store the value in sharedPreference and after Log out clear the value in sharedPreference

Logic
  • 2,230
  • 2
  • 24
  • 41
0

Use SharedPreference to store short information. It is best suite for your requirement. SharedPreference

Example

Community
  • 1
  • 1
Karn Shah
  • 501
  • 4
  • 14
0

Save a variable with a value in SharedPreferences first time when you login, then every time when you login check the saved value. When you logout you can re-write that value so that when you launch the app again since the value saved is different it will login.

To save a value to shared preferences you need to do the following: The following is to save a string variable: Here MyData is the name of File in which value will be stored.

SharedPreferences sharedPreferences = getSharedPreferences("MyData", Context.MODE_PRIVATE);
                    SharedPreferences.Editor editor = sharedPreferences.edit();
                    editor.putString("position", Long.toString(id));
                    editor.commit();

You can retrieve the saved value as shown below:

SharedPreferences sharedPreferences = getSharedPreferences("MyData", Context.MODE_PRIVATE);
        String position = sharedPreferences.getString("position", "0");

You can use as it suits you.

Hope this helps you.

keshav kowshik
  • 2,354
  • 4
  • 22
  • 45