Click here to Skip to main content
65,938 articles
CodeProject is changing. Read more.
Articles / Mobile / Android

Shared Preferences and Yes/No Alert Dialog in Android

4.75/5 (3 votes)
1 Apr 2013CPOL1 min read 19.3K  
In this post, my intent is to use the internal memory of an android and save / retrieve the data from different views.

In this post, my intent is to use the internal memory of an android and save / retrieve the data from different views.

We have several options to save data on a Android device, like Compact SQL, Files and Shared Preferences.

So, I have a One Page Application, which will accepts name and save it to the internal memory and then retrieves the data to display on second screen.

The markup of view is:

XML
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:paddingBottom="@dimen/activity_vertical_margin"
    android:paddingLeft="@dimen/activity_horizontal_margin"
    android:paddingRight="@dimen/activity_horizontal_margin"
    android:paddingTop="@dimen/activity_vertical_margin"
    tools:context=".MainActivity" 
    android:orientation="vertical">  
    <EditText
        android:id="@+id/editName"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:ems="10" 
        android:hint="Name Here">
        <requestFocus />
    </EditText>
    <Button
        android:id="@+id/btnSAVE"
        style="?android:attr/buttonStyleSmall"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Save" 
        android:onClick="SaveData"/>
    <TextView
        android:id="@+id/lblName"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text=""
        android:textAppearance="?android:attr/textAppearanceMedium" />  
</LinearLayout>

Before looking at SaveData() method, we need to see how to create the shared preference object. We need to create the SharedPrefrence object on OnCreate method of Activity. The Activity Code follows:

Java
package com.example.simplesave;
import android.os.Bundle;
import android.app.Activity;
import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences;
import android.view.Menu;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
public class MainActivity extends Activity {
SharedPreferences prefs;
String SavedNameKey="com.example.simplesave.SavedName";
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState); 
setContentView(R.layout.activity_main);
prefs = this.getSharedPreferences(
      "com.example.simplesave", Context.MODE_PRIVATE);
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
public void SaveData(View v)
{     
EditText txtName= (EditText) findViewById(R.id.editName); 
prefs.edit().putString(SavedNameKey, txtName.getText().toString()).commit();
TextView lblName=(TextView) findViewById(R.id.lblName);
lblName.setText("Name :"+txtName.getText().toString());
final Intent intent=new Intent(this,DisplayMemory.class); 
new AlertDialog.Builder(this)
    .setTitle("Data Saved")
    .setMessage("Are you sure you want to move to next Page to Test Sahred Preference approach?")
    .setPositiveButton("Yes", new DialogInterface.OnClickListener() {
        public void onClick(DialogInterface dialog, int which) {          
    startActivity(intent);
        }
    })
    .setNegativeButton("No", new DialogInterface.OnClickListener() {
        public void onClick(DialogInterface dialog, int which) { 
            // do nothing
        }
    })
    .show();
}
}

So, once the data is saved, the user will be prompted for permission, to move to next page to see what we can retrieve from the Memory. For this we have used.

  • Yes / No AlertDialog

Once the user said No, he will stay on Main Activity and a display message was shown on below of Text field. If the user said Yes, he will be moved to second screen, "Display Memory", where we can retrieve the data from memory and will be displayed using OnCreate method of that screen.

Java
package com.example.simplesave;
import android.os.Bundle;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.view.Menu;
import android.widget.TextView;

public class DisplayMemory extends Activity {
SharedPreferences prefs;
String SavedNameKey="com.example.simplesave.SavedName";
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
//setContentView(R.layout.activity_display_memory);
Intent intent = getIntent();
prefs = this.getSharedPreferences(
      "com.example.simplesave", Context.MODE_PRIVATE);
// Create the text view
    TextView textView = new TextView(this);
    textView.setTextSize(40);
    textView.setText("Data Retrieved from Shared Preferences: "+prefs.getString(SavedNameKey, ""));
    // Set the text view as the activity layout
    setContentView(textView);
}

@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.display_memory, menu);
return true;
}
}

And here are the results . . . 

Default Display:

Input Text:

Button Click:

If user says No:

If user says "Yes":

We will see using Compact SQL to save data in upcoming posts.

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)