Android Dialog not appearing - java

I just picked up the android SDK and eclipse and decided to write a simple dialog that pops up when you click a button, however I found out that the showDialog() method has been deprecated and that the DialogFragment was the best way to go about making one, so here it is:
package net.learn2develop.dialog;
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.FragmentManager;
import android.view.View;
import android.widget.Button;
public class DialogWindow extends Activity{
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.dialog_window);
Button btn = (Button) findViewById(R.id.btn_dialog);
btn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
class MyDialog extends DialogFragment {
FragmentManager fm = getFragmentManager();
public MyDialog() {
}
#Override
public Dialog onCreateDialog(Bundle savedInstanceState) {
//using the builder class
AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());
builder.setMessage("Simple Dialog")
.setPositiveButton("nothing", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
//Toast.makeText(getBaseContext(), "ok then", Toast.LENGTH_SHORT).show();
}
})
.setNegativeButton("cancel", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
//Toast.makeText(getBaseContext(), "cancel", Toast.LENGTH_SHORT).show();
}
});
return builder.create();
}
}
MyDialog md = new MyDialog();
md.show(md.fm, "dialog");
}
});
}
}
The Debugger shows the error at:
md.show(md.fm, "dialog");
On further inspection, the fm variable is null according to the variables tab in the debugger, why is this so and is there a more efficient solution to this? I am seriously new to android, sorry if this is an easy question.

You should use an AlertDialog in this case, not a DialogFragment. Here is how I would do it:
public class DialogWindow extends Activity{
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.dialog_window);
Button btn = (Button) findViewById(R.id.btn_dialog);
btn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
createDialog.show();
}
});
}
public Dialog createDialog() {
//using the builder class
AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());
builder.setMessage("Simple Dialog")
.setPositiveButton("nothing", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
//getBaseContext() is not advised (I can't remember why right now but I know I read it. You may want to read more that method but for now getActivity will work for your Toast.
//Toast.makeText(getActivity(), "ok then", Toast.LENGTH_SHORT).show();
}
})
.setNegativeButton("cancel", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
//Toast.makeText(getActivity(), "cancel", Toast.LENGTH_SHORT).show();
}
});
return builder.create();
}
}
DialogFragments should be used in conjunction with other Fragments, in the case of a single activity it would be best to use an AlertDialog.

Related

How to make a DialogFragment change text in activity main?

I'm a beginner in Android Studio and Java, and I'm building an app, which contains a dialog, built using DialogFragment. Here's the code for dialog.java:
package com.dkapps.shownamenow;
import android.app.AlertDialog;
import android.app.Dialog;
import android.content.DialogInterface;
import android.os.Bundle;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.appcompat.app.AppCompatDialogFragment;
public class datatype1 extends AppCompatDialogFragment {
String type = "";
#NonNull
#Override
public Dialog onCreateDialog(#Nullable Bundle savedInstanceState) {
AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());
builder.setNeutralButton("Regular Fraction", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
type = "frac";
}
});
builder.setNeutralButton("Whole Number", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
type = "whole";
}
});
builder.setNeutralButton("Mixed Fraction", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
type = "mixed";
}
});
return builder.create();
}
}
Now, I have a textview in my activity_main with the id 'type'. I want this dialog to set the text of that textview to the value of the string type. How do I do that?
I'd be grateful if you'd provide me some code.
You could create a method inside your activity to change the TextView's content, and call it in each of the buttons onClick methods.
Here is a code sample:
// inside you activity
public setText(String text){
findViewById(R.id.type).setText(text);
}
// onClick methods
#Override
public void onClick(DialogInterface dialog, int which) {
((MainActivity)getActivity()).setText("whole")
// change "whole" with the value of the string suitable for each button
}
You can get rid of the variable type, if you do not need it elsewhere
You could get the textView of your activity with findViewById()
private TextView typeFromActivity;
public Dialog onCreateDialog(#Nullable Bundle savedInstanceState) {
...
typeFromActivity = (TextView) findViewById(R.id.type);
type = typeFromActivity.getText().toString();
...
return builder.create();
}

How to open a new activity from a dialog fragment

My program opens a DialogFragment class while running in MainActivity.java
I want to be able to click on the "neutral button" of that dialog and open a new activity, SensorDataDisplay.java
I am having trouble finding the right way to reference the Context in my button's onClick.
package com.august.customtisensortagclient;
import android.app.AlertDialog;
import android.app.Dialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.support.v4.app.DialogFragment;
import java.util.ArrayList;
public class GetInfoDialog extends DialogFragment {
#Override
public Dialog onCreateDialog(Bundle savedInstanceState) {
final String thisWhichGetInfoDialog = ((MainActivity)getActivity()).getWhichGetInfoDialog();
final ArrayList<String> thisScannedDevicesArrayList =
((MainActivity)getActivity()).getScannedDevicesArrayList();
final int thisIsInLeftConnectedDeviceDisplay = ((MainActivity)getActivity()).getIsInLeftConnectedDeviceDisplay();
final int thisIsInRightConnectedDeviceDisplay = ((MainActivity)getActivity()).getIsInRightConnectedDeviceDisplay();
int thisIsInThisConnectedDeviceDisplay = 0;
if (thisWhichGetInfoDialog == "Left") {
thisIsInThisConnectedDeviceDisplay = thisIsInLeftConnectedDeviceDisplay;
} else if (thisWhichGetInfoDialog == "Right")
thisIsInThisConnectedDeviceDisplay = thisIsInRightConnectedDeviceDisplay;
AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());
builder.setTitle(thisWhichGetInfoDialog + " Sensor Info");
builder.setMessage("MAC Address: " + thisScannedDevicesArrayList.get(thisIsInThisConnectedDeviceDisplay));
builder.setNeutralButton("View Data", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
Intent myIntent = new Intent(?????, SensorDataDisplay.class);
myIntent.putExtra("key", "TEST VALUE"); //Optional parameters
?????.startActivity(myIntent);
}
});
builder.setNegativeButton("Done", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
// User cancelled the dialog
}
});
return builder.create();
}
}
DialogFragment has getActivity() and getContext() methods (which it inherits from Fragment), both will work in your case. If you're having trouble accessing these methods from the anonymous class (which shouldn't be the case), you can use the GetInfoDialog.this.getActivity() syntax.
getActivity() returns the Activity the fragment is attached to
builder.setNeutralButton("View Data", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
Intent myIntent = new Intent(getActivity(), SensorDataDisplay.class);
myIntent.putExtra("key", "TEST VALUE"); //Optional parameters
getActivity().startActivity(myIntent);
}
});

Confirm dialog before exit android studio

Hi guys I have an exit button on my main activity XML however I need it so when the user clicks it, it opens a dialogue to confirm the exit, if yes then exit. if no take them back.
here's my code so far, don't have any of that part however as I don't know where to start.
package com.tradingsoftwarelimited.labelprinter10;
import android.app.Activity;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.support.v7.app.ActionBarActivity;
import android.os.Bundle;
import android.view.Menu;
import android.view.View;
import android.widget.Button;
import android.widget.Toast;
public class MainActivity extends ActionBarActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
//Sets Edit and Data Button to hidden
Button hiddenButton = (Button) findViewById(R.id.editButton);
hiddenButton.setVisibility(View.INVISIBLE);
Button hiddenButton1 = (Button) findViewById(R.id.dataButton);
hiddenButton1.setVisibility(View.INVISIBLE);
//Acknolages settings button
Button showButton = (Button) findViewById(R.id.settingsButton);
//if clicked
showButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
//If clicked show Edit and data Button
Button showButton = (Button) (findViewById(R.id.editButton));
showButton.setVisibility(View.VISIBLE);
Button showButton1 = (Button) (findViewById(R.id.dataButton));
showButton1.setVisibility(View.VISIBLE);
}
});
}
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getSupportActionBar().hide();
return true;
}
};
;
private void confirmDialog(Context context){
final AlertDialog alert = new AlertDialog.Builder(
new ContextThemeWrapper(context,android.R.style.Theme_Dialog))
.create();
alert.setTitle("Alert");
alert.setMessage("Do you want to exit ?");
alert.setIcon(R.drawable.warning_icon);
alert.setCancelable(false);
alert.setCanceledOnTouchOutside(false);
alert.setButton(DialogInterface.BUTTON_POSITIVE, "Yes",
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
alert.dismiss();
finish();
}
});
alert.setButton(DialogInterface.BUTTON_NEGATIVE, "No",
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
alert.dismiss();
}
});
alert.show();
}
Call this method in
#Override
public void onBackPressed() {
super.onBackPressed();
confirmDialog(getApplicationContext());
}
of your Activity
Try like this:
Button exitButton = (Button) findViewById(R.id.exit_button);
exitButton..setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
AlertDialog.Builder builde = new AlertDialog.Builder(this);
builde.setMessage(
"Want Exit?")
.setPositiveButton("Yes ", dialogClickListeners)
.setNegativeButton("Cancel", dialogClickListeners).show();
}
});
DialogInterface.OnClickListener dialogClickListeners = new DialogInterface.OnClickListener()
{
public void onClick(DialogInterface dialog, int which)
{
switch (which)
{
case DialogInterface.BUTTON_POSITIVE:
finish();
break;
case DialogInterface.BUTTON_NEGATIVE:
break;
}
}
};
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Invite = (ImageButton) findViewById(R.id.imageButton5);
final DialogInterface.OnClickListener dialogClickListeners = new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
switch (which) {
case DialogInterface.BUTTON_POSITIVE:
finish();
break;
case DialogInterface.BUTTON_NEGATIVE:
break;
}
}
};
Invite.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
AlertDialog.Builder builde = new AlertDialog.Builder(MainActivity.this);
builde.setMessage(
"Want Exit?")
.setPositiveButton("Yes ", dialogClickListeners)
.setNegativeButton("Cancel", dialogClickListeners).show();
}
});
}

buttons work one after the other instead of at the same time [closed]

Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
Questions concerning problems with code you've written must describe the specific problem — and include valid code to reproduce it — in the question itself. See SSCCE.org for guidance.
Closed 9 years ago.
Improve this question
I am new to programming in java, i'm creating a simple application with multiple buttons within one activity. The problem that I am having is that buttons only work in sequence, one button will carry out its job only after another has been pressed, any help would be appreciated.
Code below:
import android.app.Activity;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.pm.ActivityInfo;
import android.os.Bundle;
import android.view.Menu;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
public class MainActivity extends Activity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
this.setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
// Settings button start
Button settingsButton = (Button) findViewById(R.id.btnSettings);
settingsButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
startSettings();
}
});
}
public void startSettings() {
Intent launchSettings = new Intent(this, SettingsScreen.class);
startActivity(launchSettings);
// Settings button end
// Set A Button start
Button setAButton = (Button) findViewById(R.id.btnSetA);
setAButton.setOnClickListener(new OnClickListener(){
#Override
public void onClick(View view) {
setzoneA();
}
});}
public void setzoneA(){
AlertDialog.Builder dlgAlert = new AlertDialog.Builder(this);
dlgAlert.setMessage("Zone Set");
dlgAlert.setPositiveButton("OK", null);
dlgAlert.setCancelable(true);
dlgAlert.create().show();
dlgAlert.setPositiveButton("Ok",
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
//dismiss the dialog
}
});
// Set A Button end
// Set B Button start
Button setBButton = (Button) findViewById(R.id.btnSetB);
setBButton.setOnClickListener(new OnClickListener(){
#Override
public void onClick(View view) {
setzoneB();
}
});}
public void setzoneB(){
AlertDialog.Builder dlgAlert = new AlertDialog.Builder(this);
dlgAlert.setMessage("Zone Set");
dlgAlert.setPositiveButton("OK", null);
dlgAlert.setCancelable(true);
dlgAlert.create().show();
dlgAlert.setPositiveButton("Ok",
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
//dismiss the dialog
}
});
}
// Set B Button end
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
}
Because you set listeners for button have dependency, All the button initiation and listeners should be in onCreate().
public class MainActivity extends Activity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
this.setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
// Settings button start
Button settingsButton = (Button) findViewById(R.id.btnSettings);
settingsButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
startSettings();
}
});
Button setAButton = (Button) findViewById(R.id.btnSetA);
setAButton.setOnClickListener(new OnClickListener(){
#Override
public void onClick(View view) {
setzoneA();
}
});
// Set B Button start
Button setBButton = (Button) findViewById(R.id.btnSetB);
setBButton.setOnClickListener(new OnClickListener(){
#Override
public void onClick(View view) {
setzoneB();
}
});
}
public void startSettings() {
Intent launchSettings = new Intent(this, SettingsScreen.class);
startActivity(launchSettings);
}
public void setzoneA() {
AlertDialog.Builder dlgAlert = new AlertDialog.Builder(this);
dlgAlert.setMessage("Zone Set");
dlgAlert.setPositiveButton("OK", null);
dlgAlert.setCancelable(true);
dlgAlert.create().show();
dlgAlert.setPositiveButton("Ok",
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
//dismiss the dialog
}
});
}
public void setzoneB() {
AlertDialog.Builder dlgAlert = new AlertDialog.Builder(this);
dlgAlert.setMessage("Zone Set");
dlgAlert.setPositiveButton("OK", null);
dlgAlert.setCancelable(true);
dlgAlert.create().show();
dlgAlert.setPositiveButton("Ok",
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
//dismiss the dialog
}
});
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
You need to set all your onClick() listeners within the onCreate() superfunction. Your current solution only sets the listeners when the previous button is clicked.
import android.app.Activity;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.pm.ActivityInfo;
import android.os.Bundle;
import android.view.Menu;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
public class MainActivity extends Activity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
this.setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
// Settings button start
Button settingsButton = (Button) findViewById(R.id.btnSettings);
settingsButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
startSettings();
}
});
// Set A Button start
Button setAButton = (Button) findViewById(R.id.btnSetA);
setAButton.setOnClickListener(new OnClickListener(){
#Override
public void onClick(View view) {
setzoneA();
}
});
// Set B Button start
Button setBButton = (Button) findViewById(R.id.btnSetB);
setBButton.setOnClickListener(new OnClickListener(){
#Override
public void onClick(View view) {
setzoneB();
}
});
}
public void startSettings() {
Intent launchSettings = new Intent(this, SettingsScreen.class);
startActivity(launchSettings);
// Settings button end
}
public void setzoneA(){
AlertDialog.Builder dlgAlert = new AlertDialog.Builder(this);
dlgAlert.setMessage("Zone Set");
dlgAlert.setPositiveButton("OK", null);
dlgAlert.setCancelable(true);
dlgAlert.create().show();
dlgAlert.setPositiveButton("Ok",
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
//dismiss the dialog
}
});
// Set A Button end
}
public void setzoneB(){
AlertDialog.Builder dlgAlert = new AlertDialog.Builder(this);
dlgAlert.setMessage("Zone Set");
dlgAlert.setPositiveButton("OK", null);
dlgAlert.setCancelable(true);
dlgAlert.create().show();
dlgAlert.setPositiveButton("Ok",
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
//dismiss the dialog
}
});
}
// Set B Button end
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
return true;
}

How to take text input with DialogFragment in Android?

I am trying to get a value that user enters into a Dialog, using the recommended DialogFragment class for it, the Dialog constructs and runs fine, but I cannot return the value of the EditText parameter to the parent class, without get a NullPointerException.
My DialogHost class, this constructs, returns and links the parent to its buttons.
package jo.app.co;
import android.app.Activity;
import android.app.AlertDialog;
import android.app.Dialog;
import android.app.DialogFragment;
import android.content.DialogInterface;
import android.os.Bundle;
import android.view.LayoutInflater;
public class DialogHost extends DialogFragment {
public interface NoticeDialogListener {
public void onDialogPositiveClick(DialogFragment dialog);
public void onDialogNegativeClick(DialogFragment dialog);
}
NoticeDialogListener mListener;
#override
public void onAttach(Activity activity) {
super.onAttach(activity);
try {
mListener = (NoticeDialogListener) activity;
} catch (ClassCastException e) {
throw new ClassCastException(activity.toString());
}
}
#override
public Dialog onCreateDialog(Bundle savedInstanceState) {
AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());
LayoutInflater inflater = getActivity().getLayoutInflater();
builder.setView(inflater.inflate(R.layout.dialog_add, null))
.setPositiveButton("Save", new DialogInterface.OnClickListener() {
#override
public void onClick(DialogInterface dialog, int id) {
mListener.onDialogPositiveClick(DialogHost.this);
}
})
.setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
DialogHost.this.getDialog().cancel();
}
});
return builder.create();
}
}
This is my MainActivity class showing the dialog
package jo.app.co;
import android.app.DialogFragment;
import android.os.Bundle;
import android.support.v4.app.FragmentActivity;
import android.util.Log;
import android.widget.EditText;
public class MainActivity extends FragmentActivity implements DialogHost.NoticeDialogListener {
#override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
showNoticeDialog();
}
public void showNoticeDialog() {
DialogFragment dialog = new DialogHost();
dialog.show(getFragmentManager(), "DialogHost");
}
#override
public void onDialogPositiveClick(DialogFragment dialog) {
EditText myText = (EditText) findViewById(R.id.item_added);
try {
Log.d ("IN TRY", myText.getText().toString());
}
catch (Exception e) {
Log.e ("IN CATCH", e.toString());
}
}
#override
public void onDialogNegativeClick(DialogFragment dialog) {
Log.d ("INMAIN", "REACHED NEG");
}
}
Thisthe layout of my Dialog for reference.
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="wrap_content"
android:layout_height="wrap_content">
<EditText
android:id="#+id/item_added"
android:inputType="text"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginTop="16dp"
android:layout_marginLeft="4dp"
android:layout_marginRight="4dp"
android:layout_marginBottom="4dp"
android:hint="#string/hint_add_item" />
</LinearLayout>
There seems to be problem with the way you are referring to the edit text. You need to get it from the view you inflated Please try the below code which adds all functionality in your main activity itself. If you want you can adapt to your case with a separate class:
public void showNoticeDialog() {
public String inputvalue;
LayoutInflater inflater = LayoutInflater.from(this);
final View textenter = inflater.inflate(R.layout.dialog_add, null)
final EditText userinput = (EditText) textenter.findViewById(R.id.item_added);
final AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setView(textenter)
.setTitle("Your title");
builder.setPositiveButton("Save", new DialogInterface.OnClickListener() {
#override
public void onClick(DialogInterface dialog, int id) {
inputvalue = userinput.getText().toString();
// Do something with value in inputvalue
}
})
.setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
dialog.cancel();
}
});
AlertDialog dialog = builder.create();
builder.show();
}
For alert dialog , you need to inflate an xml, only if you are planning to have multiple views like more than 1 edittext in that dialog. If you plan to have only 1 edittext as in your example, you dont need an xml and you can directly define an edittext and set it as the view of the alert dialog.
final EditText userinput = new EditText(context);
builder.setView(userinput);

Categories