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!
Related
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)
I want to create a function for dialog method and reuse the function later on.
Code to create a dialog within a function:
private void alertView( String message ) {
AlertDialog.Builder dialog = new AlertDialog.Builder(this);
dialog.setTitle( "Hello" )
.setIcon(R.drawable.ic_launcher)
.setMessage(message)
.setPositiveButton("Ok", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialoginterface, int i){
}
}).show();
}
Code to call this function:
alertView("My message");
This works fine but I want to center my message. I have looked for solutions and used various methods such as:
AlertDialog alert = dialog.show();
TextView messageText =(TextView)alert.findViewById(android.R.id.message);
messageText.setGravity(Gravity.CENTER);
messageText.setTextColor(Color.RED)
Nothing works. Could someone please help me with this?
Found a solution to my question from this website: http://examples.javacodegeeks.com/android/core/ui/dialog/android-custom-dialog-example/
Created an xml layout as described on the website and made a little change to the code in my java class:
private void alertView( String message ) {
//create a dialog component
final Dialog dialog = new Dialog(this);
//tell the dialog to use the dialog.xml as its layout description
dialog.setContentView(R.layout.dialog);
dialog.setTitle("your title");
TextView txt = (TextView) dialog.findViewById(R.id.txt);
txt.setText(message);
Button dialogButton = (Button)dialog.findViewById(R.id.dialogButton);
dialogButton.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
mUartCom.write("D"); //change this
}
});
dialog.show();
}
and then I've reused this function numerous times by changing the message:
alertView("Please select one of the red icons to begin");
I'm a beginner for Java as well as for Android Studio so, here my problem is: I had created a alert dialog window for an activity with positive button being "OK" and negative button being "No thanks". As shown in the code below.
if(Times==0) {
AlertDialog.Builder builder1 = new AlertDialog.Builder(this);
builder1.setIcon(android.R.drawable.ic_dialog_alert);
builder1.setTitle("Warning");
builder1.setMessage("Rooting of a phone may void your Warranty in most of the cases,so it is adviced to proceed at your own risk");
builder1.setCancelable(true);
builder1.setPositiveButton(
"OK",
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
Times += 1;
dialog.cancel();
}
});
builder1.setNegativeButton(
"No Thanks",
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
dialog.cancel();
}
});
}
It was going fine but now the catch is I want it to be displayed only once if the user clicks the "OK" button and don't want to show it again if the user clicked "OK". I had created a variable times in my class and initialised it to zero as shown below.
public class rootingRooting extends AppCompatActivity {
int Times=0;
and put the complete AlertDialog in the if loop and incremented it's value when the user clicked "OK" so that the loop may execute only once if the user clicked "OK", but it is of no use whenever I open the activity the alert box is being displayed inspite of clicking "OK". So, now the things i want to do happen is:
The alert box should not be displayed if the user once clicked "OK".
If the user clicked the "no Thanks" button, I want to take him to the home activity. So, how should I use the intent with the "no thanks" button?
Thank you.
You need to use SharedPreferenes to save data persistently, local variables will not help.
something like this:
EDIT As per your request, I have added a sample activity class to show the whole process. See the comments in between for more info
EDIT 2 See the code after //Second Edit comment
public class MainActivity extends AppCompatActivity {
SharedPreferences prefs;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
//When the activity starts, we look into the shared prefs and get an int of name "ok_clicked" from it.
//0 will be the default value of the int if there is no int stored in sharedPreferences.
prefs = getSharedPreferences("myPrefs", MODE_PRIVATE);
int times = prefs.getInt("ok_clicked", 0);
//if the times value is 0, we will open the dialog, otherwise nothing happens
if (times==0){
openDialog();
}
}
//Read This comment First: We will create a Method, which create an alert Dialog.
private void openDialog(){
AlertDialog.Builder dialog = new AlertDialog.Builder(this);
dialog.setTitle("Test").setMessage("Lorem ipsum dolor");
dialog.setPositiveButton("Ok", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
//When OK button is clicked, an int with value of 1 will be saved in sharedPreferences.
prefs = getSharedPreferences("myPrefs", MODE_PRIVATE);
SharedPreferences.Editor editor = prefs.edit();
editor.putInt("ok_clicked", 1);
editor.apply();
}
});
dialog.setNegativeButton("No Thanks", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
//Second Edit: To open another acitivty on No Thanks Button
Intent intent = new Intent(MyActivity.this, HomeActivity.class);
startActivity(intent);
}
});
dialog.show();
}
}
Total noob here. Went through Google's developer reference but didn't find enough detail for me to understand. I am trying to make a dialog box appear when hitting an Action Bar item.
I have 2 classes. The first one is only the DialogFragment, using a AlertDialog builder with a positive button and a negative button.
The 2nd class is the Activity, in which I would like to call my DialogFragment and display the dialog, however I when I try to do that under the OnOptionsItemSelected function, using the following code:
DialogFragment newFragment = new CreateWordListDialog();
newFragment.show(getSupportFragmentManager(), "createWordList");
I get a "cannot resolve method" line error on the 2nd line. Where should this line be placed? I must be missing something here.
Inside the function OnOptionsItemSelected you can construct your AlertDialog, you don't need to create another class for this.
AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());
builder.setTitle(R.string.title) //
.setMessage(R.string.message) //
.setPositiveButton(getString(R.string.positive), new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
// TODO
dialog.dismiss();
}
}) //
.setNegativeButton(getString(R.string.parking_no_button), new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
// TODO
dialog.dismiss();
}
});
builder.show();
In Android studio android.support.v4 etc are not encluded by default. So either add these dependencies manually or use getFragmentManager() instead of getSupportFragmentManager() and the issue will be solved
I am new to Android, i am writing a program where when a user clicks a button a Alert Dialog to appear. This alert dialog has 2 buttons, Yes and No. Upon clicking Yes/No, i need to sysout the response.
The code i have so far; Can someone help me add the Alert Dialog;
public class HelloWorldProjectActivity extends Activity implements OnClickListener {
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.myFirstScreen);
}
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
if(v.getId()==(R.id.button1)){
System.out.println("first button clicked");
// I need a Alert Dialog to appear here, and that will have 2 buttons YES and NO, the users response should be printed to the console.
}
}
You cannot System.out.print().
There are several methods to display the result. One is to use Toast. It will briefly show a text message and then disappear.
new AlertDialog.Builder(this)
.setMessage("Are you sure?")
.setPositiveButton("Yes", new OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
Toast.makeText(TestAndroidActivity.this, "YES CLICKED",
Toast.LENGTH_LONG).show();
}
}).setNegativeButton("No", new OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
Toast.makeText(TestAndroidActivity.this, "NO CLICKED",
Toast.LENGTH_LONG).show();
}
}).show();
Modify your code as follows:
The activity class doesn't have to implement OnClickListener.
Thus, remove onClick() method
Go to the layout file, add an attribute android:onClick="click" in the button declaration.
Add public void click(View view) with the previous code.
First of all, there really isn't any system.out to print to in android. What you should try instead is printing to the log. For information on how to print to the log, check this out. To then see the activity of the log (including messages you printed to it), checkout the logcat.
Second, for information on creating an alert dialog, please view this documentation.