AlertDialog never displays even with sharedPreferences - java

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 ?

Related

Save singleChoiceItems AlertDialog option using SharedPreference

I've implemented a singleChoiceItems AlertDialog which opens from a navigation menu in my android app. I'm using it to change the app theme (Light, Dark, System default).
Now I'm trying to save the current state of the AlertDialog in sharedPrefernces along with the theme that the user selects. For e.g, if I've selected a dark theme previously, I want the AlertDialog to show the same while applying the theme to the app.
Here's the code I've been using.
String selectedTheme = "Light";
public static final String SHARED_PREFS = "sharedPrefs";
SharedPreferences sharedPreferences = getSharedPreferences(SHARED_PREFS, MODE_PRIVATE);
selectedTheme = sharedPreferences.getString("str", "Light");
public void openDialog() {
String[] themes = {"Light", "Dark", "System default"};
AlertDialog.Builder builder = new AlertDialog.Builder(MainActivity.this);
builder.setTitle("Choose Theme");
builder.setSingleChoiceItems(themes, 2, new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
selectedTheme = themes[which];
}
});
builder.setPositiveButton("Ok", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
SharedPreferences sharedPreferences = getSharedPreferences("SHARED_PREFS", MODE_PRIVATE);
SharedPreferences.Editor editor = sharedPreferences.edit();
editor.putString("str", selectedTheme);
editor.apply();
if (selectedTheme.equals("Light")) {
AppCompatDelegate.setDefaultNightMode(AppCompatDelegate.MODE_NIGHT_NO);
}
else if (selectedTheme.equals("Dark")) {
AppCompatDelegate.setDefaultNightMode(AppCompatDelegate.MODE_NIGHT_YES);
}
else {
AppCompatDelegate.setDefaultNightMode(AppCompatDelegate.MODE_NIGHT_FOLLOW_SYSTEM);
}
dialog.dismiss();
}
});
builder.setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
dialog.dismiss();
}
});
builder.show();
}
With the above code, the sharedpreferences is not storing the current state. What changes do I need to do in order to make it work?
I was able to solve the problem by sharing the string related to the theme in sharedPreference.
I also implemented the AlertDialog issue where I wanted to check the items which was previously chosen inside the app.
Following is the code I used:
String selectedTheme = "Light";
int checkedItem = 0;
public static final String SHARED_PREFS = "sharedPrefs";
public static final String TEXT = "text";
public static final String RADIO = "selected";
Then I called loadData() and updateViews() from onCreate().
public void openDialog() {
String[] themes = {"Light", "Dark", "System default"};
AlertDialog.Builder builder = new AlertDialog.Builder(MainActivity.this);
builder.setTitle("Choose Theme");
if (selectedTheme.equals("Light")) {
checkedItem = 0;
} else if (selectedTheme.equals("Dark")) {
checkedItem = 1;
} else {
checkedItem = 2;
}
builder.setSingleChoiceItems(themes, checkedItem, new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
selectedTheme = themes[which];
}
});
builder.setPositiveButton("Ok", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
if (selectedTheme.equals("Light")) {
AppCompatDelegate.setDefaultNightMode(AppCompatDelegate.MODE_NIGHT_NO);
}
else if (selectedTheme.equals("Dark")) {
AppCompatDelegate.setDefaultNightMode(AppCompatDelegate.MODE_NIGHT_YES);
}
else {
AppCompatDelegate.setDefaultNightMode(AppCompatDelegate.MODE_NIGHT_FOLLOW_SYSTEM);
}
saveData();
}
});
builder.setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
dialog.dismiss();
}
});
builder.show();
}
public void saveData() {
SharedPreferences sharedPreferences = getSharedPreferences(SHARED_PREFS, MODE_PRIVATE);
SharedPreferences.Editor editor = sharedPreferences.edit();
editor.putString(TEXT, selectedTheme);
editor.putInt("selected", checkedItem);
editor.apply();
Toast.makeText(MainActivity.this, "Data Saved", Toast.LENGTH_SHORT).show();
}
public void loadData() {
SharedPreferences sharedPreferences = getSharedPreferences(SHARED_PREFS, MODE_PRIVATE);
selectedTheme = sharedPreferences.getString(TEXT, "System default");
checkedItem = sharedPreferences.getInt("selected", 0);
}
public void updateViews() {
if (selectedTheme.equals("Light")) {
AppCompatDelegate.setDefaultNightMode(AppCompatDelegate.MODE_NIGHT_NO);
checkedItem = 0;
}
else if (selectedTheme.equals("Dark")) {
AppCompatDelegate.setDefaultNightMode(AppCompatDelegate.MODE_NIGHT_YES);
checkedItem = 1;
}
else {
AppCompatDelegate.setDefaultNightMode(AppCompatDelegate.MODE_NIGHT_FOLLOW_SYSTEM);
checkedItem = 2;
}
}
I followed the tutorial from this link.

Execute after close dialog

I have a button that open a dialog for change a number. The button is in activity, and generate a new class names dialogs, for storage different dialogs.
Dialog consigna: Dialogs.class
public String consigna(){
AlertDialog.Builder alert = new AlertDialog.Builder(ctxt);
alert.setTitle("Nueva temperatura");
alert.setMessage("Agrega una nueva temperatura");
final EditText input = new EditText(ctxt);
input.setInputType(InputType.TYPE_CLASS_NUMBER);
input.setRawInputType(InputType.TYPE_CLASS_NUMBER);
alert.setView(input);
alert.setPositiveButton("Ok", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int whichButton) {
data = input.getText().toString();
}
});
alert.setNegativeButton("cancel", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int whichButton) {
//Put actions for CANCEL button here, or leave in blank
}
});
alert.show();
return data;
}
on click button: MainActivity
//I need change these two values:
final public double temperatura = 200.3;
String newData;
...
public void onClick(View v) {
switch (v.getId()){
case R.id.tempConsigna:
dialog = new Dialogs(MainActivity.this);
String data = dialog.consigna();
newData = data;
break;
...//other cases...
The issue is in newData = data; I doesn't have a data, because the dialog not are closed. The dialog work in other thread,no?
How to change newData var with the dialog result? It is posible into a dialogs class?
You need a callback method implemented via an interface:
public String consigna(final OnConfirm confirm){
final String[] data = new String[1];
AlertDialog.Builder alert = new AlertDialog.Builder(activity);
alert.setTitle("Nueva temperatura");
alert.setMessage("Agrega una nueva temperatura");
final EditText input = new EditText(activity);
input.setInputType(InputType.TYPE_CLASS_NUMBER);
input.setRawInputType(InputType.TYPE_CLASS_NUMBER);
alert.setView(input);
alert.setPositiveButton("Ok", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int whichButton) {
data[0] = input.getText().toString();
confirm.onConfirm(data[0]);
}
});
alert.setNegativeButton("cancel", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int whichButton) {
//Put actions for CANCEL button here, or leave in blank
}
});
alert.show();
return data[0];
}
public interface OnConfirm {
void onConfirm(String s);
}
And in your Main Activity
Dialogs dialog = new Dialogs(MainActivity.this);
dialog.consigna(new Dialogs.OnConfirm() {
#Override
public void onConfirm(String s) {
Log.d("data", s);
}
});
It will not return result as you want but after click on dialog ok button then access data variable. no need to return.

Remember what was selected in single choice AlertDialog

I have an AlertDialog which displays an array into a single selected choice:
protected boolean blFrom, blTo;
protected void showSelectToDialog() {
boolean[] checkedDate = new boolean[toDate.length];
int count = toDate.length;
DialogInterface.OnClickListener setD2 = new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
//TODO Auto-generated method stub
onChangeSelectedTo(which);
}
};
AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setTitle("Select To Year");
builder.setSingleChoiceItems(toDate, count, setD2);
builder.setCancelable(true);
builder.setPositiveButton("Cancel", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
dialog.dismiss();
}
});
dialog2 = builder.create();
dialog2.show();
}
protected void onChangeSelectedTo(int j) {
bTo.setText(toDate[j]);
sTo = ((AlertDialog)dialog2).getListView().getCheckedItemPosition();
blTo = true;
displayToast(String.valueOf(sTo));
to = j;
dialog.dismiss();
}
What I want to do is the first time it loads it should display the default. Once I select a choice and the dialog closes and I bring up the same dialog again it should show the previously selected choice I made and scroll to it.
How do I accomplish it?
As of right now, I can get the selected position but what next?
You can store the chosen value in a variable of your Activity or using SharedPreferences

Code breaks at AlertDialog creation. I think I have Context wrong...?

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);

Persist AlertDialog options

I'm creating an AlertDialog. Here's the snippet of code that I'm using:
final CharSequence[] items = {"Red", "Green", "Blue"};
AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setTitle("Pick a color");
builder.setSingleChoiceItems(items, -1, new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int item) {
Toast.makeText(getApplicationContext(), items[item], Toast.LENGTH_SHORT).show();
}
});
AlertDialog alert = builder.create();
alert.show();
This works fine but I haven't been able to figure out how save the selection option somewhere so that the next time the alert dialog is opened, the previously selected option is shown. I don't need this value to persist across application restarts, only as long as the application is in the background and not entirely discarded.
Being new to Android development, I have found this pretty difficult to accomplish.
Use the code below :
private static final String SELECTED_ITEM = "SelectedItem";
private SharedPreferences sharedPreference;
private Editor sharedPrefEditor;
private void showAlert() {
final CharSequence[] items = {"Red", "Green", "Blue"};
AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setTitle("Pick a color");
builder.setSingleChoiceItems(items, getSelectedItem(), new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int item) {
saveSelectedItem(item);
Toast.makeText(getApplicationContext(), items[item], Toast.LENGTH_SHORT).show();
}
});
AlertDialog alert = builder.create();
alert.show();
}
private int getSelectedItem() {
if (sharedPreference == null) {
sharedPreference = PreferenceManager
.getDefaultSharedPreferences(this);
}
return sharedPreference.getInt(SELECTED_ITEM, -1);
}
private void saveSelectedItem(int item) {
if (sharedPreference == null) {
sharedPreference = PreferenceManager
.getDefaultSharedPreferences(this);
}
sharedPrefEditor = sharedPreference.edit();
sharedPrefEditor.putInt(SELECTED_ITEM, item);
sharedPrefEditor.commit();
}
For the first time, nothing will be selected. From second time onwards the item which is previously selected will be selected by default.

Categories