public class MyActivity extends AppCompatActivity implements View.OnClickListener {
public static SharedPreferences settings; // get
private static SharedPreferences.Editor editor; // put
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_login);
settings = getSharedPreferences("mySavedStuff", MODE_PRIVATE);
editor = settings.edit();
if (settings.contains("USERNAME")){
login();
}
btn = (Button) findViewById(R.id.btn);
btn.setOnClickListener(this);
}
@Override
public void onClick(View v) {
EditText username = (EditText) findViewById(R.id.usernameEditText);
String user = username.getText().toString().trim();
if (validate(user)){
editor.putString("USERNAME", user);
editor.putInt("age", 30);
editor.putBoolean("isMale", true);
editor.commit(); // DON'T FORGET THIS LINE!!!
login();
}
}
private void login(){
Intent intent = new Intent(this, ListActivity.class);
startActivity(intent);
}
private boolean validate(String str){
if (str.isEmpty()){
return false;
}
return true;
}
}
//////////////////////////////////////////////
//SharedPreferences Support:
.getInt("data", 1); //get int
.putInt(dara", 1); //put int
.remove("setings to remove"); //delete using the key name
.clear(); //delete all SharedPreferences keys
.apply(); // like commit() but run in different thread (faster) !
Categories: Android Developer