strings.xml
Shared Preferences
Save
Retrieve
Your name
Enter your name
Save
Show
activity_main.xml
main_activity.java
import android.app.Activity;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
public class MainActivity extends Activity implements View.OnClickListener {
private EditText saveData;
private TextView retrieveData;
private Button saveBtn;
private Button showBtn;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
retrieveData = (TextView)findViewById(R.id.load_data);
saveData = (EditText)findViewById(R.id.enter_data);
saveBtn = (Button)findViewById(R.id.save);
showBtn = (Button)findViewById(R.id.show);
saveBtn.setOnClickListener(this);
showBtn.setOnClickListener(this);
showBtn.setEnabled(false);
if(retrieveName().length()>0)
showBtn.setEnabled(true);
}
@Override
public void onClick(View v) {
switch(v.getId()) {
case R.id.save:
saveName("name", saveData.getText().toString());
showBtn.setEnabled(true);
break;
case R.id.show:
retrieveData.setText(retrieveName());
break; }
}
private void saveName(String key, String value){
SharedPreferences sharedPreferences = getPreferences(MODE_PRIVATE);
SharedPreferences.Editor editor = sharedPreferences.edit();
editor.putString(key, value);
editor.commit();
}
private String retrieveName(){
SharedPreferences sharedPreferences = getPreferences(MODE_PRIVATE);
String savedData = sharedPreferences.getString("name", "");
return savedData;
}
}