Demo:
1)main.xml:
<?xml version="1.0"
encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:background="#ffffff"
android:orientation="vertical"
>
<TextView
android:id="@+id/textView1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginTop="50dp"
android:text="Enter
Name"
android:textAppearance="?android:attr/textAppearanceLarge"
android:textColor="@color/color_black"
/>
<EditText
android:id="@+id/edt1"
android:layout_width="match_parent"
android:layout_height="wrap_content"
>
<requestFocus />
</EditText>
<Button
android:id="@+id/btnSave"
android:layout_width="100dp"
android:layout_height="wrap_content"
android:layout_gravity="center"
android:text="Save"
/>
<Button
android:id="@+id/btnShowData"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center"
android:layout_marginTop="50dp"
android:text="Show Saved
Data"
android:textSize="15dp"
/>
</LinearLayout>
2)Activity:
package
com.venky.sharedpreferences;
import
android.app.Activity;
import
android.content.SharedPreferences;
import
android.os.Bundle;
import
android.view.View;
import
android.view.View.OnClickListener;
import
android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;
public class
SharedPreferencesActivity extends Activity {
/** Called when the activity is first
created. */
EditText edt1;
@Override
public void onCreate(Bundle
savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
edt1 = (EditText) findViewById(R.id.edt1);
Button btnSave = (Button)
findViewById(R.id.btnSave);
Button btnShowData = (Button)
findViewById(R.id.btnShowData);
btnSave.setOnClickListener(new OnClickListener()
{
@Override
public void onClick(View v)
{
// TODO
Auto-generated method stub
String data = edt1.getText().toString().trim();
SharedPreferences sp =
getSharedPreferences("shared_db", 1);
SharedPreferences.Editor
editor = sp.edit();
editor.putString("data", data);
editor.commit();
Toast.makeText(getApplicationContext(),
"Successfully
Saved your Name", Toast.LENGTH_SHORT)
.show();
edt1.setText("");
}
});
btnShowData.setOnClickListener(new
OnClickListener() {
@Override
public void onClick(View v)
{
// TODO
Auto-generated method stub
SharedPreferences sp =
getSharedPreferences("shared_db", 1);
String savedData =
sp.getString("data", "no value in sp");
Toast.makeText(getApplicationContext(),
"Saved
Name is => " + savedData, Toast.LENGTH_SHORT)
.show();
}
});
}
}
No comments:
Post a Comment