I'm creating an app on android studio and I want to store user input into textview even after they close the app.
I used SharedPreferences to store, load, and update data, but after I close the app the second time, it does not save the data I stored and instead shows: {}.
Is there a way I can fix this?
My code:
private String getUserName;
listTitle = (TextView)findViewById(R.id.listTitle);
listTitle.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
AlertDialog.Builder builder = new AlertDialog.Builder(MainActivity.this);
View view = getLayoutInflater().inflate(R.layout.input_name_edittext, null);
EditText name = (EditText)view.findViewById(R.id.name);
builder.setView(view)
.setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
dialog.cancel();
}
})
.setPositiveButton("Ok", new DialogInterface.OnClickListener() {
#RequiresApi(api = Build.VERSION_CODES.N)
#Override
public void onClick(DialogInterface dialog, int which) {
String nameInputted = name.getText().toString();
if(nameInputted.chars().filter(ch -> ch != ' ').count() <= 15){
saveName(nameInputted);
listTitle.setText(nameInputted);
}
else{
Toast.makeText(MainActivity.this,
"Name is too long",
Toast.LENGTH_LONG).show();
}
}
});
builder.show();
}
loadName();
updateName();
The methods:
public void saveName(String name) {
SharedPreferences sharedPreferences = getSharedPreferences(preferenceName, Context.MODE_PRIVATE);
SharedPreferences.Editor editor = sharedPreferences.edit();
editor.putString(HASHMAP_KEY, name);
editor.apply();
}
public void loadName() {
SharedPreferences sharedPreferences = getSharedPreferences(preferenceName, Context.MODE_PRIVATE);
getUserName = sharedPreferences.getString(HASHMAP_KEY, "Name");
}
public void updateName() {
listTitle.setText(getUserName);
}
Here is a way to do this in Kotlin using Shared Preferences
//get and set cache
fun setCache(key: String, value: String) {
val pref = context.getSharedPreferences(context.packageName, Context.MODE_PRIVATE)
val editor = pref.edit()
editor.putString(key, value)
editor.apply()
}
fun getCache(key: String): String {
val pref = context.getSharedPreferences(context.packageName, Context.MODE_PRIVATE)
val defaultValue = "0"
return pref.getString(key, defaultValue).toString()
}
Then you can use them as
val textView = findViewById<TextView>(R.id.someTextView)
val someBtn = findViewById<Button>(R.id.someButton)
//save data from text view
someBtn.setOnClickListner{
setCache("oldData", textView.text.toString())
}
//set data to text view
if (getCache("oldData").toInt() != 0) {
//means there is some old data already, so use it
textView.text = getCache("oldData")
}
I'm trying to make multiple-choice language on my application. The language change when I selected it, but the selection not change. I use two languages, If I chose the first language (Indonesia) change, but if I chose the second language (English) the selection stays on the first choice (Indonesia), and the language change to English. This is my code.
Button changeLang = findViewById(R.id.bahasa);
changeLang.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
showChangeLanguageDialog();
}
});
This code to show the dialog alert.
private void showChangeLanguageDialog() {
final String[] listItems = {"Indonesia", "English"};
AlertDialog.Builder mBuilder = new AlertDialog.Builder(AboutActivity.this);
mBuilder.setTitle("Pilih Bahasa");
Integer selectedPos = 0;
if(listItems.equals("Indonesia")){
selectedPos = 1; }
else {
selectedPos = 0;
}
mBuilder.setSingleChoiceItems(listItems, selectedPos, new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
String selectedItem = listItems[which];
if (selectedItem.equals("Indonesia")) {
setLocale("in");
recreate();
} else {
setLocale("en");
recreate();
}
dialog.dismiss();
}
});
AlertDialog mDialog = mBuilder.create();
mDialog.show();
}
private void setLocale(String lang) {
Locale locale = new Locale(lang);
Locale.setDefault(locale);
Configuration config = new Configuration();
config.locale = locale;
getBaseContext().getResources().updateConfiguration(config, getBaseContext().getResources().getDisplayMetrics());
SharedPreferences.Editor editor = getSharedPreferences("Settings", MODE_PRIVATE).edit();
editor.putString("My_Lang", lang);
editor.apply();
}
public void loadLocale(){
SharedPreferences preferences = getSharedPreferences("Settings", Activity.MODE_PRIVATE);
String language = preferences.getString("My_Lang","");
setLocale(language);
}
It seems you're setting the language correctly, but your alert dialog is not set dependent on your saved language. Instead of calling listItems, you need to call the language through shared preferences. Try the code below:
private void showChangeLanguageDialog() {
final String[] listItems = {"Indonesia", "English"};
AlertDialog.Builder mBuilder = new AlertDialog.Builder(MainActivity.this);
mBuilder.setTitle("Pilih Bahasa");
String language = getSharedPreferences("Settings", Activity.MODE_PRIVATE).getString("My_Lang","");
Integer selectedPos = 0;
if(language.equals("en")){
selectedPos = 1; }
else {
selectedPos = 0;
}
mBuilder.setSingleChoiceItems(listItems, selectedPos, (dialog, which) -> {
String selectedItem = listItems[which];
if (selectedItem.equals("Indonesia")) {
setLocale("in");
recreate();
} else {
setLocale("en");
recreate();
}
dialog.dismiss();
});
AlertDialog mDialog = mBuilder.create();
mDialog.show();
}
I want to display alertDialog only once. The first time user clicks on the play button, alertDialog should appear. User can stop the game. If he wishes to play again,the alertDialog should not appear again.
I've tried using sharedPreferences, but alertDialog is never displayed.
public boolean added = false;
private void startRoute(MenuItem item) {
SharedPreferences prefs = getContext().getSharedPreferences("myPref",Context.MODE_PRIVATE);
boolean added = prefs.getBoolean("added",false);
if(!added)
{
addRouteToCal();
}
refreshProgress();
}
private void addRouteToCal() {
final EditText taskEditText = new EditText(getContext());
new AlertDialog.Builder(getContext())
.setTitle(getString(R.string.current_add_to_favorites))
.setMessage(getString(R.string.current_name_favorites))
.setView(taskEditText)
.setPositiveButton(getString(R.string.ok), new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
String name=String.valueOf(taskEditText.getText());
saveRouteDone(name);
SharedPreferences.Editor prefs = getContext().getSharedPreferences("myPref",Context.MODE_PRIVATE).edit();
prefs.putBoolean("added",true);
prefs.commit();
}
})
.setNegativeButton(getString(R.string.cancel), (dialog, which) -> {
})
.show();
;
Any idea of what I did wrong ?
My question is i have a list of food item. when user press add button to add the dish i am saving this dish name in shared preference. but when i press the same dish twice in shared preference should show 2 dishes with the same name. but each time i press same dish its showing me only one dish. this is my code below.
public class Cafetaria extends AppCompatActivity {
String title;
ListView listView;
View customNav;
public String value,secdish,thrDish,frthDish;
public String Drink,Drink2,Drink3,Drink4;
String selectedDrink;
Dialog ViewDialog;
TextView tv_foodtype,tv_drink;
private Button button;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_cafetaria);
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
title = getIntent().getStringExtra("option");
getSupportActionBar().setTitle(title);
ActionBar actionBar = getSupportActionBar();
ActionBar.LayoutParams lp = new ActionBar.LayoutParams(ActionBar.LayoutParams.WRAP_CONTENT, ActionBar.LayoutParams.WRAP_CONTENT, Gravity.RIGHT | Gravity.CENTER_VERTICAL);
customNav = LayoutInflater.from(this).inflate(R.layout.food_actionbar_layout, null); // layout which contains your button.
actionBar.setCustomView(customNav, lp);
actionBar.setDisplayShowCustomEnabled(true);
customNav.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
ViewDialog = new Dialog(Cafetaria.this);
ViewDialog.setContentView(R.layout.activity_order_detail);
ViewDialog.setTitle("Your Order Details");
tv_foodtype = (TextView)ViewDialog.findViewById(R.id.nameuser);
tv_drink = (TextView)ViewDialog.findViewById(R.id.passnum);
button = (Button)ViewDialog.findViewById(R.id.okBtn);
ViewDialog.show();
final SharedPreferences mSharedPreference= PreferenceManager.getDefaultSharedPreferences(getBaseContext());
value=(mSharedPreference.getString("firstDish", ""));
Drink=(mSharedPreference.getString("selectedDrinks", ""));
Drink2=(mSharedPreference.getString("selectedDrinks1", ""));
Drink3=(mSharedPreference.getString("selectedDrinks2", ""));
Drink4=(mSharedPreference.getString("selectedDrinks3", ""));
secdish=(mSharedPreference.getString("secdish", ""));
thrDish=(mSharedPreference.getString("thirdDish", ""));
frthDish=(mSharedPreference.getString("fourtDish", ""));
tv_foodtype.setText("Main Dishes"+ " \n"+value + " \n" + secdish +"\n"+thrDish+"\n"+frthDish);
tv_drink.setText("Drink"+" \n"+Drink + " \n" + Drink2 +"\n"+Drink3+"\n"+Drink4);
button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
ViewDialog.dismiss();
}
});
}
});
listView =(ListView)findViewById(R.id.listView);
Drawable chic = this.getResources().getDrawable(R.drawable.chicktikka);
final Drawable plus = this.getResources().getDrawable(R.drawable.plus);
Drawable minus = this.getResources().getDrawable(R.drawable.minus);
ArrayList<FoodItemData> listofItem = new ArrayList<>();
FoodListViewAdapter listViewAdapter= new FoodListViewAdapter(this,R.layout.item_layout,listofItem);
listView.setAdapter(listViewAdapter);
listofItem.add(new FoodItemData("Chicken Tikka","spicey chicken tikka with mixures of indian spices",chic,plus,minus));
listofItem.add(new FoodItemData("Onion Bhaji","spicey chicken tikka with mixures of indian spices",chic,plus,minus));
listofItem.add(new FoodItemData("Chicken Pizza","spicey chicken tikka with mixures of indian spices",chic,plus,minus));
listofItem.add(new FoodItemData("Chicken Masala","spicey chicken tikka with mixures of indian spices",chic,plus,minus));
}
#RequiresApi(api = Build.VERSION_CODES.HONEYCOMB_MR1)
public void plusClick(View v)
{
if (listView.getPositionForView(v)==0) {
SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(Cafetaria.this);
final SharedPreferences.Editor editor = prefs.edit();
editor.putString("firstDish","Chicken Tikka");
AlertDialog.Builder adb = new AlertDialog.Builder(this);
adb.setTitle("Please Choose your drink");
final String[] drinks = new String[]{"Coke", "Fanta", "Sprite"};
final ArrayList<Integer> selectedItems = new ArrayList<Integer>();
final boolean[] preCheckedItems = new boolean[]{false, false, false};
adb.setMultiChoiceItems(drinks, preCheckedItems, new DialogInterface.OnMultiChoiceClickListener() {
#Override
public void onClick(DialogInterface dialog, int which, boolean isChecked) {
if (isChecked) {
selectedItems.add(which);
} else if (selectedItems.contains(which)) {
selectedItems.remove(which);
}
}
});
//Define the AlertDialog positive/ok/yes button
adb.setPositiveButton("Ok", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
for (int i = 0; i < selectedItems.size(); i++) {
int IndexOfColorsArray = selectedItems.get(i);
selectedDrink = Arrays.asList(drinks).get(IndexOfColorsArray);
editor.putString("selectedDrinks",selectedDrink);
editor.commit();
}
Toast.makeText(Cafetaria.this, "Your item has been added", Toast.LENGTH_SHORT).show();
}
});
//Define the Neutral/Cancel button in AlertDialog
adb.setNeutralButton("Cancel", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
}
});
adb.show();
}
else if (listView.getPositionForView(v) == 1) {
SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(Cafetaria.this);
final SharedPreferences.Editor editor = prefs.edit();
editor.putString("secdish","Onion Bhaji");
AlertDialog.Builder adb = new AlertDialog.Builder(this);
adb.setTitle("Choose your Drink");
final String[] drinks = new String[]{"Coke", "Fanta", "Sprite"};
final ArrayList<Integer> selectedItems = new ArrayList<Integer>();
final boolean[] preCheckedItems = new boolean[]{false, false, false};
adb.setMultiChoiceItems(drinks, preCheckedItems, new DialogInterface.OnMultiChoiceClickListener() {
#Override
public void onClick(DialogInterface dialog, int which, boolean isChecked) {
if (isChecked) {
selectedItems.add(which);
} else if (selectedItems.contains(which)) {
selectedItems.remove(which);
}
}
});
//Define the AlertDialog positive/ok/yes button
adb.setPositiveButton("Ok", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
for (int i = 0; i < selectedItems.size(); i++) {
int IndexOfColorsArray = selectedItems.get(i);
selectedDrink = Arrays.asList(drinks).get(IndexOfColorsArray);
editor.putString("selectedDrinks1",selectedDrink);
editor.commit();
}
Toast.makeText(Cafetaria.this, "Your item has been added", Toast.LENGTH_SHORT).show();
}
});
adb.setNeutralButton("Cancel", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
//When user click the neutral/cancel button from alert dialog
}
});
adb.show();
}
else if (listView.getPositionForView(v) == 2) {
SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(Cafetaria.this);
final SharedPreferences.Editor editor = prefs.edit();
editor.putString("thirdDish","Chicken Pizza");
AlertDialog.Builder adb = new AlertDialog.Builder(this);
adb.setTitle("Choose your Drink");
final String[] drinks = new String[]{"Coke", "Fanta", "Sprite"};
final ArrayList<Integer> selectedItems = new ArrayList<Integer>();
final boolean[] preCheckedItems = new boolean[]{false, false, false};
adb.setMultiChoiceItems(drinks, preCheckedItems, new DialogInterface.OnMultiChoiceClickListener() {
#Override
public void onClick(DialogInterface dialog, int which, boolean isChecked) {
if (isChecked) {
selectedItems.add(which);
} else if (selectedItems.contains(which)) {
selectedItems.remove(which);
}
}
});
adb.setPositiveButton("Ok", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
for (int i = 0; i < selectedItems.size(); i++) {
int IndexOfColorsArray = selectedItems.get(i);
selectedDrink = Arrays.asList(drinks).get(IndexOfColorsArray);
editor.putString("selectedDrinks2",selectedDrink);
editor.commit();
}
Toast.makeText(Cafetaria.this, "Your item has beed added", Toast.LENGTH_SHORT).show();
}
});
adb.setNeutralButton("Cancel", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
//When user click the neutral/cancel button from alert dialog
}
});
adb.show();
}
else if (listView.getPositionForView(v) == 3) {
SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(Cafetaria.this);
final SharedPreferences.Editor editor = prefs.edit();
editor.putString("fourtDish","Chicken Masala");
AlertDialog.Builder adb = new AlertDialog.Builder(this);
adb.setTitle("Choose your Drink");
final String[] drinks = new String[]{"Coke", "Fanta", "Sprite"};
final ArrayList<Integer> selectedItems = new ArrayList<Integer>();
final boolean[] preCheckedItems = new boolean[]{false, false, false};
adb.setMultiChoiceItems(drinks, preCheckedItems, new DialogInterface.OnMultiChoiceClickListener() {
#Override
public void onClick(DialogInterface dialog, int which, boolean isChecked) {
if (isChecked) {
selectedItems.add(which);
} else if (selectedItems.contains(which)) {
//selectedItems.remove(which);
selectedItems.add(which);
}
}
});
adb.setPositiveButton("Ok", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
for (int i = 0; i < selectedItems.size(); i++) {
int IndexOfColorsArray = selectedItems.get(i);
selectedDrink = Arrays.asList(drinks).get(IndexOfColorsArray);
editor.putString("selectedDrinks3",selectedDrink);
editor.commit();
}
Toast.makeText(Cafetaria.this, "Your item has beed added", Toast.LENGTH_SHORT).show();
}
});
adb.setNeutralButton("Cancel", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
//When user click the neutral/cancel button from alert dialog
}
});
adb.show();
}
}
public void minusClick(View v)
{
if (listView.getPositionForView(v)==0) {
final SharedPreferences mSharedPreference= PreferenceManager.getDefaultSharedPreferences(getBaseContext());
mSharedPreference.edit().remove("firstDish").commit();
mSharedPreference.edit().remove("selectedDrinks").commit();
Toast.makeText(Cafetaria.this, "Your Item has been removed", Toast.LENGTH_SHORT).show();
}
else if (listView.getPositionForView(v)==1)
{
final SharedPreferences mSharedPreference= PreferenceManager.getDefaultSharedPreferences(getBaseContext());
mSharedPreference.edit().remove("secDish").commit();
mSharedPreference.edit().remove("selectedDrinks1").commit();
Toast.makeText(Cafetaria.this, "Your Item has been removed", Toast.LENGTH_SHORT).show();
}
else if (listView.getPositionForView(v)==2)
{
final SharedPreferences mSharedPreference= PreferenceManager.getDefaultSharedPreferences(getBaseContext());
mSharedPreference.edit().remove("thirdDish").commit();
mSharedPreference.edit().remove("selectedDrinks2").commit();
Toast.makeText(Cafetaria.this, "Your Item has been removed", Toast.LENGTH_SHORT).show();
}
else if (listView.getPositionForView(v)==3)
{
final SharedPreferences mSharedPreference= PreferenceManager.getDefaultSharedPreferences(getBaseContext());
mSharedPreference.edit().remove("fourtDish").commit();
mSharedPreference.edit().remove("selectedDrinks3").commit();
Toast.makeText(Cafetaria.this, "Your Item has been removed", Toast.LENGTH_SHORT).show();
}
}
#Override
protected void onResume() {
super.onResume();
if (getSupportActionBar() != null){
getSupportActionBar().setTitle(title);
}
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case android.R.id.home:
this.finish();
return true;
}
return false;
}
#Override
protected void onRestart() {
super.onRestart();
final SharedPreferences mSharedPreference= PreferenceManager.getDefaultSharedPreferences(getBaseContext());
mSharedPreference.edit().remove("firstDish").commit();
mSharedPreference.edit().remove("selectedDrinks").commit();
mSharedPreference.edit().remove("selectedDrinks1").commit();
mSharedPreference.edit().remove("selectedDrinks2").commit();
mSharedPreference.edit().remove("selectedDrinks3").commit();
mSharedPreference.edit().remove("secdish").commit();
mSharedPreference.edit().remove("thirdDish").commit();
mSharedPreference.edit().remove("fourtDish").commit();
}
}`
This is the result I am getting. I press this dish twice and its shown only once. It should be shown twice the same dish name. Please Guide.
The code is really long to follow on here. But speaking generally, do you save each dish with different key-value pair? Maybe think about such solution. OR you could store the dishes in an array, which can be stored in Shared prefs, and once you want to see your dishes, just read out the Array List and display the items inside it.
You store the String into an Array, whenever you want to do it in your code. It's just like mArrayList.add("String"); and then you can update yuor SharedPrefs the same you already do, just check the URL on how to store ArrayList to SharedPrefs. Would be a cleaner solution in my view.
Here you can see how to store ArrayList in SharedPreferences:
Save ArrayList to SharedPreferences
And the once you want to display the items from ArrayList, you pull ArrayList from SharedPrefs and display them in AlertDialog ListView.
And here it is explained how to display Array Items in AlertDialog:
How can I display a list view in an Android Alert Dialog?
i can't seem to figure out why my app/code is crashing in this section. Any help would be appreciated. I think the problem lies on the creation of an AlertDialog in the else if statement.
Basically, this method is called on first launch of the application and asks the user to choose between two options: OCPS and Other. When OCPS is chosen, a SharedPreference is set. When other is selected, an AlertDialog with text box should pop up, allowing the user to input their own local URL, which is then saved to the SharedPreference.
Full code is available here: https://github.com/danielblakes/progressbook/
code follows:
public class MainActivity extends Activity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
boolean firstrun = getSharedPreferences(
"com.danielblakes.progressbook", MODE_PRIVATE).getBoolean(
"firstrun", true);
if (firstrun) {
new AlertDialog.Builder(this).setTitle("First Run").show();
pickDistrict(this);
getSharedPreferences("com.danielblakes.progressbook", MODE_PRIVATE)
.edit().putBoolean("firstrun", false).commit();
}
else {
String saved_district = getSharedPreferences(
"com.danielblakes.progressbook", MODE_PRIVATE).getString(
"district", null);
startupWebView(saved_district);
}
}
public Dialog pickDistrict(final Context context) {
AlertDialog.Builder districtalert = new AlertDialog.Builder(context);
districtalert
.setTitle(R.string.choose_district)
.setItems(R.array.districts,
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int i) {
if (i == 0) {
String district_site = "https://parentaccess.ocps.net/General/District.aspx?From=Global";
startupWebView(district_site);
getSharedPreferences(
"com.danielblakes.progressbook",
MODE_PRIVATE)
.edit()
.putString("district",
district_site).commit();
} else if (i == 1) {
AlertDialog.Builder customdistrict = new AlertDialog.Builder(context);
customdistrict
.setTitle(
R.string.custom_district_title)
.setMessage(
R.string.custom_district_message);
final EditText input = new EditText(
getParent());
customdistrict.setView(input);
customdistrict
.setPositiveButton(
"Ok",
new DialogInterface.OnClickListener() {
public void onClick(
DialogInterface dialog,
int which) {
String custom_url = input
.getText()
.toString();
getSharedPreferences(
"com.danielblakes.progressbook",
MODE_PRIVATE)
.edit()
.putString(
"district",
custom_url)
.commit();
}
});
customdistrict
.setNegativeButton(
"Cancel",
new DialogInterface.OnClickListener() {
public void onClick(
DialogInterface dialog,
int which) {
return;
}
}).show();
}
}
}).show();
return districtalert.create();
}
}
Change
AlertDialog.Builder customdistrict = new AlertDialog.Builder(this);
to
AlertDialog.Builder customdistrict = new AlertDialog.Builder(context);
also,
final EditText input = new EditText(getParent());
needed to be changed to
final EditText input = new EditText(context);