Dialog showing only 1 button - java

I made an app and inserted a dialog in it using DialogFragment, by reading the instructions on the officila android developers site. I made a dialog with 3 buttons, each having a different function. However, when I run it, only 1 button is displayed (mxed fraction). Why is that so?
Here's the code:
package com.example.fractionscalculator;
import android.app.AlertDialog;
import android.app.Dialog;
import android.content.DialogInterface;
import android.os.Bundle;
import android.widget.TextView;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.appcompat.app.AppCompatDialogFragment;
import androidx.fragment.app.DialogFragment;
public class specifyInput extends AppCompatDialogFragment {
#NonNull
#Override
public Dialog onCreateDialog(#Nullable Bundle savedInstanceState) {
AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());
builder.setMessage("Please specify the type of number you entered.");
builder.setTitle("Set format");
builder.setNeutralButton("Regular Fraction", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
((MainActivity)getActivity()).getandsetText1("frac");
}
});
builder.setNeutralButton("Whole Number", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
((MainActivity)getActivity()).getandsetText1("whole");
}
});
builder.setNeutralButton("Mixed Fraction", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
((MainActivity)getActivity()).getandsetText1("mixed");
}
});
return builder.create();
}
}
I am a beginner in java and android, so if it is a stupid mistake, please go easy on me.

you can use 3 kind of predefined action button like : so you have used setNeutralButton 3 time its override that button and only show 1 time.
dialog.setPositiveButton(..);
dialog.setNegativeButton(..);
dialog.setNeutralButton(..);
as per documentation :
There are three different action buttons you can add:
Positive : You should use this to accept and continue with the action (the "OK" action).
Negative : You should use this to cancel the action.
Neutral : You should use this when the user may not want to proceed with the action, but doesn't necessarily want to cancel. It appears between the positive and negative buttons. For example, the action might be "Remind me later."

Related

why alertDialog.setButton onclickListner show error that no suitable method found

MainActivity
package com.example.dialog;
import androidx.appcompat.app.AlertDialog;
import androidx.appcompat.app.AppCompatActivity;
import android.content.DialogInterface;
import android.os.Bundle;
import android.widget.Toast;
public class MainActivity extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
AlertDialog alertDialog= new AlertDialog.Builder(this).create();
alertDialog.setTitle("Term and Conditons");
alertDialog.setIcon(R.drawable.baseline_info_24);
alertDialog.setMessage("have you read all term and condition");
alertDialog.setButton("yes, I've read",new DialogInterface.OnClickListener(){
#Override
public void onClick(DialogInterface dialog, int which) {
Toast.makeText(MainActivity.this, "Tes, you can proceed now..", Toast.LENGTH_SHORT).show();
}
});
alertDialog.show();
}
}
Error
C:\Users\anonhake\AndroidStudioProjects\dialog\app\src\main\java\com\example\dialog\MainActivity.java:20: error: no suitable method found for setButton(String,<anonymous OnClickListener>)
alertDialog.setButton("yes, I've read",new DialogInterface.OnClickListener(){
^
method AlertDialog.setButton(int,CharSequence,Message) is not applicable
(actual and formal argument lists differ in length)
method AlertDialog.setButton(int,CharSequence,OnClickListener) is not applicable
(actual and formal argument lists differ in length)
method AlertDialog.setButton(int,CharSequence,Drawable,OnClickListener) is not applicable
(actual and formal argument lists differ in length)
don't build your dialog in first line (create() call), use AlertDialog.Builder instance, set "possitive" and "negative" buttons on this (also title, message etc.), then call create() or even simpler show()
check out sample HERE
// initial builder and msg setup
AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setMessage("Close app?").setTitle("Exit");
// can't close dialog with e.g. back button, must be picked on of buttons
builder.setCancelable(false);
// buttons setup
builder.setPositiveButton("Yes", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
finish(); // closing Activity
}
});
builder.setNegativeButton("No", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
}
});
builder.show();
dialog will close automatically when any button clicked, the one with "Yes" will close whole Activity, "No" is empty and you will stay in (looks like empty) Activity
As per error , it looks like method with parameter types that you are using is not there . So basically you have three choice to use
1. setButton(int,CharSequence,Message)
2. setButton(int,CharSequence,OnClickListener)
3. setButton(int,CharSequence,Drawable,OnClickListener)

Java Show a Messagebox for a short time and make it disappear by itself

after reading a lot of solutions on AlertDialog I finally managed to get a message displayed. The message is the counter for the rounds in a little game. The Message should pop up, before the player enters the next round. It should remain a few seconds and then disappear by itself.
What happens: The programm gets stuck in showing the alert window and does not go to the i++ line.
Any idea how to solve this problem without introducing a button that the user must hit? I have taken out the dismiss() because there is a screenrefresh afterwards anyway. But at the moment it woudn't reach that point anyway.
I am working with Android Studio 2.2.2
Would be great, if someone could look into it. Thanks in advance.
Here is the code:
import android.app.Activity;
import android.app.AlertDialog;
import android.app.Dialog;
import android.content.DialogInterface;
import android.os.Bundle;
import android.os.Handler;
import android.view.Gravity;
import android.view.View;
import android.view.ViewGroup;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.TextView;
import java.util.Date;
import java.util.Random;
private void startRound() {
int i=0;
round = round +1;
AlertDialog alertDialog = new AlertDialog.Builder(this).create();
alertDialog.setTitle(" ");
alertDialog.setMessage("Round " + round);
while(i<100) {
alertDialog.show();
i++;
}
// alertDialog.dismiss();
screenrefresh();
handler();
You should show your dialog and use handler to dismiss :
final Handler handler = new Handler();
handler.postDelayed(new Runnable() {
#Override
public void run() {
alertDialog.dismiss();
}
}, 100);
If you refresh activity you can use Toasts .
you can customize your toast style .
i++ is not increasing because your alert dialog needs to be closed first. so it's stuck.
Below code shows dialog and closes after 5 seconds and it can not be dismissed by the user.
final AlertDialog alertDialog = new AlertDialog.Builder(this).create();
alertDialog.setTitle(" ");
alertDialog.setMessage("Round " + round);
alertDialog.setCancelable(false); // if you want it not to be dismissed by user
alertDialog.show();
new Thread(new Runnable() {
#Override
public void run() {
try {
Thread.sleep(500); // seconds * 100
} catch (InterruptedException e) {
if (alertDialog.isShowing())
{
alertDialog.dismiss();
}
e.printStackTrace();
}finally {
if (alertDialog.isShowing())
{
alertDialog.dismiss();
}
}
}
}).run();
For you task snackbars will be more acceptable.
Add CoordinatorLayout in layout.xml
<android.support.design.widget.CoordinatorLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_alignParentBottom="true"
android:layout_centerHorizontal="true"
android:id="#+id/snackbarPosition"/>
And just run snackbar:
final View.OnClickListener clickListener = new View.OnClickListener() {
public void onClick(View v) {
...
}
};
final View coordinatorLayoutView = findViewById(R.id.snackbarPosition);
Snackbar
.make(coordinatorLayoutView, R.string.snackbar_text, Snackbar.LENGTH_LONG)
.setAction(R.string.snackbar_action_undo, clickListener)
.show();
There is one more option u can trust on
Try implementing AlarmManger as the Dialog is shown to user
For AlarmManger Implementation
Please use
PendingIntent.getBroadcast(mContext,
12345, intent, PendingIntent.FLAG_ONE_SHOT);
and u can also cancel alarm manager
I have chosen the hint from Ghorbanzadeh to use the Toast. Now it looks like this:
private void startRound() {
round = round +1;
if( round != 1 ) {
CharSequence text = ("Starte Runde " + round);
int duration = Toast.LENGTH_SHORT;
Toast toast = Toast.makeText(this, text, duration);
toast.setGravity(Gravity.CENTER_HORIZONTAL |Gravity.CENTER_VERTICAL, 0, 0);
toast.show();
}
}
The messsage is centered in the screen and lasts long enough to be seen. This was the short and easy code that I was looking for.
Thanks again for the fast help.

How to get the DialogPreference POSITIVE_BUTTON to work on OnClick?

I'm trying to write something to set a password with DialogPrefence.
How do I get the onClick() event at OK button from the dialog?
Here is the code:
package com.kontrol.app;
import android.content.Context;
import android.content.DialogInterface;
import android.preference.DialogPreference;
import android.util.AttributeSet;
public class SS1_Senha extends DialogPreference implements DialogInterface.OnClickListener{
public SS1_Senha(Context context, AttributeSet attrs) {
super(context, attrs);
setPersistent(false);
setDialogLayoutResource(R.layout.ss1_senha);
setPositiveButton("Ok", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
//Action after OK
}
});
}
}
You need to implement the DialogInterface.OnClickListener and handle the OnClick events of each buttons
Create a custom DialogPreference class like this
public class CustomDialogPreference extends DialogPreference implements DialogInterface.OnClickListener{
public CustomDialogPreference(Context context, AttributeSet attrs) {
super(context, attrs);
setPersistent(false);
setDialogLayoutResource(R.layout.image_dialog);
setPositiveButtonText("OK");
setNegativeButtonText("CANCEL");
}
#Override
public void onClick(DialogInterface dialog, int which){
if(which == DialogInterface.BUTTON_POSITIVE) {
// do your stuff to handle positive button
}else if(which == DialogInterface.BUTTON_NEGATIVE){
// do your stuff to handle negative button
}
}
}
if I understand correctly, you need to know about key pressed event in another classes (not in the SS1_Senha). For this you can use listeners (observers) pattern or handler.
To show an alert dialog you can use AlertDialog.builder.
For example:
AlertDialog alertDialog = new AlertDialog.Builder(
AlertDialogActivity.this).create();
// Setting Dialog Title
alertDialog.setTitle("Alert Dialog");
// Setting Dialog Message
alertDialog.setMessage("My Message");
// Setting OK Button
alertDialog.setButton("OK", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
// Write your code here to execute after dialog closed
Toast.makeText(getApplicationContext(), "You clicked on OK", Toast.LENGTH_SHORT).show();
}
});
// Showing Alert Message
alertDialog.show();

Where to put activity code?

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!

AlertDialog not showing up

I am trying to make a simple little test on an Android emulator called YouWave for Android 4.1.1 (I believe it is).
I am using IntelliJ to generate an APK file to use with the emulator. I simply went into Artifacts and made one Artifact to create an APK file. Didn't do anything else.
The idea of the app is simple. When some code have run, show the results of the code in a little box that I can read and then close when I have read it. But when I fire the application in the emulator it says "Loading 100 %" and then nothing happens. (It worked with two other applications that came with the software so I know it works otherwise.)
Here is the code:
package com.example.DalvikTest;
import android.app.Activity;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.os.Bundle;
import android.content.Context;
public class MyActivity extends Activity {
final Context context = this;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
long time = RunTest();
AlertDialog.Builder builder = new AlertDialog.Builder(context);
builder.setTitle("Results");
builder.setCancelable(true);
String s = "Time: " + time + " ns";
builder
.setMessage(s)
.setCancelable(false)
.setPositiveButton("Yes",new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
MyActivity.this.finish();
}
})
.setNegativeButton("No",new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
dialog.cancel();
}
});
AlertDialog alert = builder.create();
alert.show();
}
public long RunTest() {
long timeStart = System.nanoTime();
long sum = 0;
int[] arr = new int[1000000];
for(int i : arr) {
sum += i;
}
long timeEnd = System.nanoTime();
long result = timeEnd - timeStart;
return result;
}
}
Why is the box with the results now showing up?
I used YouWave some time ago and had the problem of some apps not working too.
Your problem might be in the fact that you are using debugable and development signed apk file that YouWave player doesn't support (It didn't work in older versions at least) and you need to export your file signed with production key. It's quite simple actually because you can generate your own key, considering your rep on website I am guessing you are already familiar with this proces put for reference if someone needs to know everything is explained here http://developer.android.com/tools/publishing/app-signing.html
sorry, i cant comment because i have not enough reputation,
what i want to say is:
i tested youre code and it worked so it should be fine.
and to clean up youre code type this in oncreate:
showDialog();
and under oncreate type youre code like this:
public void showDialog() {
AlertDialog.Builder builder = new AlertDialog.Builder(context);
builder.setTitle("Results");
builder.setCancelable(true);
String s = "Time: " + time + " ns";
builder
.setMessage(s)
.setCancelable(false)
.setPositiveButton("Yes",new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
MyActivity.this.finish();
}
})
.setNegativeButton("No",new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
dialog.cancel();
}
});
AlertDialog alert = builder.create();
alert.show();
}

Categories

Resources