Skip to content

Instantly share code, notes, and snippets.

@bng86
Last active December 7, 2016 09:10
Show Gist options
  • Save bng86/7d575be14c220917c8fdd9c5d27ca698 to your computer and use it in GitHub Desktop.
Save bng86/7d575be14c220917c8fdd9c5d27ca698 to your computer and use it in GitHub Desktop.
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:padding="16dp"
android:orientation="vertical">
<EditText
android:id="@+id/editName"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:hint="Name"/>
<Button
android:id="@+id/buttonSend"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="send"/>
</LinearLayout>
public class PreferenceActivity extends AppCompatActivity {
private static final String KEY_NAME = "name";
private static final String KEY_ID = "id";
private static final String KEY_AGE = "age";
private static final String PREFERENCES_NAME = "mcu";
@Override
protected void onCreate(@Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_preferences);
// define shared preferences
final SharedPreferences sharedPreferences = getSharedPreferences(PREFERENCES_NAME, Context.MODE_PRIVATE);
final EditText editName = (EditText) findViewById(R.id.editName);
// get name data
String name = sharedPreferences.getString(KEY_NAME, "default value");
editName.setText(name);
Button buttonSend = (Button) findViewById(R.id.buttonSend);
buttonSend.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
// click event
// shared preferences support type String int boolean float long String Set
// saved name data
sharedPreferences
.edit()
//key, value
.putString(KEY_NAME, editName.getText().toString())
.apply();
}
});
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment