I am trying to get and update the data which I stored in sharedpreferences xml file from a non-activity class.But I dont know how to reach the data stored in sharedPreferences from a non-activity class in android.In my activiy class i can store data in sharedprefences and i also can retrive these data in my activiy class. However i can not retrive these data from a non-activiy class. My code is below.Thank you...
mSharedPrefs = getSharedPreferences("storageforfavorite", 0);
mPrefsEditor = mSharedPrefs.edit();
for(int i= 0;i<names.size();i++){
mPrefsEditor.putString(indexForFav[i],"0");
}
mPrefsEditor.commit();
for(int i=0;i<names.size();i++){
String keyForFav=mSharedPrefs.getString(indexForFav[i], "2");
valueForFav.add(keyForFav);
}
The key is have access to the Context object.
So if you want to use sharedPreferences inside an object, maybe you should pass a Context object in the class constructor. Doing this way you can do this:
SharedPreferences prefs = context.getSharedPreferences();
You'll have to pass a Context to be able to access SharedPreferences from a non-Activity class.
Example:
// mContext => Context-object passed from calling Activity
SharedPreferences mSharedPrefs = mContext.getSharedPreferences("storageforfavorite", 0);
Related
Is it possible to get a sharedprefence data from MainActivity_A and fetch it only to MainActivity_B and the other activities like MainActivity_C and MainActivity_D cannot access the data that has been fetched to MainActivity_B?
Well It totally depends on you wheather you wanna get that data or not..once you store data in shared preference with key then just get that data in the specific activity you want Thats It !!
For Example in Activity X you save the Shared Preference value like this
public static final String SHARED_PREFS = "sharedPrefs";
SharedPreferences sharedPreferences = getSharedPreferences(SHARED_PREFS,MODE_PRIVATE);
SharedPreferences.Editor editor=sharedPreferences.edit();
editor.putString("Key",Value);
Then in Activity A you want to use this value then you can do it like this
SharedPreferences pref;
pref = getSharedPreferences(SHARED_PREFS, Context.MODE_PRIVATE);
String Value = pref.getString("Key");
In This way the value will be stored in variable String
And if you don't want the value in other activity then just don't call it !!
I am using shared preference to store the user details. Now I want to get the value from shared preferences and to display it in cardview. I used
onBindViewHolder(final MyViewHolder holder,final int position)
method to pass data. How it possible to add shared preferences in adapter class?
You can get value by using this and later on you can bind with your componant
Context context = getActivity();
SharedPreferences sharedPref = context.getSharedPreferences(
getString(R.string.preference_file_key), Context.MODE_PRIVATE);
To get instance of SharedPreferences you need context. Pass context from activity/fragment to your adapter. Once you have context, get SharedPreferences instances as below :
SharedPreferences sharedPref = context.getSharedPreferences(
getString(R.string.preference_file_key), Context.MODE_PRIVATE);
Then you can use sharedPref to access your user details.
It will be better if you maintain an instance of your SharedPreferences at your app level so that you are not creating a new instance everywhere you need it.
private SharedPreferences preferences;
in constructor:
preferences = mActivity.getSharedPreferences("pref_name", Context.MODE_PRIVATE);
now you can access it in onBindViewHolder
As shared preference is use for storing key value pairs and i am assuming you are using cardview with recyclerview, so you may need list of values.I think its bad practice and you can use sqlite for same purpose,if you want data from database or else you can get dynamically form api(if your app has backend).
You can use following code to get value from shared preference
SharedPreferences shared = getSharedPreferences(PREF_NAME, MODE_PRIVATE);
String value = (shared.getString(key, ""));
and set this string to cardviews value.
Hey guys I am unable to save a boolean value using SharedPreferences. The value is ALWAYS true for some reasons. Here is how I save the value:
public static void setSharedPreference(Context ctx, String keyValue, boolean value){
SharedPreferences sp = ctx.getSharedPreferences(Constants._preferencesName, Context.MODE_PRIVATE);
SharedPreferences.Editor editor = sp.edit();
editor.putBoolean(keyValue,value);
editor.commit();
}
And this is how I get it back:
public static boolean getBooleanPreference(Context ctx, String keyValue){
boolean prefValue;
SharedPreferences sp = ctx.getSharedPreferences(Constants._preferencesName, ctx.MODE_PRIVATE);
prefValue = sp.getBoolean(keyValue, false);
return prefValue;
}
What is wrong?!
Your code is syntactically correct, but I suspect you are passing different Context while saving than you are passing while reading from prefs. This will result in accessing different shared preferences storage. This is especially easy to step on if you are doing your writes and reads in different activities and decide to pass this as context. Unless there's a reason for doing so then you most likely want to reach your preferences from anywhere in your app then use always application context instead (getApplicationContext()).
Everything is correct in your code.
The ONLY possibility of a mistake is when you are calling these methods. Please use getApplicationContext() while putting and retrieving data.
And please do a "Clear data" for the app and start with a clean SharedPreference.
I am just wondering what would be the better way to handle data in several activities in android.
Say I had two activities, A and B, that hold some views. First I load some data from a SQL database and inflate the views in A. Now, I want to start activity B, which uses the same set of data as A did.
Is it better to pass the data via Intent (putExtra()) and then inflate the views or is it better to query the database again and then inflate.
I am not sure about that, because both approaches seem to have their disadvantages:
Querying the database takes more time /more resources
Putting extra data to the intent makes it more complex, because of putting and getting the data (especially when working with more activities)
Can someone give me some advice on what is the best practice?
As compare to DB Query use Intent.
And another way is, use one common class which will holds your data temporary.
There is various way to pass and get data. It is more useful to use Intent than DB query.
But there is another useful way is shared prefernce. Through which you can create,edit, delete data as well as can fetch data from any of the activity.
To create or edit shared preference:
String share_pref_file = "your_file_name";
SharedPreferences prefs1 = getSharedPreferences(
share_pref_time_file, Context.MODE_PRIVATE);
SharedPreferences.Editor editor1 = prefs1.edit();
editor1.putString("your_data", data); //data is your variable
editor1.commit();
To fetch data:
String share_pref_file = "your_file_name";
SharedPreferences prefs = getSharedPreferences(share_pref_file,
Context.MODE_PRIVATE);
String strJson = prefs.getString("your_data", "");
To delete:
String share_pref_file = "your_file_name";
SharedPreferences prefs1 = getSharedPreferences(
share_pref_file, Context.MODE_PRIVATE);
SharedPreferences.Editor editor = prefs1.edit();
editor.remove(share_pref_file);
editor.clear();
editor.commit();
I would like to be able to transfer data from one activity to another activity. How can this be done?
Through the below code we can send the values between activities
use the below code in parent activity
Intent myintent=new Intent(Info.this, GraphDiag.class).putExtra("<StringName>", value);
startActivity(myintent);
use the below code in child activity
String s= getIntent().getStringExtra(<StringName>);
There are couple of ways by which you can access variables or object in other classes or Activity.
A. Database
B. shared preferences.
C. Object serialization.
D. A class which can hold common data can be named as Common Utilities it depends on you.
E. Passing data through Intents and Parcelable Interface.
It depend upon your project needs.
A. Database
SQLite is an Open Source Database which is embedded into Android. SQLite supports standard relational database features like SQL syntax, transactions and prepared statements.
Tutorials -- http://www.vogella.com/articles/AndroidSQLite/article.html
B. Shared Preferences
Suppose you want to store username. So there will be now two thing a Key Username, Value Value.
How to store
// Create object of SharedPreferences.
SharedPreferences sharedPref = PreferenceManager.getDefaultSharedPreferences(this);
//now get Editor
SharedPreferences.Editor editor = sharedPref.edit();
//put your value
editor.putString("userName", "stackoverlow");
//commits your edits
editor.commit();
Using putString(),putBoolean(),putInt(),putFloat(),putLong() you can save your desired dtatype.
How to fetch
SharedPreferences sharedPref = PreferenceManager.getDefaultSharedPreferences(this);
String userName = sharedPref.getString("userName", "Not Available");
http://developer.android.com/reference/android/content/SharedPreferences.html
C. Object Serialization
Object serlization is used if we want to save an object state to send it over network or you can use it for your purpose also.
Use java beans and store in it as one of his fields and use getters and setter for that
JavaBeans are Java classes that have properties. Think of
properties as private instance variables. Since they're private, the only way
they can be accessed from outside of their class is through methods in the class. The
methods that change a property's value are called setter methods, and the methods
that retrieve a property's value are called getter methods.
public class VariableStorage implements Serializable {
private String inString ;
public String getInString() {
return inString;
}
public void setInString(String inString) {
this.inString = inString;
}
}
Set the variable in you mail method by using
VariableStorage variableStorage = new VariableStorage();
variableStorage.setInString(inString);
Then use object Serialzation to serialize this object and in your other class deserialize this object.
In serialization an object can be represented as a sequence of bytes that includes the object's data as well as information about the object's type and the types of data stored in the object.
After a serialized object has been written into a file, it can be read from the file and deserialized that is, the type information and bytes that represent the object and its data can be used to recreate the object in memory.
If you want tutorial for this refer this link
http://javawithswaranga.blogspot.in/2011/08/serialization-in-java.html
Get variable in other classes
D. CommonUtilities
You can make a class by your self which can contain common data which you frequently need in your project.
Sample
public class CommonUtilities {
public static String className = "CommonUtilities";
}
E. Passing Data through Intents
Please refer this tutorial for this option of passing data.
http://shri.blog.kraya.co.uk/2010/04/26/android-parcel-data-to-pass-between-activities-using-parcelable-classes/
When you passing data from one activity to another activity perform like this
In Parent activity:
startActivity(new Intent(presentActivity.this, NextActivity.class).putExtra("KEY_StringName",ValueData));
or like shown below in Parent activity
Intent intent = new Intent(presentActivity.this,NextActivity.class);
intent.putExtra("KEY_StringName", name);
intent.putExtra("KEY_StringName1", name1);
startActivity(intent);
In child Activity perform as shown below
TextView tv = ((TextView)findViewById(R.id.textViewID))
tv.setText(getIntent().getStringExtra("KEY_StringName"));
or do like shown below in child Activity
TextView tv = ((TextView)findViewById(R.id.textViewID));
TextView tv1 = ((TextView)findViewById(R.id.textViewID1))
/* Get values from Intent */
Intent intent = getIntent();
String name = intent.getStringExtra("KEY_StringName");
String name1 = intent.getStringExtra("KEY_StringName1");
tv.setText(name);
tv.setText(name1);
Passing data from one activity to other in android
Intent intent = new Intent(context, YourActivityClass.class);
intent.putExtra(KEY, <your value here>);
startActivity(intent);
Retrieving bundle data from android activity
Intent intent = getIntent();
if (intent!=null) {
String stringData= intent.getStringExtra(KEY);
int numberData = intent.getIntExtra(KEY, defaultValue);
boolean booleanData = intent.getBooleanExtra(KEY, defaultValue);
char charData = intent.getCharExtra(KEY, defaultValue); }
Hopefully you will find the answer from here Send Data to Another Activity - Simple Android Login
You just have to send extras while calling your intent
like this:
Intent intent = new Intent(getApplicationContext(), SecondActivity.class); intent.putExtra("Variable Name","Value you want to pass"); startActivity(intent);
Now on the OnCreate method of your SecondActivity you can fetch the extras like this
If the value u sent was in "long"
long value = getIntent().getLongExtra("Variable Name which you sent as an extra", defaultValue(you can give it anything));
If the value u sent was a "String"
String value = getIntent().getStringExtra("Variable Name which you sent as an extra");
If the value u sent was a "Boolean"
Boolean value = getIntent().getStringExtra("Variable Name which you sent as an extra",defaultValue);
Your Purpose
Suppose You want to Go From Activity A to Activity B.
So We Use an Intent to switch activity
the typical code Looks Like this -
In Activity A [A.class]
//// Create a New Intent object
Intent i = new Intent(getApplicationContext(), B.class);
/// add what you want to pass from activity A to Activity B
i.putExtra("key", "value");
/// start the intent
startActivity(i);
In Activity B [B.class]
And to Get the Data From the Child Activity
Intent i = getIntent();
if (i!=null) {
String stringData= i.getStringExtra("key");
}
This works best:
Through the below code we can send the values between activities
use the below code in parent activity(PARENT CLASS/ VALUE SENDING CLASS)
Intent myintent=new Intent(<PARENTCLASSNAMEHERE>.this,<TARGETCLASSNAMEHERE>.class).putExtra("<StringName>", value);
startActivity(myintent);
use the below code in child activity(TARGET CLASS/ACTIVITY)
String s= getIntent().getStringExtra(<StringName>);
Please see here that "StringName" is the name that the destination/child activity catches while "value" is the variable name, same as in parent/target/sending class.