I am opening an AlertDialog to present the user a text input in order to name a new item. This works fine the first time it opens. But the second time I click the button that launches the dialog, the app crashes. I get this error:
12-02 16:01:04.205: E/AndroidRuntime(515): java.lang.IllegalStateException: The specified child already has a parent. You must call removeView() on the child's parent first.
I'm not sure what this means or where I would call this removeView().
Here is my code:
public class ShoppingList extends Activity implements OnClickListener{
private AlertDialog.Builder m_alert;
private Context m_context;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.shopping_list);
m_context = getApplicationContext();
LayoutInflater inflater = (LayoutInflater) m_context.getSystemService(LAYOUT_INFLATER_SERVICE);
View layout = inflater.inflate(R.layout.add_shopping_list, (ViewGroup) findViewById(R.id.layout_root));
m_alert = new AlertDialog.Builder(ShoppingList.this);
//final EditText input = new EditText(this);
//m_alert.setView(input);
m_alert.setView(layout);
final EditText input = (EditText)layout.findViewById(R.id.new_sl_name);
m_alert.setPositiveButton(R.string.add_button, new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int whichButton) {
String value = input.getText().toString().trim();
Toast.makeText(m_context, value,
Toast.LENGTH_SHORT).show();
m_alert.create();
}
});
m_alert.setNegativeButton(R.string.cancel_button,
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int whichButton) {
dialog.cancel();
m_alert.create();
}
}
);
// Add Button. . .
Button addButton = (Button)findViewById(R.id.add_sl_button);
addButton.setOnClickListener(this);
}
public void onClick(View v) {
if(!this.isFinishing())
m_alert.show();
}
}
This is most likely because you are using m_alert.create(); in a wrong place.
Check this tutorial on dialogs: Dialogs.
m_alert.create() is called after clicking on the positive and negative buttons. What this does, is create the dialog again.
Use m_alert.dismiss() instead, so your dialog is dismissed, and you can use it again later
This might help someone. I build most of my apps on my laptop. I just got my office put back together and got my pc fired up. When I tried to load my projects from my cloud storage on my pc it seemed like there were a few build errors that happened. For AlertDialog.Builder Crash I notice that my pc on a fresh Android Studio install set my "import" to android.support.v7.app.AlertDialog instead of android.app.AlertDialog for some reason. I deleted the import and re selected the android.app.AlertDialog and everything worked like normal. I don't know if this is a bug or just how Android Studio installs files as a default. For similar errors might be worth while deleting all the import files and re selecting the ones you know apply. Good Luck!
Related
I am working on an application for my personal project.
I plan to have a table/chart in my application, and next to the application I plan to put a button which is what I need help with.
Could you please tell me what code I can use to create a button which when clicked:
Creates a new window(popup or not is fine) where there is a editText
for the users to input some text and when they are done the text is
inserted into a cell of the table?
Maybe useless information:
My application's "table" should be borderless and maybe instead of table is list with separators between the user's text
The application is essentially a to do list but when they click the button to insert a new task it is in a new window.
Create an AlertDialogBox
AlertDialog.Builder builder = new AlertDialog.Builder(getApplicationContext(), );
builder.setMessage("Message")
.setIcon(R.drawable.icon)
.setTitle("Title");
builder.setPositiveButton("OK", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
//Todo
}
});
builder.setNegativeButton("CANCEL", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
//Todo
}
});
AlertDialog alertDialog = builder.create();
alertDialog.show();
When you put a button in the XML code you need to fetch it by it's id in the activity (java class), then use
button.onClickListener( v -> {
//here you can have a code block that will be done once the button is clicked
//put Ashutosh Sagar code for the alert dialog
Keep in mind that you can make the dialog as you want by customizing it to your preferences. This usually requires another XML layout just for the look of the dialog and some more reading on Alert Dialog.
As it was said above by Aman, we can clearly post you the code but that way you won't learn anything. Happy coding.
In my app I need multiple dialogs or multiple views which will be updated after clicking positive and negative dialog buttons.
How should it looks in example:
1) Call first Dialog1
2) Inside Dialog1 I have some data and 2 buttons (positive and negative) onClick possitive Button I go to next Dialog2 on negative I exit dialogs.
3) Inside Dialog2 similar situation click on possitive button provides me to next dialog or dialog view but negative button leeds back to Dialog1
for now my code looks like :
public class DialogChoiceActivity extends DialogFragment {
LayoutInflater inflater;
View v;
public Dialog onCreateDialog(Bundle savedInstanceState) {
inflater = getActivity().getLayoutInflater();
v = inflater.inflate(R.layout.dialog_email,null);
final AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());
final Dialog dialog2 = builder.create();
builder.setTitle("Email " + " 1/10");
builder.setView(v).setPositiveButton("NEXT", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
}
}).setNegativeButton("Exit", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
}
});
return builder.create();
}
First of all I'm not sure which way is better create multiple dialogs or one Dialog with multiple Views. Which way is better if I want easily move from one dialog to another (or view). There are some problems because I cant update builder object or dissmiss it so how shold all this looks like ? what is best way to do that
Sorry for chaotic and weak language.
Create DialogFragment as you needed.
Make clicking on the positiveButton to show next dialog and dismiss current dialog.
From next dialog, clicking on negativeButton to show previous dialog and dismiss current one.
Initially in my app I am creating an AlertDialog which has three buttons, in which the middle button opens up another AlertDialog. The problem is that when the second AlertDialog closes after a button is pressed, the first one closes with it. I think both AlertDialogs get closed after I press a button on the second AlertDialog.
What I want is for the first AlertDialog to open another AlertDialog that has its own buttons, and when second AlertDialog presses a button, it only closes itself and goes back to the first one. Is there any way to achieve this?
Here is the code for the button used to open the AlertDialog:
final ImageButton fabgroup = (ImageButton) findViewById(R.id.groupButton);
Here's the code for a button that opens an AlertDialog that contains another button that opens another AlertDialog using the middle button (create button) on itself, but closes them both when a button on the second one is pressed (either the yes or no button, which is not what I want as I only want the second one to close itself and go back to the first AlertDialog, and yea this sounds pretty confusing in theory so I can try to clarify if needed):
fabgroup.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
final AlertDialog.Builder helpBuilder = new AlertDialog.Builder(CreateNote.this);
helpBuilder.setTitle("Select a group");
helpBuilder.setMessage("Add to group?");
final TextView input = new TextView(mainactiv.this);
input.setSingleLine();
input.setText("");
helpBuilder.setView(input);
helpBuilder.setNegativeButton("Yes",
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
// Do nothing but close the dialog
Toast.makeText(CreateNote.this, "Page has been added to group", Toast.LENGTH_SHORT).show();
}
});
helpBuilder.setNeutralButton("Create", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
//open another alertbox
AlertDialog.Builder helpBuilder2 = new AlertDialog.Builder(CreateNote.this);
helpBuilder2.setTitle("Assign a new group");
helpBuilder2.setMessage("Create group?");
final EditText input = new EditText(CreateNote.this);
input.setSingleLine();
input.setText("");
helpBuilder2.setView(input);
helpBuilder2.setNegativeButton("Yes",
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
// Create Group
Toast.makeText(CreateNote.this, "Group has been created", Toast.LENGTH_SHORT).show();
}
});
helpBuilder2.setPositiveButton("No", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
// Do nothing
}
});
// Remember, create doesn't show the dialog
AlertDialog helpDialog2 = helpBuilder2.create();
helpDialog2.show();
}
});
helpBuilder.setPositiveButton("No", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
// Do nothing
}
});
// Remember, create doesn't show the dialog
AlertDialog helpDialog = helpBuilder.create();
helpDialog.show();
}
});
Help would be greatly appreciated.
I eventually managed to solve this problem by creating two separate functions to generate each dialog box, and when one closes it calls the function to create the other one, kinda like recycling (or maybe closer to looping functions). Although, I'm not entirely sure how performance heavy this is, but it seems to do the job without any issues from what I'm testing. If anyone would like to chime in on how this could be an issue, then I'm open to hearing what others have to say about the negative points of using alert dialog boxes this way.
You can show an activity as dialog. Put this in your manifest file.
<activity android:theme="#android:style/Theme.Dialog" android:excludeFromRecents="true"/>
From this answer: Android Activity as a dialog
#Override
public void run() {
//Create thread that can alter the UI
AlarmPage.this.runOnUiThread(new Runnable() {
public void run() {
cal = Calendar.getInstance();
//See if current time matches set alarm time
if((cal.get(Calendar.HOUR_OF_DAY) == alarmTime.getCurrentHour())
&& (cal.get(Calendar.MINUTE) == alarmTime.getCurrentMinute())){
//If the sound is playing, stop it and rewind
if(sound.isPlaying()){
ShowDialog();
alarmTimer.cancel();
alarmTask.cancel();
alarmTask = new PlaySoundTask();
alarmTimer = new Timer();
alarmTimer.schedule(alarmTask, sound.getDuration(), sound.getDuration());
}
sound.start();
}
}
});
}
public void ShowDialog() {
final AlertDialog.Builder alertDialog = new AlertDialog.Builder(this);
alertDialog.setTitle("REMINDER!");
alertDialog.setMessage("Turn off alarm by pressing off");
alertDialog.setNegativeButton("Off", new DialogInterface.OnClickListener(){
#Override
public void onClick(DialogInterface dialog, int which) {
Toast.makeText(getApplicationContext(), "OFF", Toast.LENGTH_SHORT);
}
});
alertDialog.show();
}
I am making a simple alarm clock app that notifies the user. I want to make a alert box that gives the user the option to turn off the alarm when it goes off. I was able to make the alert box, but it only appears in the app not outside of the app. I understand the app has to be in the background running. If I need to show more code or be more specific, just ask please.
Add a line as:
public void ShowDialog() {
final AlertDialog.Builder alertDialog = new AlertDialog.Builder(this);
alertDialog.setTitle("REMINDER!");
alertDialog.setMessage("Turn off alarm by pressing off");
alertDialog.setNegativeButton("Off", new DialogInterface.OnClickListener(){
#Override
public void onClick(DialogInterface dialog, int which) {
Toast.makeText(getApplicationContext(), "OFF", Toast.LENGTH_SHORT).show();
}
});
alertDialog.show();
// line you have to add
alertDialog.getWindow().setType(WindowManager.LayoutParams.TYPE_TOAST);
}
check now.
Do not accept answers if they don't address your question, it is misleading.
The accepted answer is not correct, as it will never work outside your application.
Reason:
It requires an activity context not application context.
If you provide application context, your app will crash with IllegalArgumentException- you need to use Theme.AppCompat or their decendents...
If you need functionality as actually stated in the question you have to have a separate activity themed as a Dialog like here
or you can add a custom view to your window using window manager and making it system level alert like here.
Do this create an Activity without ContentView or a View associated with it and call your alertDialog method in your onCreate also remember to set the background of the Activity to Transparent using ColourDrawable
And that activity will look like a dialog or will suit your preference, you can also fall back to Themes so you can set an Activity as Dialog and treat it like Dialog also use DialogFragment
i would like to have my rate button in my dialog to launch marketplace and go to my specific app.
Also how do i add in a message body into this dialog?
private void makeDialog() {
AlertDialog.Builder about = new AlertDialog.Builder(this);
about.setMessage("About The Giveaway");
about.setPositiveButton("Rate", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface arg0, int arg1) {
//action
}
});
about.setNegativeButton("Close", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface arg0, int arg1) {}
});
about.show();
}
}
I wrote a simple library to do that.
It is called AppRate and you can find it on GitHub here.
Features:
Do not prompt the user if the app has crashed once.
Decide exaclty when to prompt the user. (number of launches ...)
Customize the rate dialog to fit your application design.
Usage example:
It is very easy to install and use:
Drop the jar in your libs folder.
Then include the following code in the onCreate method of your MAIN activity.
new AppRate(this)
.setShowIfAppHasCrashed(false)
.setMinDaysUntilPrompt(0)
.setMinLaunchesUntilPrompt(20)
.init();
This code will show a default rate dialog after 20 lauches.
It will be shown only if the app has never crashed.
The rate button points to your application in the Google Play Store.
I hope this can help you. :)
You can launch the Market app using an Intent. Add this to your positiveButton onClick (replacing the URL with your app url)
Intent browserIntent = new Intent(
"android.intent.action.VIEW",
Uri.parse("https://market.android.com/details?id=com.animoca.prettyPetSalon");
startActivity(browserIntent);