Passing multiple strings to SharedPreferences - android

I want to store three strings as user preferences for my app. I have a nice layout already set up, it's just a matter of saving the strings to the SharedPreferences. I would also like to know how I can retrieve these strings in the next activity. Below is my current code, I would greatly appreciate it if someone could show me how I can add this functionality to the code. This is a roadblock in my app I have been trying to get past for a few days now.
Code for main activity:
package com.amritayalur.mypowerschool;
import android.app.Activity;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.SharedPreferences.Editor;
import android.os.Bundle;
import android.preference.PreferenceActivity;
import android.preference.PreferenceManager;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
public class MyPowerSchoolActivity extends Activity {
Button buttonSubmit;
TextView textViewTitle;
TextView textViewDesc;
EditText editTextURL, editTextUser, editTextPass;
String str;
String username;
String password;
String url;
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
buttonSubmit = (Button) findViewById(R.id.buttonSubmit);
textViewTitle = (TextView) findViewById(R.id.textViewTitle);
textViewDesc = (TextView) findViewById(R.id.textViewDesc);
editTextURL = (EditText) findViewById(R.id.editTextURL);
editTextUser = (EditText) findViewById(R.id.editTextUser);
editTextPass = (EditText) findViewById(R.id.editTextPass);
//Start TextView
textViewTitle.setText("MyPowerSchool");
//button listener
buttonSubmit.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v)
{
if ( ( !editTextURL.getText().toString().equals("")) && (
!editTextUser.getText().toString().equals("")) && (
!editTextPass.getText().toString().equals("") ) )
{
url = editTextURL.getText().toString();
username = editTextUser.getText().toString();
password = editTextPass.getText().toString();
// TODO Auto-generated method stub
//Intent i = new Intent( MyPowerSchoolActivity.this,
creds.class);
//startActivity(i);
}
};
});}}

Just set up these class variables in the Activities you want to use SharedPreferences:
public static String MY_PREFS = "MY_PREFS";
private SharedPreferences mySharedPreferences;
int prefMode = Activity.MODE_PRIVATE;
And then to store string values:
SharedPreferences.Editor editor = mySharedPreferences.edit();
editor.putString("key1", "value1");
editor.putString("key2", "value2");
editor.putString("key3", "value3");
editor.commit(); // persist the values
To read them in another Activity/class:
mySharedPreferences = getSharedPreferences(MY_PREFS, prefMode);
String string1 = mySharedPreferences.getString("key1", null);
String string2 = mySharedPreferences.getString("key2", null);
This is not hard to look up and find examples of. By going to the documentation in Android Developers you will find a link to this useful site on how to use data storage on Android phones.

Somehow define your preference fields names. It is common practive to do it via final static field. It can be done in your activity class in some separate class. Give them some uniq names.
public static final String MY_PARAM_1 = "com.amritayalur.mypowerschool.PARAM_1";
public static final String MY_PARAM_2 = "com.amritayalur.mypowerschool.PARAM_2";
Get shared preference instance
// "this" is your activity or context
SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(this);
To put your strings in preferenes you need to create an editor
SharedPreferences.Editor editor = prefs.edit();
Then put your values
editor.putString(MY_PARAM_1, "First string");
editor.putString(MY_PARAM_2, "Second string");
Then you are done, commit your changes
editor.commit();
To get your values back use the getString method
// specify default value in case if preferences are empty or current key is not set
prefs.getString(MY_PARAM_1, "default value");

You can add multiple values like this:
preferences.edit()
.putLong(DAYS_LEFT, premiumStatus.getDaysLeft())
.putString(KEY, premiumStatus.getKey())
.putString(ID, premiumStatus.getId())
.apply();

First setup shared preference. For this, set this line before on create :
private Context mContext;
then put this in oncreate :
mContext = this;
Then store your value on SharedPreferece:
SharedPreferences settings =
PreferenceManager.getDefaultSharedPreferences(mcontext);
SharedPreferences.Editor editor = settings.edit();
url = editTextURL.getText().toString();
username = editTextUser.getText().toString();
password = editTextPass.getText().toString();
editor.putString("kye1", url);
editor.putString("kye2", username);
editor.putString("kye3", password);
Then retrieve your Value from another class (or from any where ) :
SharedPreferences settings = PreferenceManager.getDefaultSharedPreferences(mcontext);
String value1=settings.getString("key1",""); // for url
String value2=settings.getString("key2",""); // for name
String value3=settings.getString("key3",""); // for password
Then set this "value1/2/3" any where.

Related

Call another class and getText

public class ustawienia extends MainActivity {
EditText kryptonim;
public String test;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.ustawienia);
kryptonim = (EditText) findViewById(R.id.edit_kryptonim);
test = kryptonim.getText().toString();
}
public String call_back(){
return test;
}
}
When call call_back() from another class I've got error: Unable to start activity ComponentInfo. What's wrong with that?
When you close an activity all data from it is lost, so unless both activities are runing at the same time you can't retrieve data. You could use shared prefrences instead.
// IN ORDER TO WRITE TO A FILE
SharedPreferences.Editor prefs = getSharedPreferences("PrefsName", MODE_PRIVATE).edit();
prefs.putString("test", kryptonim.getText().toString());
prefs.apply(); // use prefs.commit(); if this doesn't work
In order to read data
SharedPreferences prefsR = getSharedPreferences("PrefsName", MODE_PRIVATE); // you could also write 0 instead MODE_PRIVATE
String restoredText = prefsR.getString("test", null);
Ofcourse you need to import SharedPrefs , and put this in oncreate or wherever you want... let me now if it works :)

how to pass extra intent to two activities

i have an app that on the first activity asks the persons name on the second page it displays the name in a sentence i want to use the name in the third fourth or 9th activity how do i properly declare it (public?) and call it when and where ever i need it? this is my code sending it
Main
public class MainActivity extends Activity {
Button ok;
EditText name;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
name=(EditText)findViewById(R.id.editText);
Typeface font_a = Typeface.createFromAsset(getAssets(),"fonts/MarkerFelt.ttf");
name.setTypeface(font_a);
ok=(Button)findViewById(R.id.button);
Typefacefont_b=Typeface.createFromAsset(getAssets(),
"fonts/SignPaintersGothicShaded.ttf");
ok.setTypeface(font_b);
ok.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View arg0) {
String nameStr = name.getText().toString();
Intent intent = new Intent(getApplicationContext(), SecondActivity.class);
intent.putExtra("NAMEDATA",nameStr);
startActivity(intent);
}
});
}
and this is activity 2 receiving it
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_second);
t = (TextView)findViewById(R.id.textView3);
Typeface font_b = Typeface.createFromAsset(getAssets(),"fonts/MarkerFelt.ttf");
t.setTypeface(font_b);
String n = this.getIntent().getStringExtra("NAMEDATA");
t.setText(n);
so please how would i reuse this?
Use SharedPreferences to save the name or whatever variable you need, then read whenever you need it. First, create global in MainActivity which will be used as preference file name:
public static final String PREFS_NAME = "MyPrefsFile";
Then, to save:
SharedPreferences settings = getSharedPreferences(PREFS_NAME, Context.MODE_PRIVATE);
SharedPreferences.Editor editor = settings.edit();
editor.putString("name", name);
editor.commit();
to load:
SharedPreferences settings = getSharedPreferences(PREFS_NAME, Context.MODE_PRIVATE);
String name = settings.getString("name", "John");
Once saved, the prefs are accessible for every activity.
So in your case, save the name when ok button is pressed:
ok.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View arg0) {
String nameStr = name.getText().toString();
SharedPreferences settings = getSharedPreferences(PREFS_NAME, Context.MODE_PRIVATE);
SharedPreferences.Editor editor = settings.edit();
editor.putString("name", nameStr);
editor.commit();
Intent intent = new Intent(getApplicationContext(), SecondActivity.class);
startActivity(intent);
}
});
Then read it:
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_second);
t = (TextView)findViewById(R.id.textView3);
Typeface font_b = Typeface.createFromAsset(getAssets(),"fonts/MarkerFelt.ttf");
t.setTypeface(font_b);
SharedPreferences settings = getSharedPreferences(PREFS_NAME, Context.MODE_PRIVATE);
String n = settings.getString("name", "defaultName");
t.setText(n);
You can do similarly in every activity you need it. See docs here.
You have a number of different approaches to share data between activities. I would say which one you use depends on the ultimate source and destination of the data.
Pass through intents - This is the method you are currently using. To proceed, just keep passing the name to the next intent.
Save to SharedPreference - This method you save the information to the "preference" file of the application. This is useful if the the user is setting up a profile or other semi-fixed information.
Write it to a DB - Here you would create a a new SQLite table for user information and write new rows to it for the name, password, and other info. This has way more overhead and is really only useful if you have multiple users in the same application
Save to a singleton - In this case you create a static class with public properties that can be set. This would be least favorable all the information is lost on application close, but could be useful for temporary creation and retention across many activities. Be warned: bad programming can make singletons a nightmare
Create class extending from Application class.
Implement setter and getter inside that class like,
public class GlobalClass extends Application {
//create setters and getters here
public void setUserInfo(String userInfo) {
}
public void getUserInfo() {
return userInfo;
}
}
then you can use this from any activity like,
GlobalClass app = (GlobalClass ) getApplication();
app.getUserInfo();

Shared Preferences overwrite last value on every key before commit() or Apply()

I'm trying to save two Boolean value over two different keys but every-time when i save value in the key it overwrites key with last value only.
Below is the function call to save the value
AssignRegistrationFun manage =
new AssignRegistrationFun(getApplicationContext());
manage.ChangeDataState(false,true);
Below is the function call in if condition to check the data state...
at this function call it returns true even though i set the first value to false
if(manage.checkDataChanged("External"))
below is function definition with class details
import android.content.Context;
import android.content.SharedPreferences;
import android.content.SharedPreferences.Editor;
public class AssignRegistrationFun {
SharedPreferences pref;
Editor editor;
Context _context;
int PRIVATE_MODE = 0;
private static final String PREF_NAME ="Tester";
private static final String EXTERNAL_DATA = "true";
private static final String INTERNAL_DATA = "true";
public AssignRegistrationFun(Context context){
this._context = context;
pref = _context.getSharedPreferences(PREF_NAME, PRIVATE_MODE);
editor = pref.edit();
}
public void ChangeDataState(boolean EX_state,boolean IN_state){
editor.putBoolean(EXTERNAL_DATA,EX_state);
editor.putBoolean(INTERNAL_DATA,IN_state);
editor.commit();//even editor.apply() not works
}
public boolean checkDataChanged(String type){
if(type.equals("External"))
return pref.getBoolean(EXTERNAL_DATA,false);
else
return pref.getBoolean(INTERNAL_DATA,false);
}
}
please help me out thanks in advance...
Both your EXTERNAL_DATA and INTERNAL_DATA are set to the same string value: "true", so when you assing to one, you overwrite the value of the other.
Solution: use different values, e.g.:
private static final String EXTERNAL_DATA = "external";
private static final String INTERNAL_DATA = "internal";

Shared Preference Force close

My Program gets Force closed when i execute this code.. can anyone tell me..whats the solution..
package com.test.sharedPreferences;
import android.app.Activity;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.widget.TextView;
public class Sharedpreference extends Activity {
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
SharedPreferences pref = getSharedPreferences("Preference",MODE_WORLD_READABLE);
SharedPreferences.Editor editor = pref.edit();
editor.putBoolean("keyBoolean", true);
editor.putFloat("keyFloat", 1.0f);
editor.putInt("keyInt", 1);
editor.putLong("keyLong", 1000000L);
editor.putString("keyString", "Hello Android");
editor.commit();
// boolean dataFromPrefBool = pref.getBoolean("keyBoolean", false);
// float dataFromPrefflaot = pref.getFloat("keyFloat", 0.0f);
int dataFromPrefInt = pref.getInt("keyInt", 0);
// long dataFromPrefLong = pref.getLong("keyLong", 0);
// String dataFromPrefString = pref.getString("keyString", null);
TextView tv = new TextView(this);
tv.setText(dataFromPrefInt);
setContentView(tv);
}
}
I would use Context.MODE_PRIVATE
When you write getInt....that means you are opening the editor.
So first open the editor and den write the getInt code.
SharedPreferences pref = getSharedPreferences("Preference",MODE_WORLD_READABLE);
int dataFromPrefInt = pref.getInt("keyInt", 0);
Here's your problem. You're opening up the shared preferences using MODE_WORLD_READABLE (ie, read-only mode) here:
SharedPreferences pref = getSharedPreferences("Preference",MODE_WORLD_READABLE);
and then following that up by trying to EDIT the shared preferences here:
SharedPreferences.Editor editor = pref.edit();
editor.putBoolean("keyBoolean", true);
...
editor.commit();
Doesn't something about that seem incorrect to you? If not, here's the documentation to clarify things.

Using shared preferences editor

I'm slowly working through an Android learning book and was given the following code to assign user data:
package com.androidbook.triviaquiz;
import android.app.Activity;
import android.content.SharedPreferences;
public class QuizActivity extends Activity {
public static final String GAME_PREFERENCES = "GamePrefs";
SharedPreferences settings = getSharedPreferences(GAME_PREFERENCES, MODE_PRIVATE);
SharedPreferences.Editor prefEditor = settings.edit();
prefeditor.putString("UserName", "John Doe"); //**syntax error on tokens**
prefEditor.putInt("UserAge", 22); //**syntax error on tokens**
prefEditor.commit();
}
However, I get an error (lines indicated with comments) that underlines the period and says "misplaced construct" and also that underlines the arguments saying "delete these tokens". I have seen this done in other applications in the same format, I don't understand what is wrong.
Edit: Of course! Those statements cannot be put directly into the class at that level and must be inside a method, something like this:
public class QuizActivity extends Activity {
public static final String GAME_PREFERENCES = "GamePrefs";
#Override
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
SharedPreferences settings = getSharedPreferences(GAME_PREFERENCES, MODE_PRIVATE);
SharedPreferences.Editor prefEditor = settings.edit();
prefEditor.putString("UserName", "John Doe");
prefEditor.putInt("UserAge", 22);
prefEditor.putString("Gender", "Male");
prefEditor.commit();
}
}
I think you may missed up OnCreate() method ,let be sure you should place the shared preference in your OnCreate() method... i just edited your code go through it
please go through the code...below
public class A extends Activity {
static SharedPreferences settings;
public static final String PREFS_NAME = "YourPrefName";
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
settings = getSharedPreferences(PREFS_NAME, 0);
Log.v("UserName"," - "+settings.getString("username","android"));
SharedPreferences.Editor editor = settings.edit();
editor.putString("username","Change Android");
editor.commit();
Log.v("UserName after changed editing preference key value"," - "+settings.getString("username","android"));
}
}
SharedPreferences will work out side a onCreate() method as long as it has a context:
SharedPreferences settings = getAplicationContext().getSharedPreferences(GAME_PREFERENCES, MODE_PRIVATE);

Categories

Resources