Fragment get the wrong shared preference data - java

I'm storing an ArrayList and Int in Shared Preference, and in fragment i call storage.arraylist().get(storage.int()); to get the position in array but every activity get the right position except the fragment its get the wrong position
My goal is to make the fragment get the right position the int that is stored but he gets the backward of this int, if the int is 15 and the arraylist.size is 16 the fragment gets 14 but in any activity the get 15 position, i tried in fragment to just put in this int + 1 to get the right but the surprise he gets an error because the int it equal to the arraylist.size
Here Where i add an item to the arraylist
storage.storeAudio(CardList.get(position));
if(!app.ismServiceBound()) {
fragment.setSlide_up();
}
app.PlayerBroadCast(1);
fragment.Start();
The storeAudio Method
public void storeAudio(ModelCardView model) {
preferences = context.getSharedPreferences(STORAGE, Context.MODE_PRIVATE);
if (loadAudio() != null) {
arrayList = loadAudio();
}
arrayList.add(model);
SharedPreferences.Editor editor = preferences.edit();
Gson gson = new Gson();
String json = gson.toJson(arrayList);
editor.putString("audioArrayList", json);
editor.apply();
}
The execution of the BroadCast in the first code
//Load data from SharedPreferences
audioList = storage.loadAudio();
audioIndex = audioList.size();
audioIndex--;
if (audioIndex != -1 && audioIndex < audioList.size()) {
//index is in a valid range
activeAudio = audioList.get(audioIndex);
storage.storeAudioIndex(audioIndex);
} else {
stopSelf();
}
In the end the fragment start to get the arraylist and the int to display some info
public void Start(){
if(!app.ismServiceBound()) {
view.setVisibility(View.GONE);
}else if (app.ismServiceBound() && storage.getState()) {
start.setImageResource(R.drawable.play);
view.setVisibility(View.VISIBLE);
}else if(app.ismServiceBound() && !storage.getState()){
start.setImageResource(R.drawable.pause);
view.setVisibility(View.VISIBLE);
}
songName.setText(storage.loadAudio().get(storage.loadAudioIndex()).getId());
bandName.setText(storage.loadAudio().get(storage.loadAudioIndex()).getSinger());
}
but its gets the wrong position i try to use the same code in activity and its work perfect without any problem but i don't know why in this fragment gets a wrong position, and Thanks for helping me.

Related

How to get values from array in strings.xml in order of each day?

I want to get values ​​from an array every day, respectively, and set these values ​​to a textbox. I can get values ​​from array and set them in textbox but next day value stays same. does not set the next value in array? what can I do?
<string-array name="morning">
<item>Good Morning. Message 1.</item>
<item>Good Morning. Message 2.</item>
<item>Good Morning. Message 3.</item>
</string-array>
mTestArray = getResources().getStringArray(R.array.morning);
preference_shared = this.getSharedPreferences("PREFERENCE", MODE_PRIVATE);
text_shared = this.getSharedPreferences("TEXT", MODE_PRIVATE);
Calendar c = Calendar.getInstance();
int timeOfDay = c.get(Calendar.DAY_OF_YEAR);
if (timeOfDay >= 0 && timeOfDay < 24) {
if (preference_shared.getBoolean("isFirstRun", true)) {
dailyGreetings.setText(mTestArray[(0) % (mTestArray.length)]);
saveDate();
}else {
if (!Objects.equals(preference_shared.getString("Date", ""), dateFormat.format(date))) {
int idx = new Random().nextInt(mTestArray.length);
dailyGreetings.setText(mTestArray[idx]);
text_shared.edit().putString("TEXT", dailyGreetings.getText().toString()).apply();
saveDate();
}
else {
dailyGreetings.setText(text_shared.getString("TEXT", ""));
}
}
}
It's Easy just
Resources res = getResources();
String[] mornings = res.getStringArray(R.array.morning);
//then use mornings as you use array.
String morning[] = getResources().getStringArray(R.array.morning);
// Solution
SharedPreferences sharedPreferences = getSharedPreferences("my_preference", MODE_PRIVATE);
SharedPreferences.Editor editor = sharedPreferences.edit();
String currentDate = new SimpleDateFormat("dd-MMM-yyyy", Locale.getDefault()).format(System.currentTimeMillis());
String[] msgArrays = getResources().getStringArray(R.array.morning);
String savedDate = sharedPreferences.getString(DATE_KEY, "");
int savedCounter = sharedPreferences.getInt(COUNTER_KEY, 0);
// First time
if (savedDate.isEmpty()) {
editor.putInt(COUNTER_KEY, savedCounter);
editor.putString(DATE_KEY, currentDate);
editor.apply();
} else if (!savedDate.equals(currentDate)) {
// New date appears, update shared preference.
savedCounter++;
if (savedCounter < msgArrays.length) {
editor.putInt(COUNTER_KEY, savedCounter);
editor.putString(DATE_KEY, currentDate);
editor.apply();
}
}
binding.tvTitle.setText(msgArrays[savedCounter]);
In this snipped of code, I'm updating shared preference by date and counter.
Date: It will be saved for next date, and if these both are not matching, shared preference will gets update with counter.
Counter: The position of your strings-arrays.
Reset: I have add another check that if in case your counter reaches to the end of array, it will be reset to '0'.

Android studio. Bundle returns only the last value from selected

I have a listView with custom adapter, where I have an checkBox and TextView, and when I select some CheckBoxes, I'm adding them into bundle and send into another fragment. In that fragment I have a simple TextView, where I need to get the value from bundle and show in that TextView. But the problem is, that when I'm getting the selected values from bundle and set in TextView, it shows only the last value. How can i solve this? Thank you.
Here the fragment where I'm adding the selected values into bundle.
nextButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
ArrayList<Profession> professionList = dataAdapter.getProfessionList();
ArrayList<String> getProfessions = new ArrayList<>();
personalInfoFragment = new PersonalInfoFragment();
for (int i = 0; i < professionList.size(); i++) {
Profession profession = professionList.get(i);
if (profession.isSelected()) {
getProfessions.add(profession.getName());
Bundle setProfessions = new Bundle();
setProfessions.putStringArrayList("String", getProfessions);
personalInfoFragment.setArguments(setProfessions);
}
}
replaceFragment();
}
});
Ok watch here. the PersonalInfoFragment is the fragment where i need to send the values. And the replaceFragment method replaces the fragment. I done debug and I'm adding the selected values into bundle successfully.
On nextButton click it saves the selected data into bundle and replaces the fragment.
Now here's the fragment where I need to get the bundle and show in textView.
Bundle bundle = getArguments();
if (bundle != null) {
ArrayList<String> getProfessionName = bundle.getStringArrayList("String");
if (getProfessionName != null) {
for (int i = 0; i < getProfessionName.size(); i++) {
profession_text.setTextColor(Color.BLACK);
profession_text.setText(getProfessionName.get(i) + ",");
}
}
}
ProfessionText is my textView where I need to set the values. But in that textView shows only the last item from bundle. How to fix this? Thank you for reading.
You can change your code like,
for (int i = 0; i < professionList.size(); i++) {
Profession profession = professionList.get(i);
if (profession.isSelected()) {
getProfessions.add(profession.getName());
}
}
Bundle setProfessions = new Bundle();
setProfessions.putStringArrayList("String", getProfessions);
personalInfoFragment.setArguments(setProfessions);
replaceFragment();
And in next fragment,
profession_text.setTextColor(Color.BLACK);
profession_text.setText("");
if (getProfessionName != null) {
for (int i = 0; i < getProfessionName.size(); i++) {
String txt = profession_text.getText().toString() + getProfessionName.get(i) + ", ";
profession_text.setText(txt);
}
}
From what i can see..u need a list of values to be displayed right..what is happening here is on each iteration you set a new value for professional text which overwrites the one that was there previously..thats why you are seeing the last value..i think if you want a list of textviews you have to create a new textview in the loop..which in this case you are better off using a listview or recycler view.

How can I stop my arraylist being put multiple times into my shared preferences file?

The arraylist should be of the form, [{"12345"}, {"67890"}, etc...]
But when I close my app - I mean press the back button the amount of times it takes to get back to the Android home screen - and then restart it, I see MatchingContactsAsArrayListis[{"12345"}, {"67890"}, etc...,{"12345"}, {"67890"}, etc...]
If I close it twice, the arraylist comes up 3 times and so on, it keeps getting longer. It should just display each value once.
I thought editorMatchingContactsAsArrayList.remove(jsonMatchingContactsAsArrayList).commit();
would take care of this.
Here's my code:
#Override
public void onResponse(String response) {
//convert the JSONArray, the response, to a string
String MatchingContactsAsString = response.toString();
//make an arraylist which will hold the phone_number part of the MatchingContacts string
MatchingContactsAsArrayList = new ArrayList<String>();
try {
JSONArray Object = new JSONArray(MatchingContactsAsString);
for (int x = 0; x < Object.length(); x++) {
final JSONObject obj = Object.getJSONObject(x);
MatchingContactsAsArrayList.add(obj.getString("phone_number"));
}
SharedPreferences sharedPreferencesMatchingContactsAsArrayList = PreferenceManager.getDefaultSharedPreferences(getApplication());
SharedPreferences.Editor editorMatchingContactsAsArrayList = sharedPreferencesMatchingContactsAsArrayList.edit();
Gson gsonMatchingContactsAsArrayList = new Gson();
String jsonMatchingContactsAsArrayList = gsonMatchingContactsAsArrayList.toJson(MatchingContactsAsArrayList);
editorMatchingContactsAsArrayList.putString("MatchingContactsAsArrayList", jsonMatchingContactsAsArrayList);
editorMatchingContactsAsArrayList.remove(jsonMatchingContactsAsArrayList).commit();
editorMatchingContactsAsArrayList.commit();
} catch (Exception e) {
e.printStackTrace();
}
}
SharedPreferences.remove() method takes in the key that you used to save.
Which in this case is "MatchingContactsAsArrayList".
And actually, you don't need to use remove(), because putString() with an existing key, will override that value. Please make sure that the data from response is correct.

Create a List of saves from one button

I need help with my project. I need to be able to press a save button that uses shared preferences, and every time I press that button, I need it to take the saved data and stack it underneath each other like a list. The key value is "result". So the save button takes the string and integer and places it onto my Main activity XML layout. But, if I press save again with different integers or string it will replace the original string and integer I had originally saved. I want it to be able to keep the original string and integer if i save it for the first time and make a new string and integer underneath the original if i do a second time and so on forever. Please help!
This is under my saving activity:
public void save(View view){
Date date = new Date();
String stringDate = DateFormat.getDateInstance().format(date);
SharedPreferences sharedPreferences = getSharedPreferences("MyData", Context.MODE_PRIVATE);
SharedPreferences.Editor editor =sharedPreferences.edit();
editor.putString("result",String.format(stringDate, date) + " - " + text_view5.getText().toString());
editor.commit();
Toast.makeText(this, "Saved successfully!", Toast.LENGTH_LONG).show();
}
This is under my loading activity:
resultPhysical = (TextView) findViewById(R.id.home);
SharedPreferences sharedPreferences = getSharedPreferences("MyData", Context.MODE_PRIVATE);
String physicalresult = sharedPreferences.getString("result", DEFAULT);
String physicalresult2= sharedPreferences.getString("result2", DEFAULT);
if (physicalresult.equals(DEFAULT)){
Toast.makeText(this,"No Data Found", Toast.LENGTH_LONG).show();
}
else{
resultPhysical.setText(physicalresult);
}
}
You can easily save them, just create an extra variable that refers to the size of saved results so that you can loop over them. To start saving, get the size then save with the index
int size = sharedPreferences.getInt("size", 0); // if it doesn't exist, get 0
// then save the result like
editor.putString("result" + String.valueOf(size), String.format(stringDate, date) + " - " + text_view5.getText().toString()); // just add index to result
// then increase the size
editor.putInt("size", ++size);
editor.commit();
To load the results
StringBuilder results = new StringBuilder();
int size = int size = sharedPreferences.getInt("size", 0); // get the size to start looping
if(size == 0){ // if results are empty
// show toast there is no saved result
} else { //start looping
for(int i = 0; i < size; i++){
String temp = sharedPreferences.getString("result" + String.valueOf(i), DEFAULT);
results.append(temp + " ");
}
resultPhysical.setText(results.toString());
}

How to store array in an sharedpreferences in android

I am building an android application where the user selects his event from spinner tool.
The Spinner tool displays the array list that user had selected first time the application is launched.
Now I had parsed the array list from app launch page to spinner activity class an using it in spinner tool success full now.
Here is code:
public static ArrayList<String> array;
Here, the name array has the arraylist.
I need to store this in sharedprefrences. How can I do this ?
I am new to android.
I don't suggest using putStringSet() since it will screw up your arrayorder.
I suggest running a for loop over your array and giving them different key names. + in the end adding another String, that tells you how long the array is once you wanna read out the strings of the SharedPreferences.
General settings:
SharedPreferences sharedPreferences = getSharedPreferences("YOURKEYFILE", Activity.MODE_PRIVATE);
SharedPreferences.Editor sharedPreferencesEditor = sharedPreferences.edit();
Save String Array:
for (int i = 0; i < array.size(); i++) {
sharedPreferencesEditor.putString("StringArrayElement" +i, array.get(i));
}
sharedPreferencesEditor.putInt("StringArrayLength", array.size());
sharedPreferencesEditor.commit();
Read String Array:
array.clear();
for (int i = 0; i < sharedPreferencesEditor.getInt("StringArrayLength", 0) {
array.add(sharedPreferencesEditor.getString("StringArrayElement" +i, "");
}
NOTE:
The above code is untested! Community correct me there if you find mistakes.
You can save your array as Serializable object.
//save the task list to preference
SharedPreferences prefs = getSharedPreferences(SHARED_PREFS_FILE, Context.MODE_PRIVATE);
Editor editor = prefs.edit();
try {
editor.putString(ARRAY, ObjectSerializer.serialize(array));
} catch (IOException e) {
e.printStackTrace();
}
editor.commit();
And to retrieve it from SharedPreferences:
SharedPreferences prefs = getSharedPreferences(SHARED_PREFS_FILE, Context.MODE_PRIVATE);
try {
array = (ArrayList<String>) ObjectSerializer.deserialize(prefs.getString(ARRAY,
ObjectSerializer.serialize(new ArrayList<String>())));
} catch (IOException e) {
e.printStackTrace();
} catch (ClassNotFoundException e) {
e.printStackTrace();
}
You can get ObjectSerializer.java from here
This code help to you maybe.You save list item by counter i.
for(int i=0;i<list.size();i++)
{
editor.putString(list.get(i)+i, list.get(i));
editor.commit();}
for(int i=0;i<list.size();i++)
{
preferences.getString(list.get(i)+i, "");
}
It's better to go with Set<String> as API version 11 introduced methods putStringSet and getStringSet which allows the developer to store a list of string values and retrieve a list of string values, respectively.
Save list
// Save the list.
editor.putStringSet("array", myStrings);
editor.commit();
Fetch list
// Get the current list.
SharedPreferences settings = this.getSharedPreferences("YourActivityPreferences", Context.MODE_PRIVATE);
SharedPreferences.Editor editor = settings.edit();
Set<String> myStrings = settings.getStringSet("array", new HashSet<String>());

Categories