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.
Related
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);
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()
}
I am trying to implement AlertDialog based on DialogFragment with this code:
public class AlertDialogFragment extends DialogFragment {
#Override
public Dialog onCreateDialog(Bundle savedInstanceState) {
return new AlertDialog.Builder(getActivity())
.setTitle("title")
.setMessage("message")
.setPositiveButton(android.R.string.yes, new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
}
})
.setNegativeButton(android.R.string.no, new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
}
})
.create();
}
}
It working well, but I get a strange white border around AlertDialog:
How to remove this border (preferably programmatically)?
UPDATE: my styles.xml contains this code:
<style name="AppBaseTheme" parent="#android:style/Theme.Holo.Light">
<item name="android:alertDialogTheme">#style/MyDialogTheme</item>
</style>
<style name="MyDialogTheme" parent="#android:style/Theme.Holo.Light.Dialog"></style>
When I remove <item name="android:alertDialogTheme">#style/MyDialogTheme</item> row, this issue is gone away. But I need this row because I want to customize AlertDialog. How to fix this style?
I have just checked your code ,but have not get any issue like this.
I call the class like
package com.example.test;
import android.app.Activity;
import android.app.AlertDialog;
import android.app.Dialog;
import android.content.DialogInterface;
import android.os.Bundle;
import android.support.v4.app.DialogFragment;
import android.support.v4.app.FragmentActivity;
import android.support.v4.app.FragmentManager;
import android.widget.Toast;
public class A extends FragmentActivity{
#Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
AlertDialogFragment al=new AlertDialogFragment();
FragmentManager fm = getSupportFragmentManager();
al.show(fm, "test");
}
class AlertDialogFragment extends DialogFragment {
#Override
public Dialog onCreateDialog(Bundle savedInstanceState) {
return new AlertDialog.Builder(getActivity())
.setTitle("title")
.setMessage("message")
.setPositiveButton(android.R.string.yes, new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
}
})
.setNegativeButton(android.R.string.no, new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
}
})
.create();
}
}
}
First of all sorry if this post may seem a duplicate but I am very new to Android programming and posting this question only when I am still not able to get a satisfactory answer for use of getActivity.
Theoretically I understand the use of getActivity() from the several posts here but I am confused how it is working in my code.
I have a class MainActivity from which I am creating a dialog onclick of a checkbox.
I have another class TaxDialog where the dialog is implemented. On click of Yes/No buttons I am calling methods define in MainActivity class.
Below are the codes:
MainActivty
import android.annotation.SuppressLint;
import android.os.Bundle;
import android.support.v4.app.DialogFragment;
import android.support.v7.app.ActionBarActivity;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;
public class MainActivity extends ActionBarActivity implements View.OnClickListener, View.OnFocusChangeListener {
// onCheck of checkbox showNoticeDialog is called
public void showNoticeDialog() {
// Create an instance of the dialog fragment and show it
Log.i("MyActivity", "Inside showNoticeDialog");
DialogFragment dialog = new TaxDialog();
Bundle args = new Bundle();
args.putString("title", "Test");
args.putString("message", "Test Message");
dialog.setArguments(args);
dialog.show(getSupportFragmentManager(), "dialog");
}
public void doPositiveClick(){
Log.i("MyActivity", "Inside +ve");
}
public void doNegativeClick(){
Log.i("MyActivity", "Inside -ve");
}
}
TaxDialog
import android.app.Activity;
import android.app.AlertDialog;
import android.app.Dialog;
import android.content.DialogInterface;
import android.os.Bundle;
import android.support.v4.app.DialogFragment;
import android.util.Log;
public class TaxDialog extends DialogFragment {
#Override
public Dialog onCreateDialog(Bundle savedInstanceState) {
Bundle args = getArguments();
String title = args.getString("title");
String message = args.getString("message");
AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());
builder.setTitle(title);
builder.setMessage(message);
builder.setPositiveButton(android.R.string.ok, new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
//getTargetFragment().onActivityResult(getTargetRequestCode(), Activity.RESULT_OK, null);
Log.i("MyActivity", "Expected fault area.");
((MainActivity) getActivity()).doPositiveClick();
}
});
builder.setNegativeButton(android.R.string.cancel, new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
((MainActivity) getActivity()).doNegativeClick();
}
});
builder.create();
return builder.create();
}
}
Here I want to understand how below line works
((MainActivity) getActivity()).doPositiveClick();
and also please make me aware of other ways of doing the same thing (something like MainActivity.this.getActivity() or something else).
Thanks a lot.
EDIT
Thanks everyone. Probably I framed the question incorrectly. My only doubt was how getActivity() returns the Activity reference. Now I understand.
Lets split it up:
getActivity() can be used in a Fragment for getting the parent Activity of the Fragment (basically the Activity that displayed the Fragment).
((MainActivity) getActivity()) additionally casts the result of getActivity() to MainActivity. Usually, you just know that getActivity() returns an object of type Activity, but using this cast, you tell the compiler that you are sure the object is a specific subclass of Activity, namely MainActivity. You need to do that in your case, because doPositiveClick() is only implemented in MainActivity, and not in Activity, so you have to assure the compiler the object is a MainActivity, and it will respond to the method doPositiveClick().
doPositiveClick() simply calls that method on the MainActivity object that is returned by getActivity().
The approach you are using is not the best way to accomplish what you want to do. Android have a good support for listeners, and for communicating with fragments. So, lets see how to communicate fragment->activity direction.
First, you need to make your MainActivity a listener from what happens on a dialog, so the best way to do this is implementing DialogInterface.OnClickListener on your MainActivity and override the onClick(DialogInterface dialog, int which) method, this method will be called from your fragmen. So until now everything is done in your MainActivity.
Now, in your fragment, you have to override the onAttach(Activity activity) method, this is the first method called when the fragment is built and this method comes with our parent Activity, inside this method initialize the listener of your fragment (your MainActivity).
Your fragment should look like this:
private DialogInterface.OnClickListener listener;
#Override
public Dialog onCreateDialog(Bundle savedInstanceState) {
Bundle args = getArguments();
String title = args.getString("title");
String message = args.getString("message");
AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());
builder.setTitle(title);
builder.setMessage(message);
builder.setPositiveButton(android.R.string.ok, new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
//Calling our MainActivity Listener with a positive answer
listener.onClick(getDialog(), 1);
}
});
builder.setNegativeButton(android.R.string.cancel, new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
//Calling our MainActivity Listener with a negative answer
listener.onClick(getDialog(), 0);
}
});
builder.create();
return builder.create();
}
#Override
public void onAttach(Activity activity) {
super.onAttach(activity);
if (activity instanceof DialogInterface.OnClickListener) {
listener = (DialogInterface.OnClickListener) activity;
} else {
throw new ClassCastException(activity.toString()
+ " must implemenet DialogInterface.OnClickListener");
}
}
And your main activity onClick() method should look like this:
#Override
public void onClick(DialogInterface dialog, int which) {
switch (which) {
case 0:
//Do your negative thing
break;
case 1:
//Do your positive thing
break;
}
Toast.makeText(this, "You clicked "+ which, Toast.LENGTH_SHORT).show();
}
This is the best approach to do what you want to do, forget about "hard" cast your MainActivity class. Hope it helps you!
I believe you can jsut do
this.doPsitiveClick();
((MainActivity)getActivity()) is just getting the current active activity and casting that to be MainActivity..
When you use fragments it is only way to get context. As above, you are using DialogFragment and in OnClickListener there is need of context.
getActivity() is user-defined.
public final Activity getActivity() - Return the Activity this fragment is currently associated with.
For your code, in TaxDialog which is extending DialogFragment need a context to create AlertDialog with AlertDialog.Builder. So here, getActivity() as a parameter in AlertDialog.Builder is passing as context which tells to AlertDialog Fragment that by which activity it is attached to.
My Alert dialog message doesn't come out because I cannot get the text of the button. After that the program will directly go to my EventActivity. How can settle this problem?
public void onClick(View v) {
// TODO Auto-generated method stub
if (v.getId() == insertButton.getId()) {
if(colorButton.getText().toString().equals("Color")){
colorAlert.show();
}
}
}
This is variable
AlertDialog colorAlert;
AlertDialog in the OnCreate()
AlertDialog.Builder CA = new AlertDialog.Builder(this);
CA.setTitle("Alert Message!");
CA.setMessage("Please insert the level of important for the event.");
CA.setPositiveButton("OK", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
// TODO Auto-generated method stub
colorAlert.dismiss();
startActivity(new Intent(this, EventActivity.class));
}
});
colorAlert = CA.create();
When you compare a String in Java, use YOUR_STRING.equals("Color");
Update:
change your while into if , because your are running it once.
The move your
startActivity(new Intent(this, EventActivity.class));
in your alertbox positive button handler.
Comparing Strings in Java.
Ok look like you need more help, here is one solution... i let you deal with the EventActivity ;)
import android.os.Bundle;
import android.app.Activity;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.Context;
import android.content.Intent;
import android.view.Menu;
import android.view.View;
import android.widget.*;
public class MainActivity extends Activity {
final Context context=this;
public static String EXTRA_MESSAGE;
Button colorButton;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main_test);
colorButton = (Button) findViewById(R.id.button1);
colorButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if(colorButton.getText().toString().equals("Color")){
AlertDialog.Builder alertBuilder = new AlertDialog.Builder(context);
alertBuilder.setMessage("myDialog").setCancelable(false).setPositiveButton("yes", new DialogInterface.OnClickListener(){
public void onClick(DialogInterface dialog, int which) {
dialog.cancel();
Intent intent = new Intent(MainActivity.this, EventActivity.class);
String message = colorButton.getText().toString();
intent.putExtra(EXTRA_MESSAGE, message);
startActivity(intent);
}
}).setNegativeButton("cancel", new DialogInterface.OnClickListener(){
public void onClick(DialogInterface dialog, int which) {
dialog.cancel();
}
});
AlertDialog myAlert = alertBuilder.create();
myAlert.show();
}
}
});
}
Adding to wtsang02 answer, you shouldn't put your alert.show in a while like this one... I see coming the infinite loop ;)