Hi I am trying to write a code for persistent/shared preferences. I am successfully saving the data in persistence storage. But every time I start my app it takes me to the storage activity. I have two activities Main Activity and Second Activity. In main activity I am saving the data and second activity I show the stored data. What I want here is when data is stored for the first time it should directly move to second activity. I want to achieve something like watsapp registration process, you enter your number and pin for the first time and it never asks for it until you uninstall app or manually clear data. how can I do so. Below is the code I have tried.
public class MainActivity extends Activity {
public static final String PREFS_NAME = "MSISDN and PIN";
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
final SharedPreferences settings = getSharedPreferences(PREFS_NAME, 0);
int id = settings.getInt("PREFS_NAME", 0);
if (id > 0) {
Intent second = new Intent(getApplicationContext(), seond.class);
startActivity(second);
}
final EditText name = (EditText) findViewById(R.id.editText1);
final EditText email = (EditText) findViewById(R.id.editText2);
Button btn = (Button) findViewById(R.id.btnsaveprefs);
btn.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
SharedPreferences.Editor editor = settings.edit();
editor.putString("MSISDN", name.getText().toString());
editor.putString("PIN", email.getText().toString());
editor.commit();
Intent second = new Intent(getApplicationContext(), seond.class);
startActivity(second);
}
});
}
}
and second activity I have
public class seond extends Activity {
public static final String PREFS_NAME = "MSISDN and PIN";
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.second);
TextView tvname = (TextView) findViewById(R.id.uname);
TextView tvemail = (TextView) findViewById(R.id.uemail);
SharedPreferences settings = getSharedPreferences(PREFS_NAME, 0);
tvname.setText(settings.getString("MSISDN", "Unknown"));
tvemail.setText(settings.getString("PIN", "Email default"));
}
}
That's the correct way to do it:
Notice you did not set the id as said in other answers. Your coding style is bad by the way : NEVER start a class name with lower case letters and also why is
id
an int ? You use it as boolean. Why do you save an email in a preference calledPIN
and a name in a preference calledMSISDN
???