Okay so I have this message popup that asks the user to kindly rate the app. They can choose Yes or No. If Yes is pressed, the app in the app store will be opened. If no is pressed, the dialog box closes (for now). I want it so that if Yes is pressed, the dialog box will no longer ever show (even if the user only presses yes but does not actually rate the app..) even after they close and re-open the app.
The purpose of this is so that the user doesn't keep getting asked to rate the app even when they may have already done that.
Dialog Class:
public class CustomDialogClass extends Dialog implements
android.view.View.OnClickListener {
public Activity c;
public Dialog d;
public Button yes, no;
public CustomDialogClass(Activity a) {
super(a);
// TODO Auto-generated constructor stub
this.c = a;
}
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
requestWindowFeature(Window.FEATURE_NO_TITLE);
setContentView(R.layout.custom_dialog);
yes = (Button) findViewById(R.id.btn_yes);
no = (Button) findViewById(R.id.btn_no);
yes.setOnClickListener(this);
no.setOnClickListener(this);
}
#Override
public void onClick(View v) {
switch (v.getId()) {
case R.id.btn_yes:
Intent intent = new Intent(Intent.ACTION_VIEW);
intent.setData(Uri.parse("market://details?id=com.nianticlabs.pokemongo&hl=en"));
getContext().startActivity(intent);
dismiss();
break;
case R.id.btn_no:
dismiss();
break;
default:
break;
}
dismiss();
}
}
(I know the link is for pokemon go lol its just for trial purposes.)
any help will be greatly appreciated :)
________edit_______
code where i show the dialog (occurs when the user enters a specific class):
public class Final1 extends Activity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.final1);
CustomDialogClass cdd=new CustomDialogClass(Final1.this);
cdd.show();
You may need to store a state about whether the user pressed YES button. And before you want to show your dialog, check the state.
Since you only need a Boolean value, SharedPreferences is recommended.
It would be helpful if I could see where you show the actual dialog box, the code you provide for that only goes to the market page again... but we can still work with this.
If you want to never show this box to the user again, I recommend using SharedPreferences. This will enable us to store (basically) permanent variables.
Example:
SharedPreferences settings = getContext().getSharedPreferences("your-app", 0);
if(settings.getBoolean("btn_pressed", false)){
//show dialog
}
This will make sure the dialog doesn't open if we have the Shared Preferences boolean "btn_pressed" set to true.
To set this boolean after the yes button is pressed:
#Override
public void onClick(View v) {
switch (v.getId()) {
case R.id.btn_yes:
SharedPreferences.Editor edit = c.getSharedPreferences("your-app", 0).edit();
edit.putBoolean("btn_pressed", true);
edit.apply();
Intent intent = new Intent(Intent.ACTION_VIEW);
intent.setData(Uri.parse("market://details?id=com.nianticlabs.pokemongo&hl=en"));
getContext().startActivity(intent);
dismiss();
break;
case R.id.btn_no:
dismiss();
break;
default:
break;
}
dismiss();
}
Shared Preferences is an easy way for your app to remember permanent user settings or things of this nature. Hope this helps!
EDIT: please note syntax correction, the editor has a capital (SharedPreferences.editor becomes SharedPreferences.Editor)
Related
I am a beginner about java and android. I am learning about Sample softkeyboard in Android studio. I want to know how I can open Preference Screen by long press on a key (like Globe key) of sample keyboard instead of going to Setting menu of my phone. Thank you.
Sorry for my bad English.
Thats the way you can open the preference screen with a button click
public void onClick(View v) {
switch (v.getId()) {
case R.id.btnPrefs:
Intent intent = new Intent(PreferenceActivity.this,
PrefsActivity.class);
startActivity(intent);
break;
The long click is something like following
btn.setOnLongClickListener(new OnLongClickListener() {
#Override
public boolean onLongClick(View v) {
// TODO Auto-generated method stub
return true;
}
});
my problem is this:
I make a toast "welcome" in the Activity Main for the first time that you open the home, and it's ok,but when another page to return to the home via the back button, how can I make the toast "welcome" does not appear anymore?
the code of main activity is:
public class MyActivity extends Activity {
/**
* Called when the activity is first created.
*/
MyActivity actvi1;
int cont=0;
#Override
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
Button btnabout=(Button)findViewById(R.id.about);
//click
btnabout.setOnClickListener(new View.OnClickListener()
{
#Override
public void onClick(View v)
{
// definisco l'intenzione di aprire l'Activity "aboutme.java"
Intent aboutmejava= new Intent(MyActivity.this,aboutme.class);
startActivity(aboutmejava);
}
}
);
//toast
Toast toast = Toast.makeText(getApplicationContext(),
"Welcome", Toast.LENGTH_SHORT);
toast.setGravity(Gravity.CENTER_HORIZONTAL, 20, 0);
toast.show();
code of aboutme.java
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.aboutme);
Button btnback=(Button)findViewById(R.id.scritta);
btnback.setOnClickListener(new OnClickListener()
{
#Override
public void onClick(View v)
{
Intent main = new Intent(aboutme.this,MyActivity.class);
startActivity(main);
If you want it to only show the very first time the application runs, put a boolean flag in SharedPreferences and check here. There are tons of examples but here is one
If you want it to show *every time the Activity is first run when the app starts, simply replace your onClick() code with onBackPressed(). This way it won't start a new instance of your MyActivity and since the Toast code is in onCreate() and not onResume(), it won't run when you go back by clicking the back button.
SharedPreferences
This works.
SharedPreferences sp = getPreferences(Context.MODE_PRIVATE);
int show = sp.getInt("firstlaunch", 0);
if(show == 0) {
Toast.makeText(getApplicationContext(), "WELCOME", Toast.LENGTH_LONG).show();
sp.edit().putInt("firstlaunch", 1).apply();
}
Place it in your home activities onCreate method.'
A shared preference is a "setting" of sort. It's a xml file that is loaded which contains all of your settings. When we first run "sp.getInt" you can see that i have a 0 after the "key - fistlaunch". The 0 is specifying what to give our Int SHOW if it can't find any shared preference with that key. Next if the int show is equal to 0 we run our Toast and then change the shared preference value to 1 so next time you run it doesn't show...
boolean b = false;
if(!b) {
Toast toast = Toast.makeText(getApplicationContext(),
"Welcome", Toast.LENGTH_SHORT);
toast.setGravity(Gravity.CENTER_HORIZONTAL, 20, 0);
toast.show();
b = true
}
kind of like that?
Are you another instance of MainActivity?
In order to return to your Main activity you should send an Intent with the flag FLAG_ACTIVITY_CLEAR_TOP (or set android:launchMode="singleTop" in launchMode in AndroidManifest.xml)
Intent main = new Intent(aboutme.this,MyActivity.class);
main.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
startActivity(main);
By doing so, your main activity will be restored, instead of creating a new instance of MainActivity
so I have a code that checks something and I put it in the onCreate() of an Activity. I want to know if it's correct to put it there and also, for some reason the code that checks the Main Activity doesn't work at all, the second one which has a toast works. I think the problem may be in an AlertDialog. Here's the one with the toast:
AlertDialog.Builder Dial = new AlertDialog.Builder(Screen.this);
Dial.setTitle(R.string.Dial_Tit);
Dial.setMessage(R.string.Dial_Mes);
Dial.setPositiveButton("OK", PosBC());
Dial.setNegativeButton(R.string.Dial_NegBC, NegBC());
Dial.show();
Note: both buttons have methods, I just didn't post them. The problem is that the alert doesn't even show. And also for some reason the toast does work, it like automatically clicks thebutton, even thought the method has an intent which doesn't work.
More code as requested:
private DialogInterface.OnClickListener NegBC() {
Intent moveToStart;
moveToStart = new Intent(Screen.this, Launch.class);
startActivity(moveToStart);
return null;
}
private DialogInterface.OnClickListener PosBC() {
startActivity(new Intent(android.provider.Settings.ACTION_WIRELESS_SETTINGS));
Toast.makeText(getApplicationContext(), R.string.settingsToast, Toast.LENGTH_LONG).show();
return null;
}
Update: I've added the create() method which shows the dialog but it goes like this : when activity is created shows toast, press back goes to settings, press back from settings shows dialog, buttons don't work.
onCreate() will be called whenever you start the application and if it is not cached in the device's RAM.
I do not understand what you are trying to achieve other than that, please edit your post by adding more of your code and I will also edit my answer to be more detailed.
use this code to display alertDialog in android on clicking a button:
package .....; // name of your package.
import android.app.Activity;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.Toast;
public class AlertDialogActivity extends Activity {
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Button btnAlertTwoBtns = (Button) findViewById(R.id.button1);
btnAlertTwoBtns.setOnClickListener(new View.OnClickListener() {
public void onClick(View arg0) {
// Creating alert Dialog with two Buttons
AlertDialog.Builder alertDialog = new AlertDialog.Builder(AlertDialogActivity.this);
// Setting Dialog Title
alertDialog.setTitle(" "); //type your title here insid the quotes.
// Setting Dialog Message
alertDialog.setMessage(" "); //type the message which is to be displayed
// Setting Icon to Dialog
alertDialog.setIcon(R.drawable.ic_launcher); // set the icon from drawable folder just put the icon file in drawable folder.
// Setting Positive "Yes" Button
alertDialog.setPositiveButton("YES",
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog,int which) {
// Write your code here to execute after dialog
Toast.makeText(getApplicationContext(), "You clicked on YES", Toast.LENGTH_SHORT).show(); // just a sample code to tell that what things you can do here
}
});
// Setting Negative "NO" Button
alertDialog.setNegativeButton("NO",
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
// Write your code here to execute after dialog
Toast.makeText(getApplicationContext(), "You clicked on NO", Toast.LENGTH_SHORT).show();
dialog.cancel();
}
});
// Showing Alert Message
alertDialog.show();
}
});
}
}
Write your AlertDialog code in OnCreateDialog and Start a in OnCreate AsynTask for Checking purpose and once your task is finished, inside onPostExecute close the Dialog.
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
showDialog(0x01);
}
#Override
protected Dialog onCreateDialog(int id) {
AlertDialog.Builder Dial;
switch (id) {
case 0x01:
Dial = new AlertDialog.Builder(Screen.this);
Dial.setTitle(R.string.Dial_Tit);
Dial.setMessage(R.string.Dial_Mes);
Dial.setPositiveButton("OK", PosBC());
Dial.setNegativeButton(R.string.Dial_NegBC, NegBC());
Dial.create();
break;
default:
break;
}
return super.onCreateDialog(id);
}
Ok, I solved it myself, turns out it was just logic missing :D. Sorry!
In my app i have to use same dialog box on all the activities but then on to the click of button on dialog box i need to perform different operations for different activities, i have kept a common code for dialog but then how to call different functions, here is my code:
final Dialog dialog = new Dialog(mContext,R.style.Theme_Levels);
dialog.requestWindowFeature(Window.FEATURE_NO_TITLE);
dialog.setContentView(R.layout.custom_alert);
TextView title = (TextView)dialog.findViewById(R.id.title);
title.setText("Network Error");
TextView msg = (TextView)dialog.findViewById(R.id.msg_txt);
msg.setText("The system is down, please check after some time ");
ImageView cancel = (ImageView)dialog.findViewById(R.id.cancel);
cancel.setOnClickListener(new OnClickListener(){
#Override
public void onClick(View v) {
dialog.dismiss();
}
});
TextView continue_btn = (TextView)dialog.findViewById(R.id.continue_btn);
continue_btn.setBackgroundResource(R.drawable.feedback_button_purple);
continue_btn.setText("Retry");
continue_btn.setOnClickListener(new OnClickListener(){
#Override
public void onClick(View v) {
//TODO perform different operation depending upon from where this function has been called
dialog.dismiss();
}
});
dialog.show();
Create an interface, say DialogActivity, with one method "handlePositiveButton". Let all your Activities implement this interface. From the Dialog.onClick you do this:
DialogActivity activity = (DialogActivity) getActivity();
activity.handlePositiveButton();
Put the code you have specified in a function of a Utils file.
Then pass the positive button onclick listener in that function.
Refer the below code.
public static void showAlertDialog(OnClickListener listener) {
// enter your code here
continue_btn.setOnClickListener(listener);
// more code here
}
I want to implement functionality where user will be able to select which group of items to be displayed using checkbox shared preferences. To be precise I will read checked items from the preferences and display.
Here is my preferences class
public class Preferences extends PreferenceActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
//One way to add default preferences
//addPreferencesFromResource(R.xml.prefs);
//For now I prefer this
setPreferenceScreen(defaultPref());
}
// The first time application is launched this should be read
private PreferenceScreen defaultPref() {
PreferenceScreen root = getPreferenceManager().createPreferenceScreen(this);
CheckBoxPreference checkboxPref = new CheckBoxPreference(this);
checkboxPref.setKey("1");
checkboxPref.setTitle("SomeRandomStuff");
root.addPreference(checkboxPref);
return root;
}
public showAllPreferences () {
// TO SHOW ALL THE PREFERENCES BUT NOT SURE HOW TO DISPLAY THEM
}
}
Now I cannot understand how do I add more preferences dynamically and display them in preference screen.
Here is the main activity class
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
try {
setContentView(R.layout.main);
}catch (Exception e) {
e.printStackTrace();
}
exView = (ExpandableListView) findViewById(R.id.expandableListView1);
// STUFF TO ADD IN PREFERENCES
editText = (EditText) findViewById(R.id.editText1);
//BUTTON TO ADD PREFERENCES.(SEARCH TERM IS IDENTIFIED AND ADDED TO PREF)
addButton = (ImageButton) findViewById(R.id.imageButton1);
// BUTTON TO DISPLAY PREFERENCES
prefButton = (ImageButton) findViewById(R.id.imageButtonPref);
SharedPreferences settings = PreferenceManager.getDefaultSharedPreferences(this);
final SharedPreferences.Editor editor = settings.edit();
addButton.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View arg0) {
// TODO Auto-generated method stub
PrefObject obj = new PrefObject();
String key = Integer.toString(i);
String title = editText.getText().toString();
//prefArray.add(obj);
editor.putString(key, title);
editor.commit();
i++
}
});
prefButton.setOnClickListener(new OnClickListener() {
// This method should show the preferences activity with new data
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
Intent intent = new Intent(Main.this, Preferences.class);
startActivity(intent);
// I know how to call the intent but I am not sure if
// how to read the saved contents and display it
Preferences pref = new Preferences();
pref.showAllPreferences();
}
});
AFAIK, there is no "visibility" option for preferences, which kinda makes sense when you think it's all just a ListView.
See [1]. For what I see, you could do something like this:
PreferenceScreen screen = this.getPreferenceScreen();
// Use "1" since you're using "1" to create it.
CheckBoxPreference ckbox = (CheckBoxPreference) this.findPreference("1");
screen.removePreference(ckbox);
To recreate, you could do this [2]:
screen.addPreference(ckbox);
Additionally, remember to create your preference using the setOrder(int order) so that when you recreate, it will be recreated in the proper position.
As you can see, it could be worth to keep a global reference to the preference to make it easier and faster.
Of course, I don't need to tell that you should integrate that logic into your CheckboxPreference listener. See this answer by nobody else than Reto Meier himself to see a good way of doing it (it's a checkbox, too). There he registers a listener to the whole screen and checks which preference triggered the listener, but you can do it simpler (but more verbose later on) by just setting its setOnPreferenceChangeListener.
*edit: I see that you're also using a button to add the preference. You can also implement the same logic above into the button itself. It all depends if you want to do this using a checkbox or a button.
Finally, it could be worth to just set the enabled state, unless you are doing something like "see advanced preferences" or something worth to keep novice users away from doing dangerous stuff to your app. But generally the enable states work better for user experience, IMHO.
I hope this answers your question.