In my application when user click back , I make an alert dialog that included 2 buttons. first button is Exit that allow user to exit the application.
the second button is 5 star that allow user to rate me in the market.
it works correctly.
but the problem is that when I kill the application and I run it again, this process repeat. and I want if the user rate me before , I don't show the 5 star button to user again.
how can I save my state button in it?
I know that I must share preferences , but how?
int star = 0;
public void onClick(View v) {
int id = v.getId();
if(id == R.id.button1 && stringListCounter <lines.size() - 1) {
stringListCounter++;
} else if (id == R.id.button2 && stringListCounter > 0) {
stringListCounter--;
}
txtQuestion.setText(lines.get(stringListCounter));
}
public void onBackPressed() {
AlertDialog.Builder alertDialog = new AlertDialog.Builder(QuizActivity.this);
alertDialog.setTitle("please rate us");
alertDialog.setPositiveButton("5star", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
Intent browserIntent = new Intent(
Intent.ACTION_EDIT,
Uri.parse("http://cafebazaar.ir/app/my package name/?l=fa"));
startActivity(browserIntent);
star ++;
}
});
alertDialog.setNegativeButton("exit", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
Intent intent1 = new Intent(Intent.ACTION_MAIN);
intent1.addCategory(Intent.CATEGORY_HOME);
intent1.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
startActivity(intent1);
}
});
alertDialog.show();
}
here my star value is 0. when user rate me , the value of star become 1 . I
want save the my star value to 1 that this process don't repeat again.
please help
First Of Save Preferences
SharedPreferences sharedPref = getActivity().getPreferences(Context.MODE_PRIVATE);
SharedPreferences.Editor editor = sharedPref.edit();
editor.putInt("KeyValue", newHighScore);
editor.commit();
Read from Shared Preferences
SharedPreferences sharedPref = getActivity().getPreferences(Context.MODE_PRIVATE);
int defaultValue = getResources().getInteger("KeyValue");
after get preference easily check condition
you can create one method in shared preferences that will give your app state means when user is clicking on 5 start on that time you have to set the app state 1. and next time before calling this
alertDialog.setPositiveButton("5star", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
Intent browserIntent = new Intent(
Intent.ACTION_EDIT,
Uri.parse("http://cafebazaar.ir/app/my package name/?l=fa"));
startActivity(browserIntent);
star ++;
}
});
apply if condition and check the state of the app in shared preference means if state is 1 then don't allow to execute this functionality else allow.
Related
Hello guys and Happy new year to all!
I'm having a weird trouble in my app which I can't seem to fix. It should be a logic error, but I'm not able to somehow catch it.
Here is my code
public String[] str={"Disabled","Sound Quality Prefered","Bass Prefered","Battery Prefered",};
public int ThemePresetValue = 0;
private int SelectedThemePresetValue = 0;
public void presets() {
AlertDialog.Builder alertDialog = new AlertDialog.Builder(this);
alertDialog.setTitle("Select Your Sound Preset");
alertDialog.setNegativeButton("Cancel", null);
alertDialog.setPositiveButton("Select", themePresetDialogPositiveListener);
alertDialog.setSingleChoiceItems(str, ThemePresetValue, PresetListListener);
alertDialog.show();}
DialogInterface.OnClickListener PresetListListener =
new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
SelectedThemePresetValue = which;
}
};
DialogInterface.OnClickListener themePresetDialogPositiveListener =
new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
mPreset = "";
ThemePresetValue = SelectedThemePresetValue;
if (ThemePresetValue == 0) {
mPreset = "Disabled";
} else if (ThemePresetValue == 1) {
mPreset = "Sound Quality Prefered";
} else if (ThemePresetValue == 2) {
mPreset = "Bass Prefered";
} else if (ThemePresetValue == 3) {
mPreset = "Battery Prefered";
}
if (mPreset.equals("Disabled")) {
disabler();
} else if (mPreset.equals("Sound Quality Prefered")) {
SoundQPreset();
} else if (mPreset.equals("Bass Prefered")) {
bassPreset();
} else if (mPreset.equals("Battery Prefered")) {
batteryPreset();
}
}
};
The problem is that after I choose one of the presets the choice sticks until the app is closed from multitasking (MainActivity gets restarted or killed). Then if I re-open the app, the choice of dialog is re-set onto 0 ("Disabled").
Why is this happening? Do you have a solution?
Yes, the field is created each time anew for the respective object and since this object (i.e. the activity) is destroyed the memory holding the field is freed up as well. So the field's lifespan is bounded by that of the object. To make it continuous, you better save the value in SharedPreferences, or in general to write it out to some storage, before destroying the activity, e.g. in onPause() and then fetch it from those preferences in onCreate() or onResume() callbacks. For example:
/*--- Saving ---*/
SharedPreferences prefs =
getApplicationContext().getSharedPreferences(PREFERENCES_NAME, Context.MODE_PRIVATE);
prefs.edit().putInt(KEY_NAME, VALUE).apply();
/*--- Retrieving ---*/
int oldValue =
getApplicationContext().getSharedPreferences(PREFERENCES_NAME, Context.MODE_PRIVATE)
.getInt(KEY_NAME, 0);
PREFERENCES_NAME is the file name of your shared preferences file. KEY_NAME is the key, under which you save and later retrieve the stored value. VALUE is simply the value to save.
Hope this helps!
As you are not persisting the user's choice, the choice remains in memory until activity finishes. You should save the user's choice locally using SharedPreferences or sqlite for instance!
When the activity restarts you can read the saved value and set the option as selected!
I would like to prompt the user to give me input in my android application using a dialog.
When the user puts the figure it will go to another screen, but it does not give the user to input the value it does not waiting to the user its going to another activity directly.
What can i do to waiting the user to input the value he needs and after that it will take the user to the activity he needs. This is the code that i use.
else
{
{
// get prompts.xml view
LayoutInflater layoutInflater = LayoutInflater.from(Login.this);
View promptView = layoutInflater.inflate(R.layout.activity_input_dialog, null);
AlertDialog.Builder alertDialogBuilder = new AlertDialog.Builder(Login.this);
alertDialogBuilder.setView(promptView);
final EditText editText = (EditText) promptView.findViewById(R.id.editCodeSurvey);
// setup a dialog window
alertDialogBuilder.setCancelable(false)
.setPositiveButton("OK", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
String surveyCode = editText.getText().toString();
}
})
.setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
dialog.cancel();
}
});
// create an alert dialog
AlertDialog alert = alertDialogBuilder.create();
alert.show();
}
//After Creating Dialog then we asking if the User that signed in is a manager
if(parseUser.getBoolean("isManager"))
{
//open manager Class
startActivity(new Intent(Login.this,ManagerScreen.class));
}
else{
//open Student Class to fill the survey
startActivity(new Intent(Login.this,StudentField.class));
}
You are not waiting for user input. You need to put code of launching new activity inside the Dialog box listener.
Put
//After Creating Dialog then we asking if the User that signed in is a manager
if(parseUser.getBoolean("isManager"))
{
//open manager Class
startActivity(new Intent(Login.this,ManagerScreen.class));
}
else{
//open Student Class to fill the survey
startActivity(new Intent(Login.this,StudentField.class));
}
inside onClick of OK button. It should be like this
public void onClick(DialogInterface dialog, int id) {
String surveyCode = editText.getText().toString();
//After Creating Dialog then we asking if the User that signed in is a manager
if(parseUser.getBoolean("isManager"))
{
//open manager Class
startActivity(new Intent(Login.this,ManagerScreen.class));
}
else{
//open Student Class to fill the survey
startActivity(new Intent(Login.this,StudentField.class));
}
}
public void onClick(DialogInterface dialog, int id) {
String surveyCode = editText.getText().toString();
if(parseUser.getBoolean("isManager")) {
//open manager Class
startActivity(new Intent(Login.this,ManagerScreen.class));
} else {
//open Student Class to fill the survey
startActivity(new Intent(Login.this,StudentField.class));
}
}
put the code inside on click method
My goal is add data to listView, after push on notification shows dialog, if user press Yes, app will show activity with fragment, and again will display new dialog to add new item. But if I press add, I get:
java.lang.NullPointerException: Attempt to invoke virtual method 'android.support.v4.app.LoaderManager android.support.v4.app.FragmentActivity.getSupportLoaderManager()' on a null object reference
My dialog to add new item to listview be in MainActivity, but I need to refresh my listview in Fragment, i am using ViewPager.
It seems like my fragment not initialized yet, but dialog at display now. How to implement this solution? One more thing, in my notification I set AutoCancel(true), but notif is still being on screen.
Here is the screen chronology:
Step 1
Step 2
one more image i can't add(
My dialog activity:
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
final String text = getIntent().getStringExtra("text");
new AlertDialogWrapper.Builder(this)
.setTitle(R.string.title_alert)
.setMessage(R.string.title_alert)
.setNegativeButton("No", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
finish();
}
})
.setPositiveButton("Yes", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
Intent intent = new Intent(DialogActivity.this, MainActivity.class);
intent.putExtra("notification",true);
intent.putExtra("text",text);
startActivity(intent);
finish();
}
}).show();
}
My method which will cal if user press add item in second dialog
private void showTrackerDialog(TrackersFragment f, final String text,boolean isFromNotif) {
final TrackersFragment trackersFragment = f;
tracker = new Tracker();
MaterialDialog dialog = new MaterialDialog.Builder(this)
.title("New tracker :)")
.customView(R.layout.add_track, true)
.positiveText("ADD")
.positiveColorRes(R.color.primary_light_green)
.negativeText(android.R.string.cancel)
.negativeColorRes(R.color.primary_red)
.callback(new MaterialDialog.ButtonCallback() {
#Override
public void onPositive(MaterialDialog dialog) {
if (hours.getValue() == 0 && minutes.getValue() == 0 && isLimit.isCheck()) {
Toast.makeText(getApplicationContext(), "Please check your the input values!", Toast.LENGTH_SHORT).show();
return;
}
//limited
if ((((hours.getValue() != 0 && minutes.getValue() == 0) || (hours.getValue() == 0 && minutes.getValue() != 0))
|| (hours.getValue()!=0 && minutes.getValue()!=0)) && isLimit.isCheck()) {
try {
hoursToMillis = Long.parseLong(String.valueOf(hours.getValue()));
minutesToMillis = Long.parseLong(String.valueOf(minutes.getValue()));
tracker.setLimitTime((hoursToMillis * 60 * 60 * 1000) + (minutesToMillis * 60 * 1000));
tracker.setName(name.getText().toString());
tracker.setElapsedTime((long) 0);
tracker.setIsFinished(false);
tracker.persist(RemindMe.db);
trackersFragment.updateListView(true,tracker);
return;
} catch (Exception ex) {
ex.printStackTrace();
Toast.makeText(getApplicationContext(), "Something goes wrong :(", Toast.LENGTH_SHORT).show();
return;
}
}
//no limit
if (!isLimit.isCheck()) {
tracker.setLimitTime(0L);
tracker.setName(name.getText().toString());
tracker.setElapsedTime((long) 0);
tracker.setIsFinished(false);
tracker.persist(RemindMe.db);
trackersFragment.updateListView(true,tracker);
}
}
#Override
public void onNegative(MaterialDialog dialog) {
}
}).build();
And here is the NullPointerExeption, getSupportLoaderManager()
public void updateListView(boolean isAdded,Tracker tracker) {
if(isAdded && tracker!=null){
trackerList.add(tracker);
getActivity().getSupportLoaderManager().getLoader(TRACKLOADER_ID).forceLoad();
adapter.swapCursor(Tracker.getAll(db));
}
}
Your problem here isn't trying to add to the list, but understanding the lifecycle. It seems to me that you have not setup the fragment, or possible have crossed paths of which fragment library you are using. Your error says v4.Support.Fragment. Make sure you use that same class everywhere. Even when opening it. (Check your imports. Make sure they are all v4).
Also check that your MainActivity does not extend Activity, but FragmentActivity
After which, If you are trying to notify your app from a notification, your best solution is going to be a BroadcastReceiver.
I can save the choice while I am using the app, but whenever I close the app and restart it, the choices are empty again. Where am I going wrong? It is always loading the default "0" instead of remembering the last selection.
SharedPreferences preferences = PreferenceManager.getDefaultSharedPreferences(this);
final SharedPreferences.Editor editor = preferences.edit();
SharedPreferences choiceSettings = getSharedPreferences("currentChoice", 0);
final int[] currentChoice = {choiceSettings.getInt("currentChoice", 0)};
final CharSequence[] items = {"AT&T", "Tmobile", "Verizon", "Sprint", "Other"};
// Decide which carrier, so we can apply the correct forwarding code.
final AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setTitle("Select your carrier");
builder.setIcon(R.drawable.ic_launcher);
builder.setSingleChoiceItems(items, currentChoice[0],
new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int item) {
// TODO Auto-generated method stub
switch (item) {
case 0:
Toast.makeText(getApplicationContext(),
items[item], Toast.LENGTH_SHORT).show();
// Your code when first option seletced
currentChoice[0] = 0;
editor.putInt(String.valueOf(currentChoice[0]), 0);
editor.putString("fCode", "*67*");
editor.apply();
break;
case 1:
// Your code when 2nd option seletced
Toast.makeText(getApplicationContext(),
items[item], Toast.LENGTH_SHORT).show();
currentChoice[0] = 1;
editor.putInt(String.valueOf(currentChoice[0]), 0);
editor.putString("fCode", "*67*");
editor.apply();
break;
case 2:
// Your code when 2nd option seletced
Toast.makeText(getApplicationContext(),
items[item], Toast.LENGTH_SHORT).show();
currentChoice[0] = 2;
editor.putInt(String.valueOf(currentChoice[0]), 0);
editor.putString("fCode", "*67*");
editor.apply();
break;
}
dialog.cancel();
}
});
AlertDialog alert = builder.create();
alert.show();
}
In the beginning (line 4), you try to load a variable named "currentChoice":
final int[] currentChoice = {choiceSettings.getInt("currentChoice", 0)};
In general you save a variable with editor.putInt(String key, int value). So key is the name used for saving your variable.
When you write
currentChoice[0] = 0;
editor.putInt(String.valueOf(currentChoice[0]), 0);
String.valueOf(currentChoice[0]) becomes "0". You save an int 0 to a variable named "0".
So change the second line to
editor.putInt("currentChoice", currentChoice[0]);
You are using two shared preferences container, the default one and a custom one. Use only the default one.
SharedPreferences preferences = PreferenceManager.getDefaultSharedPreferences(this);
final SharedPreferences.Editor editor = preferences.edit();
final int[] currentChoice = {preferences.getInt("currentChoice", 0)};
I have the following code:
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;
dialog2.dismiss();
}
What I am looking to do is, when the dialog loads the first time and the user selects a choice it is stored. So the next time the user opens the dialog, it will remember what was select and scroll to that choice.
How do I accomplish that?
Save the selected choice's position for the first time using Shared Preferences.
Then at the start of showSelectToDialog() check if any value exists in Shared Preferences, if so, then set the value of count from the Shared Preferences else set value of count to toDate.length.
I can't see the rest of your code, but all you have to do is save the user's choice in a variable somewhere else, and then read that choice every time you open the dialogue. It could be a static variable on the class, or it could be an instance variable of the class, or it could be a public field of some other class you have access to, like a parent object. You just need to assign it when you close the dialogue, and read it back and initialize the value to what you read when you open the dialogue.