Save user input to SharedPrefernces and set Value to EdiText - android

I want to save user input to SharedPreferences when i click a button so that when a user launches the activity again the user input is set to the EditText and TextView. I already have a sharedPreferences File created that i save some text to in a previous activity.
I want update the SharedPreferences File with another details from this new activity that i created.
This is code for creating and saving to SharedPreferences
private SharedPreferences prefs;
public static final String PREF_FILE_NAME = "AuthUser";
prefs = this.getSharedPreferences(PREF_FILE_NAME, Context.MODE_PRIVATE);
txtDate = (TextView) findViewById(R.id.txtDate);
addIdButton = (Button) findViewById(R.id.btnAddId);
addIdButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
expiryDate = txtDate.getText().toString();
edtIdNumber = (EditText) findViewById(R.id.edtIdNumber);
idNumber = edtIdNumber.getText().toString();
SharedPreferences.Editor editor = prefs.edit();
editor.putInt("idType", idType);
editor.putString("idNumber", idNumber);
editor.putString("expiryDate", expiryDate);
editor.apply();
}
});
This is my code to set the value from shared preferences to EditText and TextView
#Override
public void onStart(){
super.onStart();
File f = new File(PREF_FILE_NAME);
if (f.exists()){
idType = prefs.getInt("idType", 0);
idNumber = prefs.getString("idNumber", "");
expiryDate = prefs.getString("expiryDate", "");
edtIdNumber = (EditText) findViewById(R.id.edtIdNumber);
txtDate = (TextView) findViewById(R.id.txtDate);
txtDate.setText(expiryDate);
edtIdNumber.setText(idNumber);
edtIdNumber.setText(idNumber);
txtDate.setText(expiryDate);
}
}

File f = new File(PREF_FILE_NAME); just has the name of the preference so
f.exists() will always returns false
Solution : Remove
File f = new File(PREF_FILE_NAME);
if (f.exists()){
because if you don't have any value then simply use the default value
#Override
public void onStart(){
super.onStart();
//File f = new File(PREF_FILE_NAME); // not a right path
//if (f.exists()){ // false
idType = prefs.getInt("idType", 0);
idNumber = prefs.getString("idNumber", "");
expiryDate = prefs.getString("expiryDate", "");
edtIdNumber = (EditText) findViewById(R.id.edtIdNumber);
txtDate = (TextView) findViewById(R.id.txtDate);
txtDate.setText(expiryDate);
edtIdNumber.setText(idNumber);
edtIdNumber.setText(idNumber);
txtDate.setText(expiryDate);
//}
}
Alternatively you can use contains

To Achive your work:
First of all try to understand difference between onCreate() and onStart() method of Activity in android, follow following url: https://developer.android.com/guide/components/activities/activity-lifecycle.html
-: use onCreate() method instead of onStart() for setting ui variables;
secondly change in your code like:
public void onClick(View view) {
expiryDate = txtDate.getText().toString();
edtIdNumber = (EditText) findViewById(R.id.edtIdNumber);
idNumber = edtIdNumber.getText().toString();
SharedPreferences.Editor editor = prefs.edit();
editor.putInt("idType", idType);
editor.putString("idNumber", idNumber);
editor.putString("expiryDate", expiryDate);
editor.commit();
}

just remove if (f.exists()) condition from Onstart() because File f = new File(PREF_FILE_NAME); just has the name of the preference so f.exists() will always returns false
like below code
#Override
public void onStart(){
super.onStart();
/* File f = new File(PREF_FILE_NAME);
if (f.exists()){*/
idType = prefs.getInt("idType", 0);
idNumber = prefs.getString("idNumber", "");
expiryDate = prefs.getString("expiryDate", "");
edtIdNumber = (EditText) findViewById(R.id.edtIdNumber);
txtDate = (TextView) findViewById(R.id.txtDate);
txtDate.setText(expiryDate);
edtIdNumber.setText(idNumber);
txtDate.setText(expiryDate);
}

Related

Set space/blank/ null value to default value

I'm new in developing Android application and currently I'm developing a android software that require user to input quite amount of data and save it on sharedPreferences as database. Here is my coding:
public static final String DEFAULT= "NONE";
When saving the data input by the user, a portion of coding are as shown at the following:
public void OnClickSave(){
button17=(Button)findViewById(R.id.button17);
button17.setOnClickListener(
new View.OnClickListener() {
#Override
public void onClick(View v) {
name = (EditText) findViewById(R.id.name);
material = (EditText) findViewById(R.id.material);
type = (EditText) findViewById(R.id.type);
proper1 = (EditText) findViewById(R.id.proper1);
p1 = (EditText) findViewById(R.id.p1);
p2 = (EditText) findViewById(R.id.p2);
p3 = (EditText) findViewById(R.id.p3);
po1 = (EditText) findViewById(R.id.po1);
po2 = (EditText) findViewById(R.id.po2);
po3 = (EditText) findViewById(R.id.po3);
c1 = (EditText) findViewById(R.id.c1);
c2 = (EditText) findViewById(R.id.c2);
c3 = (EditText) findViewById(R.id.c3);
SharedPreferences sharedPreferences = getSharedPreferences("Database", Context.MODE_PRIVATE);
SharedPreferences.Editor editor = sharedPreferences.edit();
editor.putString("name", name.getText().toString());
editor.putString("material", material.getText().toString());
editor.putString("type", type.getText().toString());
editor.putString("proper1",proper1.getText().toString());
editor.putString("p1", p1.getText().toString());
editor.putString("p2", p2.getText().toString());
editor.putString("p3", p3.getText().toString());
editor.putString("po1", po1.getText().toString());
editor.putString("po2", po2.getText().toString());
editor.putString("po3", po3.getText().toString());
editor.putString("c1", c1.getText().toString());
editor.putString("c2", c2.getText().toString());
editor.putString("c3", c3.getText().toString());
editor.commit();
Toast.makeText(MainActivity.this, "Saved!!!", Toast.LENGTH_LONG).show();
}
}
);
}
For loading of data,
public void OnClickLoad(){
button38=(Button)findViewById(R.id.button38);
button38.setOnClickListener(
new View.OnClickListener() {
#Override
public void onClick(View v) {
SharedPreferences sharedPreferences = getSharedPreferences("Database", Context.MODE_PRIVATE);
String name = sharedPreferences.getString("name", DEFAULT);
String material = sharedPreferences.getString("material", DEFAULT);
String type = sharedPreferences.getString("type", DEFAULT);
String proper1 = sharedPreferences.getString("proper11", DEFAULT);
String p1 = sharedPreferences.getString("p1", DEFAULT);
String p2 = sharedPreferences.getString("p2", DEFAULT);
String p3 = sharedPreferences.getString("p3", DEFAULT);
String po1 = sharedPreferences.getString("po1", DEFAULT);
String po2 = sharedPreferences.getString("po2", DEFAULT);
String po3 = sharedPreferences.getString("po3", DEFAULT);
String c1 = sharedPreferences.getString("c1", DEFAULT);
String c2 = sharedPreferences.getString("c2", DEFAULT);
String c3 = sharedPreferences.getString("c3", DEFAULT);
}
}
);
AlertDialog.Builder a_builder = new AlertDialog.Builder(MainActivity12.this);
a_builder.setMessage(
"Data input 1:"+ name + "\n"+ material +"\n"+ type +"\n"+ proper1 +"\n"+
p1+ "\n"+p2 +"\n"+ p3 + "\n"+po1 +"\n"+ po2 +"\n"+po3 +"\n"+ s1 +"\n"+s2 +"\n"+s3 + "\n" )
.setCancelable(false)
.setPositiveButton("Proceed", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
dialog.cancel();
}
})
.setNegativeButton("Return", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
dialog.cancel();
}
})
;
AlertDialog alert= a_builder.create();
alert.setTitle("Checking");
alert.show();
}
When the user didn't input any data and didn't press the save button, the data shows will be the DEFAULT data, which is NONE as set.
public static final String DEFAULT= "NONE";
However, when the user didn't input any data and press the save button, the output of the data become blank.
Here's the question, is that possible to set the blank input or space input to DEFAULT data? (Means when user didn't insert any input(or space only) and save, corresponding data loaded is NONE.)
I been refer to some solution similar to this ,knowing that I can do it manually 1 by 1, but is that any alternative solution to make it faster and put into the Sharepreferances?
Thank in advance for anyone who concern and help ! Sorry for my poor language.
However, when the user didn't input any data and press the save button, the output of the data become blank.
It's empty string "".
Here's the question, is that possible to set the blank input or space input to DEFAULT data?
You are doing this wrong way. You should not put the entry into shared preferences, when there's noting entered. Then during read you would get your DEFAULT. So make helper like
protected void storeData(SharedPreferences.Editor editor, String key, EditText et) {
String content = et.getText().toString();
// is there any content? Empty string is no content
if ("".equals(content)) {
// ensure we do not retain previously stored value for that key
editor.remove(key);
} else {
// save new data in the storage
editor.putString(key, content);
}
}
and then replace all the calls you have that put string data directly, like this one:
editor.putString("p1", p1.getText().toString());
with calls to our helper:
storeData(editor, "p1", p1);

android storing values in array or list without overwrite

Am just wondering if there is a way to save data into a text file without being overwritten.
Currently i am using sharedpreferences and it overwrites the data which is okay but coinciding with this, i want somewhere where i can keep record of the value before being overwritten in a list or column form.
So it goes something like this:
60, 65, 70..etc
The values are stored one after another without being overwritten. I am thinking of doing this locally in a text file which can be read as well.
I am doing this so i can create a stats page or something like that.
I hope someone can help me find a solution.
My code:
public class workout extends Activity {
TextView weightresultText, newweightresultText, difficultyrating;
Boolean male, strength;
double newweight, newweight1;
int weight, age;
Button button, button4;
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.workout);
button = (Button) findViewById(R.id.button);
button4 = (Button) findViewById(R.id.button4);
SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(getApplicationContext());
weight = Integer.parseInt(sharedPreferences.getString("storedweight", "Your Weight"));
age = Integer.parseInt(sharedPreferences.getString("storedage", "Your Age"));
male = sharedPreferences.getBoolean("is_male", false);
strength = sharedPreferences.getBoolean("is_strength", false);
weightresultText = (TextView) findViewById(R.id.weightresultLabel);
newweightresultText = (TextView) findViewById(R.id.newweightresultLabel);
difficultyrating = (TextView) findViewById(R.id.difficultylevel);
if (sharedPreferences.getBoolean("firstrun", true)) {AgeCalculation();
sharedPreferences.edit().putBoolean("firstrun", false).commit();}
AfterFirstLaunch();
}
public void SaveWeight(){
savePreferences("storednewweight", (Double.toString(newweight)));
}
//Should only happen on first launch.
public void AgeCalculation() {
if (strength == true){
if (male == true && age >= 18) {
newweight = (weight * 0.8);
}
if (male == true && age >= 30) {
newweight = (weight * 0.6);
}
if (male == true && age >= 50) {
newweight = (weight * 0.4);
}
if (male == true && age >= 70) {
newweight = (weight * 0.2);
}
if (male == true && age > 80) {
newweight = (weight * 0.1);
}
if (male == false && age >= 20 ){
newweight = (weight * 0.3 );
}
weightresultText.setText(Double.toString(newweight));
SaveWeight();
}}
private void savePreferences(String key, String value) {
SharedPreferences sharedPreferences = PreferenceManager
.getDefaultSharedPreferences(this);
SharedPreferences.Editor editor = sharedPreferences.edit();
editor.putString(key, value);
editor.commit();
}
// On every other launch, it is based on button, the newweight is saved and loaded each time.
public void buttonClick1(){
button.setOnClickListener(new View.OnClickListener() {
public void onClick(View arg0) {
//this gets the current weight based on first time launch.
SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(getApplicationContext());
String newweight = sharedPreferences.getString("storednewweight", "");
newweight1 = Double.parseDouble(newweight);
newweight1 = newweight1 + 5;
//saves value into sharedpreference
savePreferences("storednewweight", (Double.toString(newweight1)));
//save to shared preference, and load value on new launch?
//also store into local database for review later.
difficultyrating.setText("1");
button.setEnabled(false);
button4.setEnabled(false);
//save this data then on new launch it uses this figure.
// so first time it creates then uses this figure for future.
}
});}
public void buttonClick4(){
button4.setOnClickListener(new View.OnClickListener() {
public void onClick(View arg0) {
//this gets the current weight based on first time launch.
SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(getApplicationContext());
String newweight = sharedPreferences.getString("storednewweight", "");
newweight1 = Double.parseDouble(newweight);
newweight1 = newweight1 + 10;
//saves value into sharedpreference
//save to text file in array
savePreferences("storednewweight", (Double.toString(newweight1)));
difficultyrating.setText("2");
button.setEnabled(false);
button4.setEnabled(false);
//save this data then on new launch it uses this figure.
// so first time it creates then uses this figure for future.
}
});}
//runs on every other launch
public void AfterFirstLaunch(){
buttonClick1();
buttonClick4();
//receive value on other launches and show on field.
SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(getApplicationContext());
String newweight = sharedPreferences.getString("storednewweight", "");
weightresultText.setText(newweight);
}
}
For something like this, where you're storing multiple entries of similar data, you'd really want to use an SQL database with a content provider. You'd just create new rows for each entry.
For writing into a textFile with overwritten use the following code
File sdCard = Environment.getExternalStorageDirectory();
String path = sdCard.getAbsolutePath() + "/SO/";
File dir = new File(path);
if (!dir.exists()) {
if (dir.mkdirs()) {
}
}
File logFile = new File(path + "filename.txt");
if (!logFile.exists()) {
logFile.createNewFile();
}
// BufferedWriter for performance, true to set append to file
FileWriter fw = new FileWriter(logFile, true);
BufferedWriter buf = new BufferedWriter(fw);
buf.append("Message");
buf.newLine();
buf.flush();
buf.close();
Make sure you have permission defined in your AndroidManifest.xml
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />

Android: How to store array of strings in SharedPreferences for android

I'm building an app which searches the web using search engine. I have one edittext in my app from which user will search the web. I want to save the search keywords just like browser history does. I'm able to save and display it with the last keyword but I can't increase the number of searches result. I want to display the last 5 searhes. Here is my code :
public class MainActivity extends Activity implements OnClickListener {
Button insert;
EditText edt;
TextView txt1, txt2, txt3, txt4, txt5;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
edt = (EditText) findViewById(R.id.search_word);
txt1 = (TextView) findViewById(R.id.txt1);
txt1.setOnClickListener(this);
insert = (Button) findViewById(R.id.insert);
insert.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
if ((edt.getText().toString().equals(""))) {
Toast.makeText(
getBaseContext(),
"Whoa! You haven't entered anything in the search box.",
Toast.LENGTH_SHORT).show();
} else {
SharedPreferences app_preferences = PreferenceManager
.getDefaultSharedPreferences(MainActivity.this);
SharedPreferences.Editor editor = app_preferences.edit();
String text = edt.getText().toString();
editor.putString("key", text);
editor.commit();
Toast.makeText(getBaseContext(), text, Toast.LENGTH_LONG)
.show();
}
}
});
}
#Override
protected void onStart() {
// TODO Auto-generated method stub
super.onStart();
SharedPreferences app_preferences = PreferenceManager
.getDefaultSharedPreferences(this);
String text = app_preferences.getString("key", "null");
txt1.setText(text);
}
public void onClick(View v) {
String text = txt1.getText().toString();
Toast.makeText(getBaseContext(), text, Toast.LENGTH_SHORT).show();
}
}
Please help me in overcoming this problem.
SAVE ARRAY
public boolean saveArray(String[] array, String arrayName, Context mContext) {
SharedPreferences prefs = mContext.getSharedPreferences("preferencename", 0);
SharedPreferences.Editor editor = prefs.edit();
editor.putInt(arrayName +"_size", array.length);
for(int i=0;i<array.length;i++)
editor.putString(arrayName + "_" + i, array[i]);
return editor.commit();
}
LOAD ARRAY
public String[] loadArray(String arrayName, Context mContext) {
SharedPreferences prefs = mContext.getSharedPreferences("preferencename", 0);
int size = prefs.getInt(arrayName + "_size", 0);
String array[] = new String[size];
for(int i=0;i<size;i++)
array[i] = prefs.getString(arrayName + "_" + i, null);
return array;
}
Convert your array or object to Json with Gson library and store your data as String in json format.
Save;
SharedPreferences sharedPrefs = PreferenceManager.getDefaultSharedPreferences(context);
Editor editor = sharedPrefs.edit();
Gson gson = new Gson();
String json = gson.toJson(arrayList);
editor.putString(TAG, json);
editor.commit();
Read;
SharedPreferences sharedPrefs = PreferenceManager.getDefaultSharedPreferences(context);
Gson gson = new Gson();
String json = sharedPrefs.getString(TAG, null);
Type type = new TypeToken<ArrayList<ArrayObject>>() {}.getType();
ArrayList<ArrayObject> arrayList = gson.fromJson(json, type);
Original answer: Storing Array List Object in SharedPreferences

getString from a few SharedPreferences file and create listView

First - sorry for my english;) I'am writing profile manager for Android and i want getString from a few SharedPreferences file and create listView. It's part of my code:
private static final String PN = "profile_name";
private EditTextPreference editText;
private SharedPreferences preferences;
public class Profile_Preferences extends PreferenceActivity {
...
private void SavePreferences() {
String text= editText.getText().toString();
preferences = getSharedPreferences("Profile_" + text, Activity.MODE_PRIVATE); //Here we created SharedPreferences file with name "Profile_"+ this what user write in editText
SharedPreferences.Editor preferencesEditor = preferences.edit();
preferencesEditor.putString(PN, editText.getText());
preferencesEditor.commit();
Ok. The user was doing a few profile, so we have file for example: Profile_home.xml, Profile_work.xml, Profile_something.xml. Now i wan't create listView with profile name from this file. It's my next Activity:
public class Tab_profiles extends ListActivity {
ArrayList<String> listItems = new ArrayList<String>();
ArrayAdapter<String> adapter;
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.list);
adapter = new ArrayAdapter<String>(this,android.R.layout.simple_list_item_multiple_choice, listItems);
setListAdapter(adapter);
...
public void LoadList() {
//It's a good idea to getString "profile_name" form every xml file with name "Profile_" + "" ?
preferences = getSharedPreferences("Profile_"+ "", Activity.MODE_PRIVATE);
String take_profile_name = preferences.getString("profile_name", null);
listItems.add(take_profile_name );
adapter.notifyDataSetChanged();
}
But this doesn't work... logcat log:
FATAL EXCEPTION: MAIN
java.land.Null.PointerException
at android.widget.ArrayAdaper.createViewFromResource(ArrayAdapter.java:355)
...
I don't now whoat it's wrong...
Please help my:) Thank you for any answers and sorry for my errors in writing and code;)
There are a few problems in your code:
String text = editText.getText().toString();
preferences = getSharedPreferences("Profile_" + text, Activity.MODE_PRIVATE);
SharedPreferences.Editor preferencesEditor = preferences.edit();
preferencesEditor.putString(PN, editText.getText());
If a user types "home" in the EditText, you create a preference file called "Profile_home" and save its name in the same file? You need to save the user generated file names in a different file which has a name you know, so you can access it in your code.
Second problem:
preferences = getSharedPreferences("Profile_" + "", Activity.MODE_PRIVATE);
String take_profile_name = preferences.getString("profile_name", null);
You're trying to open "Profile_" settings. This file does not exist(?). The second parameter of getString must not be null, otherwise you'll add a null-reference to your list of string, which fails. Replace it with an empty string "".
Edit: Here's a little workaround to get all custom named preferences:
private void SavePreferences() {
String text = editText.getText().toString();
preferences = getSharedPreferences("ProfileNames", Activity.MODE_PRIVATE);
SharedPreferences.Editor preferencesEditor = preferences.edit();
// increment index by 1
preferencesEditor.putInt("profile_count", preferences.getInt("profile_count", 0) + 1);
// save new name in ProfileNames.xml with key "name[index]"
preferencesEditor.putString("name" + (preferences.getInt("profile_count", 0) + 1), editText.getText());
preferencesEditor.commit();
}
public void LoadList() {
preferences = getSharedPreferences("ProfileNames", Activity.MODE_PRIVATE);
List<String> profileNames = new LinkedList<String>();
int profileCount = preferences.getInt("profile_count", 0);
for (int i = 1; i <= profileCount; i++) {
profileNames.add(preferences.getString(name + i, ""));
}
listItems.addAll(profileNames);
adapter.notifyDataSetChanged();
}

Retrieving shared prefrences values in another activity

Can anyone tell where i am wrong because its just a simple process but how its not retrieving the values i cant understand and do conditional check over the string variable...
Activity A:-
EditText e = (EditText) findViewById(R.id.editText1);
EditText e1 = (EditText) findViewById(R.id.editText2);
EditText e2 = (EditText) findViewById(R.id.editText3);
EditText e3 = (EditText) findViewById(R.id.editText4);
EditText e4 = (EditText) findViewById(R.id.editText5);
EditText e5 = (EditText) findViewById(R.id.editText6);
EditText e6 = (EditText) findViewById(R.id.editText7);
SharedPreferences myPrefs = getSharedPreferences("myPrefs", Context.MODE_WORLD_READABLE);
SharedPreferences.Editor editor = myPrefs.edit();
editor.putString("text", e.getText().toString());
SharedPreferences myPrefs1 = getSharedPreferences("myPrefs1", Context.MODE_WORLD_READABLE);
SharedPreferences.Editor editor1 = myPrefs1.edit();
editor1.putString("text1", e1.getText().toString());
SharedPreferences myPrefs2 = getSharedPreferences("myPrefs2", Context.MODE_WORLD_READABLE);
SharedPreferences.Editor editor2 = myPrefs.edit();
editor2.putString("text2", e2.getText().toString());
SharedPreferences myPrefs3 = getSharedPreferences("myPrefs3", Context.MODE_WORLD_READABLE);
SharedPreferences.Editor editor3 = myPrefs3.edit();
editor3.putString("text3", e3.getText().toString());
SharedPreferences myPrefs4 = getSharedPreferences("myPrefs4", Context.MODE_WORLD_READABLE);
SharedPreferences.Editor editor4 = myPrefs4.edit();
editor4.putString("text4", e4.getText().toString());
SharedPreferences myPrefs5 = getSharedPreferences("myPrefs5", Context.MODE_WORLD_READABLE);
SharedPreferences.Editor editor5 = myPrefs5.edit();
editor5.putString("text5", e5.getText().toString());
SharedPreferences myPrefs6 = getSharedPreferences("myPrefs6", Context.MODE_WORLD_READABLE);
SharedPreferences.Editor editor6 = myPrefs6.edit();
editor6.putString("text6", e6.getText().toString());
Activity B:-In this activity i am accessing the values and doing the conditional check but only else condition is getting executed on both cases
public class CheckActivity extends Activity{
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
SharedPreferences myPrefs = getSharedPreferences("myPrefs",Context.MODE_PRIVATE);
String restoredText = myPrefs.getString("text", "");
SharedPreferences myPrefs1 = getSharedPreferences("myPrefs1",Context.MODE_PRIVATE);
String restoredText1 = myPrefs1.getString("text1", "");
SharedPreferences myPrefs2 = getSharedPreferences("myPrefs2",Context.MODE_PRIVATE);
String restoredText2 =myPrefs2.getString("text2", "");
SharedPreferences myPrefs3 = getSharedPreferences("myPrefs3",Context.MODE_PRIVATE);
String restoredText3 =myPrefs3.getString("text3", "");
SharedPreferences myPrefs4 = getSharedPreferences("myPrefs4",Context.MODE_PRIVATE);
String restoredText4 = myPrefs4.getString("text4", "");
SharedPreferences myPrefs5 = getSharedPreferences("myPrefs5",Context.MODE_PRIVATE);
String restoredText5 = myPrefs5.getString("text5", "");
SharedPreferences myPrefs6 = getSharedPreferences("myPrefs6",Context.MODE_PRIVATE);
String restoredText6 = myPrefs6.getString("text6", "");
Intent i1 = new Intent();
if((restoredText.length()>1)&&(restoredText1.length()>1)&&(restoredText2.length()>1)&&(restoredText3.length()>1)&&(restoredText4.length()>1)&&(restoredText5.length()>1)&&(restoredText6.length()>1))
{
i1.setClass(this,ShpoonkleActivity.class);
}
//if((restoredText.length()==0)||(restoredText1.length()==0)||(restoredText2.length()==0)||(restoredText3.length()==0)||(restoredText4.length()==0)||(restoredText5.length()==0)||(restoredText6.length()==0))
else
{
i1.setClass(this,Test.class);
}
startActivity(i1);
finish();
}
}
you should commit your data with editor.commit();
NB: in your case , there is no need to use a lot of instances of SharedPreferences , you need just one instance, and then put all your Strings into it , and commit
you should use
editor.commit();
for your changes to be preserved. and also, you need not use different files to store various strings, you can store all the strings in the same shared preferences file.
actually saving edittext's text was creating ambiguity and hence was not executing well so i did this as shown below:-
Activity B:-
protected void onPause() {
EditText ed = (EditText)findViewById(R.id.editText1);
EditText ed1 = (EditText)findViewById(R.id.editText2);
EditText ed2 = (EditText)findViewById(R.id.editText3);
EditText ed3 = (EditText)findViewById(R.id.editText4);
EditText ed4 = (EditText)findViewById(R.id.editText5);
EditText ed5 = (EditText)findViewById(R.id.editText6);
EditText ed6 = (EditText)findViewById(R.id.editText7);
super.onPause();
SharedPreferences myPrefs = getSharedPreferences("myPrefs", Context.MODE_WORLD_READABLE);
SharedPreferences.Editor editor = myPrefs.edit();
editor.putString("text", ed.getText().toString());
editor.putString("text1", ed1.getText().toString());
editor.putString("text2", ed2.getText().toString());
editor.putString("text3", ed3.getText().toString());
editor.putString("text4", ed4.getText().toString());
editor.putString("text5", ed5.getText().toString());
editor.putString("text6", ed6.getText().toString());
editor.commit();
}
Activity A:-
public class CheckActivity extends Activity{
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
SharedPreferences myPrefs = getSharedPreferences("myPrefs",Context.MODE_PRIVATE);
String restoredText = myPrefs.getString("text", "");
String restoredText1 = myPrefs.getString("text1", "");
String restoredText2 =myPrefs.getString("text2", "");
String restoredText3 =myPrefs.getString("text3", "");
String restoredText4 = myPrefs.getString("text4", "");
String restoredText5 = myPrefs.getString("text5", "");
String restoredText6 = myPrefs.getString("text6", "");
Intent i1 = new Intent();
if((restoredText.length()>0)&&(restoredText1.length()>0)&&(restoredText2.length()>0)&&(restoredText3.length()>0)&&(restoredText4.length()>0)&&(restoredText5.length()>0)&&(restoredText6.length()>0))
{
i1.setClass(this,ShpoonkleActivity.class);
}
//if((restoredText.length()==0)||(restoredText1.length()==0)||(restoredText2.length()==0)||(restoredText3.length()==0)||(restoredText4.length()==0)||(restoredText5.length()==0)||(restoredText6.length()==0))
else
{
i1.setClass(this,Test.class);
}
startActivity(i1);
finish();
}
}
And it works awesome ...thnx..

Categories

Resources