EditText in dialog returning null string - android

I have this button to show a dialog which in turn has an EditText for the users to write something and then tap the done button to save it otherwise another button to close the dialog. The problem here is that I am not able to fetch that String that the user wrote. It returns me a null sting instead and causes the app to crash. Here's the code :
I call the dialog up on clicking on a button:
//Write Review Dialog Box
writeReviewBtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Log.i("HAPPENED", "This Onclick is working");
try{
// Create custom dialog object
final Dialog dialog = new Dialog(GetReviewActivity.this);
// Include dialog's xml file
dialog.setContentView(R.layout.write_review_activity);
// Set dialog title
dialog.setTitle("Your review is valuable");
final EditText etWR = (EditText)findViewById(R.id.etWR);
Button writeButton = (Button) dialog.findViewById(R.id.buttonWR);
Button declineButton = (Button) dialog.findViewById(R.id.buttonNoThanks);
dialog.show();
//Done Button
writeButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Log.i("HAPPENED: ","writeButton Block Is WORKING!");
Activity activity = GetReviewActivity.this;
activity.runOnUiThread(new Runnable() {
#Override
public void run() {
String Review = etWR.getText().toString();
StoreAReview(Review);
}
});
}
});
// if decline button is clicked, close the custom dialog
declineButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// Close dialog
dialog.dismiss();
}
});
}catch (Exception e){
e.printStackTrace();
}
}
});

final EditText etWR = (EditText)findViewById(R.id.etWR); is resolving to Activity#findViewById. But your dialog's layout is not attached to your activity window, it's attached to the dialog. so you have to inflate EditText from your dialog's view:
Try
final EditText etWR = (EditText)dialog.findViewById(R.id.etWR);
instead of
final EditText etWR = (EditText)findViewById(R.id.etWR);

Been through this issue before. I tried initiating EditText with Dialog reference but this didn't work
final EditText etWR = (EditText)dialog.findViewById(R.id.etWR);
Solution:
This is how I solved it:
#Override
public Dialog onCreateDialog(Bundle savedInstanceState) {
View dialogWR = getActivity().getLayoutInflater().inflate(R.layout.write_review_activity, null);
etWR = (EditText) dialogWR.findViewById(R.id.etWR);
}

You should initialize EditText
EditText etWR = (EditText)dailog.findViewById(R.id.etWR);
becoz your EditText is coming from dailog. So

U just miss the dialog.findViewById(R.id.etWR)
change this line
final EditText etWR = (EditText)findViewById(R.id.etWR);
to this one
final EditText etWR = (EditText)dialog.findViewById(R.id.etWR);
then, add click event code

Related

Android- Help fixing Custom Alert Dialog with EditText

Context: There is a custom Listview and each list item has a button in it. When you click the button an alertDialog appears with an edit text and submit button. This only happens on the first click, on subsequent clicks a Toast will simply appear with the number of times it has been clicked thus far.
When you click the submit button a toast will appear displaying the text that was entered into the editText and the number of times they have clicked on it which will presumably always be 1 since this can only happen on the first click.
Problem: The timesClicked counter is not working properly if the user so much as clicks on the editText before clicking submit. It is restting to 0 I guess. However if the user does not click on the editText then the program works normally. 0_o I'm at a loss.
Attempts at solving: I simplified the code down quite a bit to try and pinpoint the problem and this is where I am stuck. Originally I was inflating a view that only had an edit text and then I was just using builder.setPositiveButtton. I thought implementing the buttons directly in the view would fix it but that doesn't seem to be the case. I have been stuck on this for awhile. Any help would be great
Here is a video of the bug happening
private class OnSubtractClickListener implements View.OnClickListener {
final int id; //id of list item that was clicked
int timesClicked;
Toast toast;
public OnSubtractClickListener(int id, View view) {
super();
this.id = id;
timesClicked = 0;
}
#Override
public void onClick(View view) {
if (timesClicked != 0) {
toast.setText(Integer.toString(timesClicked));
toast.show();
}
else{
toast = Toast.makeText(view.getContext(), "", Toast.LENGTH_SHORT);
final View dialogView = LayoutInflater.from(view.getContext()).inflate(R.layout.dialog_add_notes, null);
AlertDialog.Builder builder = new AlertDialog.Builder(view.getContext());
builder.setView(dialogView);
builder.setTitle("Subtract cigar?");
builder.setIcon(R.mipmap.monkey_launcher);
final AlertDialog dialog = builder.create();
Button yesButton = (Button)dialogView.findViewById(R.id.dialog_notes_yes_button);
yesButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
EditText editText = (EditText)dialogView.findViewById(R.id.dialog_editText);
String userInput = editText.getText().toString();
String timesClickedString = Integer.toString(++timesClicked);
toast.setText(timesClickedString + ": " + userInput);
toast.show();
dialog.dismiss();
}
});
dialog.show(); //new
}
}
}
You can make class that extend Dialog.
example:
public class CustomDialog extends Dialog {
private EditText editText;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
WindowManager.LayoutParams lpWindow = new WindowManager.LayoutParams();
lpWindow.flags = WindowManager.LayoutParams.FLAG_DIM_BEHIND;
lpWindow.dimAmount = 0.8f;
getWindow().setAttributes(lpWindow);
setContentView(R.layout.activity_custom_dialog);
editText = (EditText) findViewById(R.id.editText);
}
}
You can use this dialog..
mCustomDialog = new CustomDialog();
mCustomDialog.show();
You can make the layout as you wish.
======================================================================
You can use AlertDialog.Builder.setPositiveButton.
site : setPositiveButton
example...
toast = Toast.makeText(view.getContext(), "", Toast.LENGTH_SHORT);
final View dialogView = LayoutInflater.from(view.getContext()).inflate(R.layout.dialog_add_notes, null);
AlertDialog.Builder builder = new AlertDialog.Builder(view.getContext());
builder.setView(dialogView);
builder.setTitle("Subtract cigar?");
builder.setIcon(R.mipmap.monkey_launcher);
builder.setPositiveButton("text", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialogInterface, int which) {
EditText editText = (EditText)dialogView.findViewById(R.id.dialog_editText);
String userInput = editText.getText().toString();
String timesClickedString = Integer.toString(++timesClicked);
toast.setText(timesClickedString + ": " + userInput);
toast.show();
}
});
final AlertDialog dialog = builder.create();
dialog.show(); //new
I found the solution. Basically what was happening was that when the Keyboard appeared it would cause the listview to adjust the size recreating the whole listview with recycled/old versions of the list items from before the dialog appeared -effectively undoing any changes made to the ListView items by the dialog.
In your listview XML add this:
android:descendantFocusability="beforeDescendants"
In Mainfest.xml:
<activity android:name= ".yourActivity"
android:windowSoftInputMode="adjustPan"/>

how to create a custom dialog and receive results in android?

i have an activity that when user click on button , a dialog open. in this dialog there is a spinner that have 3 choices: Blue,Red,Green. and there is a submit button. i want that when user select a color and click on submit, in caller activity, its String color set to selected color in dialog. i try this: but not worked. please help me....
String color;
String dialogColor;
showDialog.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
final Dialog dialog = new Dialog(context);
dialog.setContentView(R.layout.custom_dialog);
dialog.setTitle("my dialog");
Spinner spinner = (Spinner) dialog.findViewById(R.id.spinner);
final TextView status = (TextView) dialog.findViewById(R.id.status);
Button submit = (Button) dialog.findViewById(R.id.submit);
spinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
#Override
public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
dialogColor = parent.getItemAtPosition(position).toString();
status.setText("Color is: "+dialogColor);
color = dialogColor;
}
#Override
public void onNothingSelected(AdapterView<?> parent) {
}
});
submit.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent();
intent.putExtra("Color",dialogColor);
dialog.dismiss();
}
});
dialog.show();
}
});
i use both of direct and with intent ways to assign my color String to selected value. but not worked. where i have mistake?
I think the best way to create custom dialogs now is the Dialog Fragment, because the simple dialog it's limited. For example it's the way to create a dialogs with material design. And you have a differents ways to take info from dialog fragment, the first and the second for example.
This is basic code to create a dialog fragment:
//Method to call and start dialog fragment class
public void ShowPhotoFilesDialog(Activity context,File photo){
//Declaration of classes
Custom_DialogFragment custom_dialogFragment = new Custom_DialogFragment ();
FragmentManager fragmentManager = context.getFragmentManager();
// The device is using a large layout, so show the fragment as a dialog
custom_dialogFragment.show(fragmentManager, "dialog");
}
And this is the basic dialog fragment class:
public class Custom_DialogFragment extends DialogFragment {
#Override
public Dialog onCreateDialog(Bundle savedInstanceState) {
try {
// The only reason you might override this method when using onCreateView() is
// to modify any dialog characteristics. For example, the dialog includes a
// title by default, but your custom layout might not need it. So here you can
// remove the dialog title, but you must call the superclass to get the Dialog.
Dialog dialog = super.onCreateDialog(savedInstanceState);
AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());
//To hide action bar from layout
dialog.requestWindowFeature(Window.FEATURE_NO_TITLE);
//Declaration of controls
View v = getActivity().getLayoutInflater().inflate(R.layout.my_custom_layout);
builder.setView(v);
//My code
return builder.create();
}
catch (Exception ex){
Log.e("-- Custom_DialogFragment.onCreateDialog --","",ex);
return null;
}
}
}
Tell me if I helped you, good programming!

Dialog still show after click positive button

I have button on (CustomDilaog activity) when clicked show custom dialog with password edittext and OK button and cancel button , if you put correct password it open another activity (Text activity), till now every things work fine ,
i have question with two parts.
Part one : when im in (Text activity) and press back button to return to (CustomDilaog activity) , still the dialog show over it , how to let it dismiss
Part two : after dialog fired , if i dont write password and just click OK button with edittext empty it has no response , how to let this click just dismiss dialog without no action ( which is open (Text activity) if wrote correct password .
(CustomDilaog activity):
public class CustomDilaog extends Activity {
final Context context = this;
private Button button;
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
TextView tv=(TextView)findViewById(R.id.introclusion_tv1);
tv.setTypeface(FontFactory.getBFantezy(getBaseContext()));
TextView tv1=(TextView)findViewById(R.id.introclusion_tv2);
tv1.setTypeface(FontFactory.getBFantezy(getBaseContext()));
tv1.setText(Html.fromHtml(getString(R.string.introclusion)));
button = (Button) findViewById(R.id.button1);
// add button listener
button.setOnClickListener(new OnClickListener() {
public void onClick(View arg0) {
// custom dialog
final Dialog dialog = new Dialog(context,R.style.cust_dialog);
dialog.requestWindowFeature(Window.FEATURE_NO_TITLE);
dialog.setContentView(R.layout.custom);
// set the custom dialog components - text, image and button
TextView text = (TextView) dialog.findViewById(R.id.text);
Typeface font = Typeface.createFromAsset(getAssets(), "BFantezy.ttf");
text.setTypeface(font);
text.setText("write password :");
Button dialogButton = (Button) dialog.findViewById(R.id.dialogButtonOK);
Typeface font1 = Typeface.createFromAsset(getAssets(), "BFantezy.ttf");
dialogButton.setTypeface(font1);
// if button is clicked, close the custom dialog
dialogButton.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
EditText password = (EditText) dialog.findViewById(R.id.password);
////
if( password.getText().toString().length() > 0 ) {
if( password.getText().toString().equals("test")) {
Intent intent = new Intent(CustomDilaog.this,Text.class);
startActivity(intent);
}
else{
// get your custom_toast.xml layout
LayoutInflater inflater = getLayoutInflater();
View layout = inflater.inflate(R.layout.custom_toast,
(ViewGroup) findViewById(R.id.custom_toast));
// set a dummy image
ImageView image = (ImageView) layout.findViewById(R.id.image_toast);
image.setImageResource(R.drawable.ic_launcher);
// set a message
TextView text = (TextView) layout.findViewById(R.id.text_toast);
text.setText("Wrong password");
// Toast...
Toast toast = new Toast(getApplicationContext());
toast.setGravity(Gravity.CENTER_VERTICAL, 0, 0);
toast.setDuration(Toast.LENGTH_LONG);
toast.setView(layout);
toast.show();
}
}
}
});
Button dialogButtonCancell = (Button) dialog.findViewById(R.id.cancel);
Typeface font11 = Typeface.createFromAsset(getAssets(), "BFantezy.ttf");
dialogButtonCancell.setTypeface(font11);
dialogButtonCancell.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
dialog.dismiss();
}
});
dialog.show();
}
});
}
}
call dialog.dismiss() at the beginning of dialogButton click listener:
dialogButton.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
dialog.dismiss();
EditText password = (EditText) dialog.findViewById(R.id.password);
if( password.getText().toString().length() > 0 ) {
...
}
});
Part one : when im in (Text activity) and press back button to return to (CustomDilaog activity) , still the dialog show over it , how to let it dismiss
Simply call finish() in your CustomDialogActivity when you start the new Activity. It looks like your Intent is calling this same Activity though so I'm a little confused on that.
if( password.getText().toString().length() > 0 ) {
if( password.getText().toString().equals("test")) {
Intent intent = new Intent(CustomDilaog.this,Text.class);
startActivity(intent);
Part two : after dialog fired , if i dont write password and just click OK button with edittext empty it has no response , how to let this click just dismiss dialog without no action ( which is open (Text activity) if wrote correct password .
Add an else statement to your first if and inside it put dialog.dismiss()

Changing button text from AlertDialog

i am new to developing apps for android and i want to create a simple Conterter app, just for the start. In my view i have a edittext and a Button. If i click the button, it will open a AlertDialog with list of strings. I cant figure out how to manage this: When i click on one item in the AlertView i want to set the text of the button to the selected string and dismiss the AlertDialog. Can somebody please help me ?
public class VypocetDlzkyActivity extends Activity {
EditText HodnotaDlzka;
Button prevodDlzkaZtlacidlo;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_vypocet_dlzky);
}
public void zmenPrevodZ(View view){
final String[] jednotkyDlzky = {"milimeter", "centimeter", "decimeter", "meter", "kilometer", "svetelny rok"};
AlertDialog.Builder builder = new AlertDialog.Builder(VypocetDlzkyActivity.this);
builder.setTitle("Vyberte jednotku");
builder.setItems(jednotkyDlzky,null);
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int item) {
String value = jednotkyDlzky[item].toString();
prevodDlzkaZtlacidlo.setText(value);
dialog.cancel();
}
};
final AlertDialog alert = builder.create();
alert.show();
}
You need to set the values of these 2 member variables in your onCreate() method, like this:
HodnotaDlzka = (EditText)findViewById(R.id.xxxx);
prevodDlzkaZtlacidlo = (Button)findViewById(R.id.yyyy);
xxxx is the ID you gave the EditText in activity_vypocet_dlzky.xml and yyyy is the ID you gave to the Button.
Also, after a button is clicked in the AlertDialog, the dialog is automatically dismissed, so you don't need to call dialog.cancel().
Problem is you didnt add any onClick listnerz.On clicking on button you need to call the required method.
public class MainActivity extends Activity implements OnClickListener {
EditText HodnotaDlzka;
Button prevodDlzkaZtlacidlo;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
HodnotaDlzka = (EditText) findViewById(R.id.e1);
prevodDlzkaZtlacidlo = (Button) findViewById(R.id.b1);
prevodDlzkaZtlacidlo.setOnClickListener(this);
}
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
final String[] jednotkyDlzky = {"milimeter", "centimeter", "decimeter", "meter", "kilometer", "svetelny rok"};
AlertDialog.Builder builder = new AlertDialog.Builder(MainActivity.this);
builder.setTitle("Vyberte jednotku");
builder.setItems(jednotkyDlzky,new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int item) {
String value = jednotkyDlzky[item].toString();
prevodDlzkaZtlacidlo.setText(value);
}
});
enter code here
final AlertDialog alert = builder.create();
alert.show();
}
}

Displaying custom dialog

Alright, so I would like to have a custom dialog, but I cannot figure out for the life of me how to make it appear when the function is called.
public void addHomework() {
final Dialog alert = new Dialog(this);
alert.setTitle("Add Homework");
alert.setContentView(R.layout.homework_item_entry);
Button add_button = (Button) findViewById(R.id.add_homework_button);
Button cancel_button = (Button) findViewById(R.id.cancel_homework_button);
add_button.setOnClickListener( new OnClickListener() {
public void onClick(View v) {
Toast.makeText(ClassHomeworkList.this, "Adding homework", Toast.LENGTH_SHORT).show();
}
});
cancel_button.setOnClickListener( new OnClickListener() {
public void onClick(View v) {
alert.dismiss();
}
});
alert.show();
}
What could I do?
I know this is an old thread, but even after reading the Android docs it also was not obvious to me how to display a custom dialog using the standard Dialog class. Basically you can call:
this.showDialog(MANAGE_PASSWORD); // MANAGE_PASSWORD static final int
from your activity. Then instantiate the custom dialog in the onCreateDialog method:
protected Dialog onCreateDialog(int id) {
Dialog dialog;
switch(id) {
case MANAGE_PASSWORD:
dialog= getInstancePasswordDialog();
break;
case DIALOG_ABOUT:
// do the work to define the About Dialog
dialog= getInstanceAlertDialog(); // called "the first time"
break;
default:
dialog = null;
}
return dialog;
}
The code to instantiate the dialog is in getInstancePasswordDialog(). Here is the code sample.
I think you have the problem that your two buttons cannot be found by their ID's like this (as you are trying to find them in your main activity, but they are in the layout for the dialog)
Button add_button = (Button) findViewById(R.id.add_homework_button);
Button cancel_button = (Button) findViewById(R.id.cancel_homework_button);
But instead need to do:
Button add_button = (Button) alert.findViewById(R.id.add_homework_button);
Button cancel_button = (Button) alert.findViewById(R.id.cancel_homework_button);
Have you read the following document: http://developer.android.com/guide/topics/ui/dialogs.html#ShowingADialog ?
You should override your Activity's onCreateDialog(int) method as described there and then use showDialog(int)
LayoutInflater factory = LayoutInflater.from(this);
View view = factory.inflate(R.layout.dialog, null);
//the id is your root layout
LinearLayout layout = (LinearLayout) view.findViewById(R.id.layout);
alert.setContentView(layout);

Categories

Resources