How to use shared preference to send data from activity to fragment? - java

I'm trying to send integer value from activity to a fragment to change text size value, Iv tried user bundle and custom constructor and didn't work.
So how can I use shared preferences for this purpose?

Hey have you tried something like this
Bundle bundle=new Bundle();
bundle.put('key',0);
FragmentName name=new FragmentName();
name.setArguements(bundle);
Integer q=getArguments.getInt(key)

If you insist on shared preference use this code :
To save the data
private void saveSp(String key , String value){
PreferenceManager.getDefaultSharedPreferences(Context)
.edit()
.putString(key, value).apply();
}
To get your data:
PreferenceManager.getDefaultSharedPreferences(Context).getString("string", "default")

Related

How to send an object from imported package to another Activty

I've made an activity (A) that recovers a List<Event> from Google Calendar API in an AsyncTask, and then sends it from (A) to (B). The list isn't empty when putting it into the bundle:
bundle.putSerializable(KEY_EVENTS_LIST, (Serializable) items);
but it's null when I recover it in (B)
Bundle b = getIntent().getExtras();
eventList = (List<Event>) b.getSerializable(MainActivity.KEY_EVENTS_LIST);
I don't know which other way I could send it from (A) to (B), or if I could send the List directly to B from the AsyncTask.
You can send serialized array list (ArrayList) using intent from Activity A to Activity B
Intent intent = new Intent(context, B.class);
intent.putExtra("list", serializedArrayListObject);
activity.startActivity(intent);
In Activity B in onCreate method
ArrayList<Event> list=getIntent().getSerializableExtra("list");
to get list from intent
The WorkAround you can do to tackle this creates an Event Class in your project with all the attributes of Event(another package) class and make your Event class a paracalable.
Before setting list to bundle convert it to your list and pass this list.
This is not a good solution but up to my knowledge it will work perfectly.
Hope this will help you.
If you want to save the List in background while sending it to the other activity, you can use sharedPreferences for that as shown below:-
1) You cannot directly save an arrayList in SharedPreferences, so you need to convert it to a set first by:-
Set<String> set = new HashSet<String>();
set.addAll(Your_ArrayList);
2) Save it using sharedPreferences:-
SharedPreferences.Editor editor = getSharedPreferences(MY_PREF_STRING, MODE_PRIVATE).edit();
editor.putStringSet("Key", set);
editor.apply();
where MY_PREF_STRING is declared globally as public static final String MY_PREF_STRING = "MY_PREF";
Retrieve this using
1) In another activity where you want to retrieve this just paste the code given below:-
SharedPreferences preferences = getSharedPreferences(MY_PREF, MODE_PRIVATE);
Set<String> set2 = new HashSet<String>();
set2 = preferences.getStringSet("Key", Collections.singleton("0"));
2) You can again convert this to arrayList using:-
ArrayList<String> array = new ArrayList<String>();
array.addAll(set2);

Variables don't get changed after going back

I have a boolean variable public static boolean isInDarkTheme but when I try to change the value in my settings activity it only gets changed tempolarily.
I did it so:
if (on) {
//Do something when Switch button is on/checked
MainActivity.isInDarkTheme = true;
} else {
//Do something when Switch is off/unchecked
MainActivity.isInDarkTheme = false;
}
Log.d("DarkTheme", "SETTINGS " + MainActivity.isInDarkTheme);
in my settings the variable is changed but when I go back to my main with the
arrow I created with this:
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
picture with this button
it is still the same in the main
but! when I use my software key to get back to the MainActivity it get saved
picture with software back key
Any idea what I can do that it get saved with the other button?
your variable will not be saved and will be collected by garbage collector once the activity is destroyed.
you have to use something like SharedPreferences.
to save the variable
SharedPreferences sharedPrefrences = getSharedPreferences("pref_name", MODE_PRIVATE);
sharedPrefrences.edit().putBoolean("isDarkTheme", true).apply();
to load
SharedPreferences sharedPrefrences = getSharedPreferences("pref_name", MODE_PRIVATE);
// key , default value
boolean isDark= sharedPrefrences.getBoolean("isDarkThem", false);
read about SharedPreferences here
The most likely reason is that both activities are loaded by different class loaders with the effect that the MainActivity you "see" in your Settings activity is a different one than the one you "see" in your other activity. You can find that out by logging the classloader "attached" to the MainActivity by calling MainActivity.class.getClassLoader()

Pass data from listview to field in other class

I have a listview in a class that should pass data to another class however it seems I am doing it wrong. Class A contains the listview and through an intent it sends the data back. Class B must receive the data and pass to a field. For that I use a bundle which contain the string and must pass it. However it seems I am doing something wrong. Any hints?
Class A.
public static final String Item = "shop";
listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
String item3 = (String)arrayAdapter.getItem(position).toString();
Intent intent = new Intent(getActivity().getApplicationContext(),ClassB.class);
intent.putExtra(Item,item3);
startActivity(intent);
//Toast.makeText(getActivity().getApplicationContext(), "msg msg", Toast.LENGTH_LONG).show();
}
});
Class B.
Bundle argsss = new Bundle();
argsss = getActivity().getIntent().getExtras();
if(argsss != null){
String shop = argsss.getString(ClassA.Item);
testButton.setText(shop);
}
Stacktrace :
Process: nl.boydroid.loyalty4g.app, PID: 27526
android.content.ActivityNotFoundException: Unable to find explicit activity class {nl.boydroid.loyalty4g.app/nl.boydroid.loyalty4g.app.redeempoints.RedeemItemFragment}; have you declared this activity in your AndroidManifest.xml?
at android.app.Instrumentation.checkStartActivityResult(Instrumentation.java:1636)
at android.app.Instrumentation.execStartActivity(Instrumentation.java:1430)
at android.app.Activity.startActivityForResult(Activity.java:3532)
at android.app.Activity.startActivityForResult(Activity.java:3493)
at android.support.v4.app.FragmentActivity.startActivityFromFragment(FragmentActivity.java:849)
at android.support.v4.app.Fragment.startActivity(Fragment.java:880)
at nl.boydroid.loyalty4g.app.redeempoints.SearchableShopList$1.onItemClick(SearchableShopList.java:90)
at android.widget.AdapterView.performItemClick(AdapterView.java:308)
at android.widget.AbsListView.performItemClick(AbsListView.java:1524)
at android.widget.AbsListView$PerformClick.run(AbsListView.java:3531)
at android.widget.AbsListView$3.run(AbsListView.java:4898)
at android.os.Handler.handleCallback(Handler.java:733)
at android.os.Handler.dispatchMessage(Handler.java:95)
at android.os.Looper.loop(Looper.java:136)
at android.app.ActivityThread.main(ActivityThread.java:5586)
at java.lang.reflect.Method.invokeNative(Native Method)
at java.lang.reflect.Method.invoke(Method.java:515)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1268)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1084)
at dalvik.system.NativeStart.main(Native Method)
This should work:
String shop = getActivity().getIntent().getStringExtra(ClassA.Item);
Problem with your code it that you're binding String into Intent object directly and not into Bundle. This is reason why your code is not working. Your Bundle is empty.
you have sent data through the intent not bundle so get the data in other activity as intent
String shop = getActivity().getIntent().getStringExtra(ClassA.Item);
note: Im not that knowledgeable in android so i dont know about Bundle class nor Intent class just want to share some thoughts.
Try this.
String shop = argsss.getString("shop");
the value of the Item which is your key (shop) because of this.
public static final String Item = "shop";
look at this ,
//you are putting or passing the value of item3 to Item which is your key named "shop"
intent.putExtra(Item,item3);
so you can only get the value using the key you set.
Update
try this
// first create a bundle for you to be able to use it later.
Bundle sampleBundle = new Bundle();
// then set the values you want. with the Item key.
sampleBundle.putString(Item, item3);
// then create the intent
Intent intent = new Intent(getActivity().getApplicationContext(),ClassB.class);
// then put your bundle to intent.
intent.putExtras(sampleBundle);
startActivity(intent);
to get this try this.
Bundle bundle = this.getIntent().getExtras();
if(bundle !=null){
//Obtain Bundle
String strdata = bundle.getString("shop");
//do the process
}
note again: i havent compile it i dont have ide for android its just a hint.
or
if you want to use only intent to pass some value
use your code above then on the other class you can get it by :
Intent intent = getIntent();
//this is how you retrieve the data
String shop = intent.getStringExtra("shop");
Additional ref.
Intent
Fragment to Fragment Try this dude. :)
Fragment to Fragment . Look at the last answer it may help you finding some ways on how fragments work.
Another possible solution
Passing data fragment to fragment
Additional info.
I think you cant pass data from fragment to another fragment directly.
Often you will want one Fragment to communicate with another, for
example to change the content based on a user event. All
Fragment-to-Fragment communication is done through the associated
Activity. Two Fragments should never communicate directly.
Based on Fragment Documentation.
Question.
//note: not sure about the flow of the program. just want to ask.
ClassA extends Activity ClassB extends Activity
|| ||
ClassA call the FragmentClassA? FragmentClassB startActivity(ClassB)?
|| ||
FragmentClassA you want to pass data --> ? FragmentClassB
after that, you want to start the ClassB Activity class inside FragmentClassB?
Bundle add the object as serializable and send it to another fragment.

Why do i get the default value back?

On my SettingsActivity i am saving a value with the following code:
SharedPreferences.Editor editor = getPreferences(MODE_PRIVATE).edit();
editor.putString("ClassName", strArrClasses.get(i));' // i is a variable inside a loop
int intClassID = i+1;
editor.putInt("ClassID", intClassID);
editor.commit();
I'm now trying to get the value of the SharedPreference with the Key "ClassID" on my MainActivity with the following code:
SharedPreferences sharedPrefs = getPreferences(MODE_PRIVATE);
int intClassID = sharedPrefs.getInt("ClassID", 543548564);
My problem now is that I cant access the class ID and I am always getting the default value.
Edit:
I already checked if i can get the ClassID on my SettingsActivity and that works well
use getSharedPreferences instead. Like
SharedPreferences sharedPrefs = getSharedPreferences(name, MODE_PRIVATE);
as from document here
getPreferences retieves a SharedPreferences object for accessing
preferences that are private to this activity. This simply calls the
underlying getSharedPreferences(String, int) method by passing in this
activity's class name as the preferences name.
and getSharedPreferences retrieve SharedPreference by the name.
In your case you used getPreferences which returned SharedPreferences of those activities only.

Global EditText Variables

I'm writing my first android app, and I have an EditText object that I want to be read across my entire program (multiple activities). I'd like to take in a user's name on one screen/activity/layout and read it in several others to manipulate or display it, so I've found that the string needs to be public and static, and that there should be a class with my global variables. What is the correct way to do this? I've tried using bundles and several other methods, but none seem to work.
You should definitely be passing this value through intents.
Intent intent = new Intent(getApplicationContext(),NEXTCLASS.class);
intent.putExtra("username",mEditText1.getText().toString());
startActivity(intent);
and then to receive it in the next class
Bundle extras = intent.getExtras();
mEditText1.setText(extras.getString("username"))
You could also use shared preferences however I think that is unnecessary for your situation as you do not need the username to persist when the app is closed.
Update:
To use shared prefs..
SharedPreferences sharedPreferences = getSharedPreferences("myprefs", MODE_PRIVATE);
SharedPreferences.Editor editor = sharedPreferences.edit();
editor.putString("username", myusername);
To read from shared prefs...
SharedPreferences sharedPreferences = getSharedPreferences("myprefs", MODE_PRIVATE);
String username = sharedPreferences.getString("username", "");
An example of using a static property
public class utility {
public static String USERNAME = "username";
}
To invoke you do not need to instantiate the class just do this from each class that needs it
String username = sharedPreferences.getString(utility.USERNAME, "")
You can use SharedPreferences to store the value. Read more here.

Categories