Skip to content

Instantly share code, notes, and snippets.

@leonguyen
Created April 17, 2013 08:41
Show Gist options
  • Select an option

  • Save leonguyen/5402780 to your computer and use it in GitHub Desktop.

Select an option

Save leonguyen/5402780 to your computer and use it in GitHub Desktop.
Android Lab: Shared References - Write a MainActivity program
package com.example.androidlab;
import android.os.Bundle;
import android.app.Activity;
import android.content.SharedPreferences;
import android.view.View;
import android.widget.EditText;
import android.widget.Toast;
public class MainActivity extends Activity {
public static final String PREFS_NAME = "AndroidPrefs";
SharedPreferences settings;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
final EditText txtName = (EditText) findViewById(R.id.editTextName);
settings = getSharedPreferences(PREFS_NAME, 0);
View.OnClickListener handler = new View.OnClickListener() {
public void onClick(View v) {
switch (v.getId()) {
case R.id.buttonSave:
String strName = txtName.getText().toString();
txtName.setText("");
SharedPreferences.Editor editor = settings.edit();
editor.putString("name", strName);
editor.commit();
Toast.makeText(MainActivity.this,"You entered: " + strName, Toast.LENGTH_SHORT).show();
break;
case R.id.buttonShow:
String name = settings.getString("name", null);
Toast.makeText(MainActivity.this, "Saved Name is: " + name,Toast.LENGTH_LONG).show();
break;
}
}
};
findViewById(R.id.buttonSave).setOnClickListener(handler);
findViewById(R.id.buttonShow).setOnClickListener(handler);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment