I am trying to use AlertDialog widget in my app, but whatever I do the app crashes at launch. I know something is messed up or not defined but can't seem to find it.I have defined a button for triggering the alert dialog and set 'yes' and 'no' options for the dialog. Selecting 'yes' will result in exiting the app and showing a toast and Selecting 'no' will close the alert dialog and return to app by showing a toast. This is how it should work on paper but as I said the app will crash on launch.
My code:
package com.example.togglebutton;
import androidx.appcompat.app.AlertDialog;
import androidx.appcompat.app.AppCompatActivity;
import android.content.DialogInterface;
import android.os.Bundle;
import android.view.View;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.Button;
import android.widget.Toast;
import android.widget.ToggleButton;
public class MainActivity extends AppCompatActivity {
private Button bt;
AlertDialog.Builder builder;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
bt = (Button) findViewById(R.id.btn);
builder = new AlertDialog.Builder(this);
bt.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
builder.setMessage("Do you want to close this application ?")
.setCancelable(false)
.setPositiveButton("Yes", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id, ) {
finish();
Toast.makeText(getApplicationContext(), "you chose yes",
Toast.LENGTH_SHORT).show();
}
})
.setNegativeButton("No", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
dialog.cancel();
Toast.makeText(getApplicationContext(), "you chose no ",
Toast.LENGTH_SHORT).show();
}
});
AlertDialog alert = builder.create();
alert.setTitle("AlertDialogExample");
alert.show();
}
});
}
}
SOLUTION OF YOUR PROBLEM
You need to set the layout of the activity and in the above-posted code what we can see that it is missing. So just add the line below super.onCreate(savedInstanceState);
setContentView(R.layout.YOUR_LAYOUT_NAME);
NOTE: Replace YOUR_LAYOUT_NAME with the name of the layout file which you have defined for MainActivity.
Because you forgot this line
super.onCreate(savedInstanceState);
setContentView(R.layout.yourLayout);
Add setContentView(R.layout.activity_main) below super.onCreate(savedInstanceState);
Related
EDITED
I've created a simple UI in Android Studio which requires to use Button, Radio Group, Edit Text etc.
So every time I press the radio button, it toasts the message which button was pressed.
If I type a specific word in search bar, in my example "Car", and the radio button is on Pictures, for example, the dialog box should pop up with the message "Pictures were found", or lets say I type in "Car" again and the radio button is checked on "Videos", then, in this case, the dialog box message will be "Videos were found".
If I press the search button, and the search field(EditText) is empty or have some other word(not "Car"), the dialog box's message should be "Unsuccessful search". So I could solve the first problem, my problem is with the Button and Search field, I can't find a way to link them to compare the user input with word "Car" and show the required dialog box.
This is what it looks like
This is what I tried so far.
EDITED
package com.example.administrator.simpleui;
import android.content.DialogInterface;
import android.support.v7.app.AlertDialog;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.RadioButton;
import android.widget.RadioGroup;
import android.widget.Toast;
public class MainActivity extends AppCompatActivity {
RadioGroup radioGroup;
RadioButton radioButton;
Button button;
// EditText editText;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
radioGroup = (RadioGroup) findViewById(R.id.radio_group);
final EditText editText = (EditText) findViewById(R.id.edit_text);
button = (Button) findViewById(R.id.myButton);
int radioId1 = radioGroup.getCheckedRadioButtonId();
radioButton = (RadioButton) findViewById(radioId1);
final AlertDialog.Builder alertDialog1 = new AlertDialog.Builder(this);
alertDialog1.setTitle("Note").setMessage("Fail search").setPositiveButton("Ok", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialogInterface, int i) {
Toast.makeText(getApplicationContext(),"Ok was pressed",Toast.LENGTH_SHORT).show();
}
}).setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialogInterface, int i) {
Toast.makeText(getApplicationContext(),"Cancel was pressed",Toast.LENGTH_SHORT).show();
}
}).create();
final AlertDialog.Builder alertDialog2 = new AlertDialog.Builder(this);
alertDialog2.setTitle("Note").setMessage(radioButton.getText() + " was found").setPositiveButton("ok", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialogInterface, int i) {
Toast.makeText(getApplicationContext(),"ok was pressed",Toast.LENGTH_SHORT).show();
}
}).setNegativeButton("cancel", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialogInterface, int i) {
Toast.makeText(getApplicationContext(),"ok was pressed",Toast.LENGTH_SHORT).show();
}
}).create();
button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
if(editText.getEditableText().toString().equals("Car")) {
alertDialog2.show();
}else {
alertDialog1.show();
}
}
});
}
public void checkButton(View v){
int radioId = radioGroup.getCheckedRadioButtonId();
radioButton = (RadioButton) findViewById(radioId);
Toast.makeText(this, radioButton.getText() + " was selected",Toast.LENGTH_SHORT).show();
}
}
So i solved it by myself but still have one small bug,everytime i the Search for key word Car it the dialog box message shows me the value of radio button which i declared in my xml file(i have 4 radio buttons here, Videos,Pictures,Blog and FAQ and the one is checked by default is Videos) => so i always have the message like "Videos was found", but i need it show according the checked radio button, for example if the radio button is checked on Pictures and i typed in car then the the message is "Pictures was found", but my code only generates with videos. Problem is in this line:
final AlertDialog.Builder alertDialog2 = new AlertDialog.Builder(this);
alertDialog2.setTitle("Note").setMessage(radioButton.getText() + " was found").setPositiveButton("ok", new DialogInterface.OnClickListener()
Don't know how to make it to see the current radio button.
I wrote code to check the GPS settings and make an alert dialog, but it doesn't show up in android emulator.
This is the code that used to check the GPS settings and show the alert dialog.
package com.example.user.testlocation;
import android.content.DialogInterface;
import android.content.Intent;
import android.location.LocationManager;
import android.provider.Settings;
import android.support.v7.app.AlertDialog;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
public class Location extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_location);
}
private void isLocationEnalbled(){
LocationManager locationManager=(LocationManager)getSystemService(LOCATION_SERVICE);
if(!locationManager.isProviderEnabled(LocationManager.GPS_PROVIDER)|| !locationManager.isProviderEnabled(LocationManager.NETWORK_PROVIDER)){
AlertDialog.Builder alertDialog=new AlertDialog.Builder(this);
alertDialog.setTitle("Enable Location");
alertDialog.setMessage("Your locations setting is not enabled. Please enabled it in settings menu.");
alertDialog.setPositiveButton("Location Settings", new DialogInterface.OnClickListener(){
public void onClick(DialogInterface dialog, int which){
Intent intent=new Intent(Settings.ACTION_LOCATION_SOURCE_SETTINGS);
startActivity(intent);
}
});
alertDialog.setNegativeButton("Cancel", new DialogInterface.OnClickListener(){
public void onClick(DialogInterface dialog, int which){
dialog.cancel();
}
});
AlertDialog alert=alertDialog.create();
alert.show();
}
else{
AlertDialog.Builder alertDialog=new AlertDialog.Builder(this);
alertDialog.setTitle("Confirm Location");
alertDialog.setMessage("Your Location is enabled, please enjoy");
alertDialog.setNegativeButton("Back to interface",new DialogInterface.OnClickListener(){
public void onClick(DialogInterface dialog, int which){
dialog.cancel();
}
});
AlertDialog alert=alertDialog.create();
alert.show();
}
}
}
It doesn't show any error, but the alert dialog doesn't display when I implement it.
You never call the isLocationEnalbled() method which does the check. Add this to your class, so that the app checks isLocationEnalbled() everytime the activity is resumed.
#Override
public void onResume() {
super.onResume();
isLocationEnalbled();
}
in your onCreate() method you have to call isLocationEnalbled()
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_location);
isLocationEnalbled()
}
So I'm trying to create a dialog pop up. Here's the Dialog fragment I created in a separate DialogClass.Java file
import android.app.AlertDialog;
import android.app.Dialog;
import android.app.DialogFragment;
import android.content.DialogInterface;
import android.os.Bundle;
import android.widget.Toast;
public class DialogClass extends DialogFragment{
#Override
public Dialog onCreateDialog(Bundle savedInstanceState) {
AlertDialog.Builder newAlertDialog = new AlertDialog.Builder(getActivity());
newAlertDialog.setTitle("Dialog");
newAlertDialog.setMessage("This is a dialog");
newAlertDialog.setPositiveButton(("OK"), new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
Toast.makeText(getActivity(), ("You clicked Ok"), Toast.LENGTH_SHORT).show();
}
});
newAlertDialog.setNegativeButton(("Cancel"), new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
Toast.makeText(getActivity(), ("You clicked Cancel"), Toast.LENGTH_SHORT).show();
}
});
return super.onCreateDialog(savedInstanceState);
}
}
Then when I use this class to create a method it brings us a blank dialog box when I run the app. This is how I use it:
Note: myButtinClick is a method that runs on the click of a button.
public void myButtonClick(View view) {
DialogFragment myFrag = new DialogClass();
myFrag.show(getFragmentManager(), "");
}
Please can anyone figure out what I am doing wrong?
See a screenshot of what the Dialog looks like via this link.
http://i.stack.imgur.com/xsQQj.png
You've only created the Dialog builder, but not the Dialog itself.
You should return newAlertDialog.create() and rename newAlertDialog to dialogBuilder or something like that.
I need help implementing the code to add a negative or positive button to close my alert dialogue (any help would be much appreciated). I think some of my punctuation in the code needs altering as well so any help would be great :)
package kevin.erica.box;
import android.app.Activity;
import android.app.AlertDialog;
import android.app.Dialog;
import android.content.DialogInterface;
import android.content.res.Resources;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.ImageButton;
import android.widget.TextView;
import java.util.Random;
public class TheKevinAndEricaBoxActivity extends Activity {
/** Called when the activity is first created. */
private String[] myString;
private String list;
private String[] myString2;
private String list2;
private static final Random rgenerator = new Random();
private static final Random rgenerator2 = new Random();
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
Resources res = getResources();
myString = res.getStringArray(R.array.myArray);
list = myString[rgenerator.nextInt(myString.length)];
myString2 = res.getStringArray(R.array.myArray2);
list2 = myString2[rgenerator.nextInt(myString2.length)];
ImageButton ib = (ImageButton) findViewById(R.id.imagebutton1);
ib.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View erica) {
AlertDialog.Builder b = new AlertDialog.Builder(
TheKevinAndEricaBoxActivity.this);
b.setMessage(myString[rgenerator.nextInt(myString.length)]);
b.setTitle(R.string.title1);
Dialog d = b.create();
d.show();
}
});
}
}
You can use the below code in your app::::
AlertDialog.Builder b = new AlertDialog.Builder(TheKevinAndEricaBoxActivity.this);
b.setMessage(myString[rgenerator.nextInt(myString.length)]);
b.setTitle(R.string.title1);
b.setPositiveButton("Button Text", new DialogInterface.OnClickListener(){
#Override
public void onClick(DialogInterface dialog, int which){
//stuff you want the button to do
}
});
b.setNegativeButton("Button Text", new DialogInterface.OnClickListener(){
#Override
public void onClick(DialogInterface dialog, int which){
//stuff you want the button to do
}
});
AlertDialog.Builder alertDialogBuilder = new AlertDialog.Builder(
context);
// set title
alertDialogBuilder.setTitle("Your Title");
// set dialog message
alertDialogBuilder
.setMessage("Click yes to exit!")
.setCancelable(false)
.setPositiveButton("Yes",new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog,int id) {
// if this button is clicked, close
// current activity
MainActivity.this.finish();
}
})
.setNegativeButton("No",new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog,int id) {
// if this button is clicked, just close
// the dialog box and do nothing
dialog.cancel();
}
});
// create alert dialog
AlertDialog alertDialog = alertDialogBuilder.create();
// show it
alertDialog.show();
Search in Google before you post a question..
Here is a guide.
Take notice of the functions "set___Button".
b.setNegativeButton("Button Text", new DialogInterface.OnClickListener(){
#Override
public void onClick(DialogInterface dialog, int which){
//stuff you want the button to do
});
You need make a custom dialog. See the sample:
Context mContext = getApplicationContext();
Dialog dialog = new Dialog(mContext);
dialog.setContentView(R.layout.custom_dialog);
dialog.setTitle("Custom Dialog");
TextView text = (TextView) dialog.findViewById(R.id.text);
text.setText("Hello, this is a custom dialog!");
ImageView image = (ImageView) dialog.findViewById(R.id.image);
image.setImageResource(R.drawable.android);
This is the full sample:
http://developer.android.com/guide/topics/ui/dialogs.html
I'm new at Eclipse and the Android applications making so here comes a very rookie question. How can I make this function work properly? I have just copy > paste it to my public class nowActivity extends Activity { and fixed the errors that accord. The function is as follows:
package weather.right;
import weather.right.now.R;
import android.app.Activity;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.location.LocationManager;
import android.net.Uri;
import android.os.Bundle;
import android.view.View;
import android.widget.TextView;
import android.widget.Toast;
public class nowActivity extends Activity {
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
LocationManager locationManager = (LocationManager) getSystemService(LOCATION_SERVICE);
if (locationManager.isProviderEnabled(LocationManager.GPS_PROVIDER)){
Toast.makeText(this, "GPS is Enabled in your devide", Toast.LENGTH_SHORT).show();
}else{
showGPSDisabledAlertToUser();
}
}
public void goToSo(View view) {
goToUrl("http://erik-edgren.nu/weather");
}
private void goToUrl(String url) {
Uri uriUrl = Uri.parse(url);
Intent launchBrowser = new Intent(Intent.ACTION_VIEW, uriUrl);
startActivity(launchBrowser);
}
private void showGPSDisabledAlertToUser(){
AlertDialog.Builder alertDialogBuilder = new AlertDialog.Builder(this);
alertDialogBuilder.setMessage("GPS is disabled in your device. Would you like to enable it?")
.setCancelable(false)
.setPositiveButton("Goto Settings Page To Enable GPS",
new DialogInterface.OnClickListener(){
public void onClick(DialogInterface dialog, int id){
Intent callGPSSettingIntent = new Intent(
android.provider.Settings.ACTION_LOCATION_SOURCE_SETTINGS);
startActivity(callGPSSettingIntent);
}
});
alertDialogBuilder.setNegativeButton("Cancel",
new DialogInterface.OnClickListener(){
public void onClick(DialogInterface dialog, int id){
dialog.cancel();
}
});
AlertDialog alert = alertDialogBuilder.create();
alert.show();
}
}
Thanks in advance.
protected void onCreate1(Bundle savedInstanceState) should be protected void onCreate(Bundle savedInstanceState)?
You are supposed to override the onCreate() method. See this for more details.
For Android, sub-classes of Activity are supposed to implement certain methods so to do this you have to override certain methods by matching the parent class' methods exactly. onCreate() is one such method.
For the emulator, GPS can be tested by following the guide here. Otherwise it will show up as disabled.