Dismiss() not working for Customize AlertDialog - android

I am developing a android App which is totally based on request and response from servlet.I have populate some data in customize Alert-dialog Where i using two thing one is cross button that will delete item from list in alert-dialog and update view of alert dialog , second thing is close button that will suppose to dismiss this alert-dialog. I am showing full coding of my alert-dialog. I calling alert dialog on button click by all these method.
intiliazeOrderListDialog();
showOrderListDialog();
My decleration is as follow
public AlertDialog detailsDialog, orderDialog;
AlertDialog.Builder builder;
Now i am going to post my intiliazeOrderListDialog() block.
public void intiliazeOrderListDialog() {
builder = new AlertDialog.Builder(MainScreen.this);
mContext = getApplicationContext();
inflater = (LayoutInflater) mContext.getSystemService(LAYOUT_INFLATER_SERVICE);
orderDialogLayout = inflater.inflate(R.layout.my_order_list,(ViewGroup)findViewById(R.id.order_list_root));
orderList = (ListView) orderDialogLayout.findViewById(R.id.order_list);
ibOrderDelete = (ImageButton)orderDialogLayout.findViewById(R.id.deleteOrder);
tvPrice = (TextView) orderDialogLayout.findViewById(R.id.order_list_total);
tvTaxes = (TextView) orderDialogLayout.findViewById(R.id.order_list_taxes);
tvTotal = (TextView) orderDialogLayout.findViewById(R.id.order_list_grand_total);
Button bclose = (Button) orderDialogLayout.findViewById(R.id.close);
Button bPlaceOrder = (Button) orderDialogLayout.findViewById(R.id.my_order_placeorder);
bclose.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
orderDialog.dismiss();
System.out.println(" click on closowse");
}
});
bPlaceOrder.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
System.out.println("Place order click");
palceMyOrdertoServer();
new SendOrderFromTable().execute();
System.out.println("place order to server is called");
String msg = "Your Order is Successfully placed to Kitcken";
Message msgObject = new Message();
msgObject.what = 1;
msgObject.obj = msg;
addMenuItemHandler.sendMessage(msgObject);
orderDialog.dismiss();
}
});
}
and at last i am going to post showOrderListDialog(); block
public void showOrderListDialog() {
builder.setView(orderDialogLayout);
orderDialog = builder.create();
orderDialog.show();
}
I know i have posted too many codes but its conveniences for those who want to help me . I have a very simple problem why my
orderDialog.dismiss();
is not working for me.? Thanks in advance to all .

Finally i solve my own issue . "Self help is best help ;;".
It was issue of calling method in setOnClickListener.
I just call it,
android:clickable="true"
android:onClick="clickHandler"
if (v.getId() == R.id.myOrder) {
System.out.println("Click my Order");
System.out.println("OrderListAdapter.totalCount ="
+ OrderListAdapter.totalCount);
// select COUNT(*) from CDs;
int jcount = 0;
jcount = countjournals();
System.out.println("jcount = " + jcount);
// Count implementation at my Order
if (jcount < 1) {
alertShow();
} else {
intiliazeOrderListDialog();
showOrderListDialog();
}
// startActivity(new Intent(RestaurantHome.this,
// MyOrderList.class));
}

Related

Android: getting wrong checked radio button text value

I am trying to view specific icons based on the selected radio button using an if statement.
I didn't want to use a listener since I'm clicking a submit button anyway.
I have 3 buttons: Party, Accident and Other.
When running my code my Log message shows that I always get "other" (else clause) as a checked value, even when it is not.
I have tried so many different ways from many different threads on Stack Overflow but I'm afraid I might be doing something else wrong.
Here is the code:
private void addMarkerToMap() {
AlertDialog.Builder builder = new AlertDialog.Builder(MapsActivity.this);
View view = getLayoutInflater().inflate(R.layout.dialoglayout, null);
streetname = (EditText) view.findViewById(R.id.streetname_input);
title = (EditText) view.findViewById(R.id.title_input);
description = (EditText) view.findViewById(R.id.description_input);
radioGroup = (RadioGroup) view.findViewById(R.id.radioGroup);
final int selectedID = radioGroup.getCheckedRadioButtonId();
radioButton = (RadioButton) view.findViewById(selectedID);
Button addButton = (Button) view.findViewById(R.id.add_button);
Button cancelButton = (Button) view.findViewById(R.id.cancel_button);
builder.setView(view);
final AlertDialog dialog = builder.create();
dialog.show();
addButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
addMarker(streetname, title, description);
}
});
cancelButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
dialog.dismiss();
}
});
}
private void addMarker(EditText streetname, EditText title, EditText description) {
String streetnameText = streetname.getText().toString();
String titleText = title.getText().toString();
String descriptionText = description.getText().toString();
String radioText = radioButton.getText().toString();
BitmapDescriptor icon; //= BitmapDescriptorFactory.fromResource(R.drawable.standard); //has to have a standard value
//Log.d("id", "id" + ID);
Log.d("radioText", "text: " + radioText);
if(streetnameText.isEmpty() || titleText.isEmpty() || descriptionText.isEmpty()) {
Toast.makeText(this, "One of the textboxes is empty. Please fill in all textboxes", Toast.LENGTH_LONG).show();
} else {
if(radioText.equals("Accident")){
icon = BitmapDescriptorFactory.fromResource(R.drawable.accident);
}
else if(radioText.equals("Party")){
icon = BitmapDescriptorFactory.fromResource(R.drawable.party);
}
else {
icon = BitmapDescriptorFactory.fromResource(R.drawable.standard);
}
MarkerOptions markerOptions = new MarkerOptions().position(latlngGlobal)
.title(titleText)
.snippet(descriptionText)
.icon(icon);
//TODO add new marker
mMarker = mGoogleMap.addMarker(markerOptions);
// TODO Get location for marker, add to database
}
}
I have also tried using this instead but it's the same result (gives ID of "other"):
if(ID == R.id.accident_radio){
icon = BitmapDescriptorFactory.fromResource(R.drawable.accident);
}
else if(ID == R.id.party_radio){
icon = BitmapDescriptorFactory.fromResource(R.drawable.party);
}
else {
Log.d("id", "id" + ID);
icon = BitmapDescriptorFactory.fromResource(R.drawable.standard);
}
You declared radioButton as the selected radio button in the group at that specific time only, you don't do any new declarations for it before calling addMarker(...) so it will always be the same.
Instead of:
String radioText = radioButton.getText().toString();
Try something like this (but make it nicer):
String radioText = ((RadioButton) view.findViewById(((RadioGroup) view.findViewById(R.id.radioGroup)).getCheckedRadioButtonId())).getText().toString();

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"/>

EditText getText() returns empty string

I have an activity with a button, when the user clicks on the button, an AlertDialog appear with 2 EditText where you put email and password to login.
When I try to get the text from the EditText i always get only empty strings.
The layout login_alert is the layout of the AlertDialog.
Here the code:
View view = getLayoutInflater().inflate(R.layout.login_alert, null, false);
String email = ((EditText) view.findViewById(R.id.emailEditText)).getText().toString();
String password = ((EditText) view.findViewById(R.id.passwordEditText)).getText().toString();
System.out.println("DEBUG: "+email+", "+password); // Empty strings
EDIT:
Activity code:
public class MainActivity extends FragmentActivity {
public static final String mAPP_ID = "...";
public static final String USER_DB_URL = "...";
AssetsExtracter mTask;
private MainFragment mainFragment;
private List<User> usersList = new ArrayList<User>();
private User currentUser = null;
private Button labLoginButton;
private EditText emailET;
private EditText passwordET;
private ProgressDialog dialog;
private View alertView; /* THIS IS THE SOLUTION */
boolean userIsLogged = false;
static {
IMetaioSDKAndroid.loadNativeLibs();
}
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
setContentView(R.layout.activity_main);
/*View view = getLayoutInflater().inflate(R.layout.login_alert, null, false); BEFORE*/
alertView = getLayoutInflater().inflate(R.layout.login_alert, null, false);
emailET = (EditText) view.findViewById(R.id.emailEditText);
passwordET = (EditText) view.findViewById(R.id.passwordEditText);
labLoginButton = (Button) findViewById(R.id.loginLabButton);
updateLoginButton();
dialog = new ProgressDialog(this);
dialog.setMessage("Signin in...");
if (savedInstanceState == null) {
// Add the fragment on initial activity setup
mainFragment = new MainFragment();
getSupportFragmentManager().beginTransaction()
.add(android.R.id.content, mainFragment).commit();
} else {
// Or set the fragment from restored state info
mainFragment = (MainFragment) getSupportFragmentManager()
.findFragmentById(android.R.id.content);
}
mTask = new AssetsExtracter();
mTask.execute(0);
}
/* THIS METHOD IS CALLED BY THE LOGIN BUTTON IN THE MAIN ACTIVITY LAYOUT */
public void onLabLoginButtonClick(View v) {
if (userIsLogged) {
currentUser = null;
userIsLogged = false;
updateLoginButton();
Toast.makeText(this, "Disconnected from Lab", Toast.LENGTH_SHORT)
.show();
} else {
/*View messageView = getLayoutInflater().inflate(
R.layout.login_alert, null, false); BEFORE */
AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setIcon(R.drawable.icon_launcher);
builder.setTitle(R.string.login_string);
builder.setView(alertView); /* USING THE GLOBAL VARIABLE */
builder.setPositiveButton("Sign me", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface d, int which) {
dialog.show();
// Download user and return a List of User
DownloadFilesAsyncTask task = new DownloadFilesAsyncTask(USER_DB_URL) {
#Override
protected void onPostExecute(final List<User> result) {
usersList = result;
loginCheckRoutine(); //HERE I MANAGE THE LOGIN AND GETTING EMPTY STRING
}
};
task.execute();
}
});
builder.setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
// TODO Auto-generated method stub
}
});
builder.create();
builder.show();
}
}
public void updateLoginButton() {
if (userIsLogged) {
labLoginButton.setText(R.string.logout_string);
} else {
labLoginButton.setText(R.string.login_string);
}
}
public void loginCheckRoutine() {
String email = emailET.getText().toString();
String password = passwordET.getText().toString();
System.out.println("DEBUG: " + email + ", " + password); // EMPTY
// controllo nella lista se c'รจ l'utente coi dati inseriti
for (int i = 0; i < usersList.size(); i++) {
if (usersList.get(i).getEmail().equals(email)
&& password.equals("admin")) {
currentUser = usersList.get(i);
userIsLogged = true;
updateLoginButton();
dialog.dismiss();
break;
}
}
if (!userIsLogged) {
userIsLogged = false;
updateLoginButton();
dialog.dismiss();
Toast.makeText(MainActivity.this, "Login Failed",
Toast.LENGTH_SHORT).show();
}
}
}
PROBLEM SOLVED, SOLUTION:
In the onCreate() I inflate the alert_dialog layout in a View variable. I made that View variable global (before onCreate()) and then in onLabLoginButtonClick() I don't inflate the view again, but I use that global instantiated in the onCreate(). hope its clear. thank you all!
You getText just after initialization. Untill you have text in xml you won't get the text. In onclick of alertdialog button get the text.
Declare
EdiText ed1,ed2; // before onCreate if in activity and onCraeteView in fragment
as a instance variable
View view = getLayoutInflater().inflate(R.layout.login_alert, null, false);
ed1= (EditText) view.findViewById(R.id.emailEditText))
ed2 = (EditText) view.findViewById(R.id.emailEditText);
then on Alert dialog Button click
String email = ed1.getText().toString();
String password= ed2.getText().toString()
you must get the text when you click on login button of alert dialog box
the above mentioned code you get text when you show alert dialog it always return always empty string you should follow the following procedure
first you make a custom alert box layout having two edit text and one button
user write text to edittext for login and give password and then click login button
when you call login button click listener you can get text of edittext easyly
You are trying to get the text immediately after you inflated the view. Try doing it when the user clicks the done button instead.
Before onCreate add:
EditText email;
EditText pass;
Add this in your onCreate
etEmail (EditText) view.findViewById(R.id.emailEditText);
etPass (EditText) view.findViewById(R.id.emailEditText);
Then add this to when your button is clicked
String email = etEmail.getText().toString();
String pass = etEmail.getText().toString();
Just ensure that the editText.getText.toString() method is inside the OnClick() method, eg:
TextView submit = enquiryFragment.findViewById(R.id.query_submit_button);
submit.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v){
query_type = query_type_editText.getText().toString();
query_text = query_editText.getText().toString();
if (query_text.length()!=0 && query_type.length()!=0) {
postQuery(query_type, query_text, store_id);
// Log.e("query_type ",query_type );
}else{
Toast.makeText(getContext(), "Enter something !", Toast.LENGTH_SHORT).show();
}
}
});
Alternatively add a TextChangedListener to you textview to change the change the string every time the textboxtext changes.
A textwatcher is also possible
you should get the text when you click on save or done button.
If you get this text on click of alert dialog button, you may end up taking it multiple times.

Why my dismiss() method not able close Customize Alert dialog

I am developing a android app where I have created Customize alert dialog. I declare Globally alert dialog and and AlertDialog.builder as follow. Now I am calling three method f1(), f2(),f3(), in button click.
btn_my_order.setOnTouchListener(new OnTouchListener() {
#Override
public boolean onTouch(View v, MotionEvent event) {
f1();
f2();
f3();
return false;
}
});
I Declared orderDialog and builde globally as follow :-
private AlertDialog orderDialog = null;
AlertDialog.Builder builder;
My f1() block is as follow :-
F1{
builder = new AlertDialog.Builder(MainScreen.this);
mContext = getApplicationContext();
/**
* by the help of inflater my ordre is showing in list view
*/
inflater = (LayoutInflater) mContext.getSystemService(LAYOUT_INFLATER_SERVICE);
orderDialogLayout = inflater.inflate(R.layout.my_order_list,(ViewGroup)findViewById(R.id.order_list_root));
orderList = (ListView) orderDialogLayout.findViewById(R.id.order_list);
ibOrderDelete = (ImageButton)orderDialogLayout.findViewById(R.id.deleteOrder);
tvPrice = (TextView) orderDialogLayout.findViewById(R.id.order_list_total);
tvTaxes = (TextView) orderDialogLayout.findViewById(R.id.order_list_taxes);
tvTotal = (TextView) orderDialogLayout.findViewById(R.id.order_list_grand_total);
Button bclose = (Button) orderDialogLayout.findViewById(R.id.close);
Button bPlaceOrder = (Button) orderDialogLayout.findViewById(R.id.my_order_placeorder);
bclose.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
orderDialog.dismiss();
System.out.println(" click on close button");
}
});
/**
* click of place order to kitchen
*/
bPlaceOrder.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
System.out.println("Place order click");
palceMyOrdertoServer();
new SendOrderFromTable().execute();
System.out.println("place order to server is called");
String msg = "Your Order is Successfully placed to Kitcken";
Message msgObject = new Message();
msgObject.what = 1;
msgObject.obj = msg;
addMenuItemHandler.sendMessage(msgObject);
orderDialog.dismiss();
}
});}
My f2() is for some Cursor work with data base
F2{
// many stuff to be here populate data from cursor and bind it with adapter
// no any issue in this mehod
}
Now finally I am calling f3()
F3{
builder.setView(orderDialogLayout);
orderDialog = builder.create();
orderDialog.show();
}
Now i am going to explain all my problem f1() method is for initialization f2() is for populate data and f3() to show customize alert dialog . Why my
orderDialog.dismiss();
is not working for me.Even though i am able to see my logcat with message
"Click on close button"
That means execution is going on dismiss() method then why customize alert dialog didn't close at click. Thanks in advance to all
You should add final in your orderDialog private variable.

Android Dialog return String?

Hi I am popping up dialog to take comments from user. And returning a value according to that. That "rcomment" is a global variable. And it returns null. This is not working. What am I doing wrong ?
public String getDoNotBoardDialog(final int groupposition)
{
final Dialog dia = new Dialog(this);
dia.requestWindowFeature(Window.FEATURE_NO_TITLE);
dia.setContentView(R.layout.donotboard);
final EditText donotedit = (EditText) dia.findViewById(R.id.donotboardcomment);
donotedit.setText("");
Button button1 = (Button) dia.findViewById(R.id.donotboardbutton);
button1.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
r = donotedit.getText().toString();
String boardingComment = getString(R.string.donotboard) + " " + r;
PostCommentForAC(groupposition, boardingComment);
Intent intent = new Intent(getBaseContext(), TestExList.class);
intent.putExtra("EmpID", empid);
startActivity(intent);
rcomment = "true";
dia.cancel();
}
});
Button button2 = (Button) dia.findViewById(R.id.boardbutton);
button2.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
rcomment = "false";
dia.cancel();
}
});
dia.show();
return rcomment;
}
The getDoNotBoardDialog will initial return rcomment as null. rcomment will only be changed to "true" or "false" when the onClickListeners are fired. They are fired not when getDoNotBoardDialog is run, but after that, whenever the onClickListeners are fired.
Whatever you want to happen when rcomment is changed to "true" or "false" should be placed in the onClick methods. So if you want to check what rcomment is after a user clicks, do it there.
Edit: dont use below code. It will kill your app (ANR).
You would have to wait before you can return something. A quick (but really dirty) solution would be to add some wait/notify mechanism like so: (written blind so might contain some errors).
public String getDoNotBoardDialog(final int groupposition) {
// some Object to wait on
final Object waitOnMe = new Object();
final Dialog dia = new Dialog(this);
dia.requestWindowFeature(Window.FEATURE_NO_TITLE);
dia.setContentView(R.layout.donotboard);
final EditText donotedit = (EditText) dia.findViewById(R.id.donotboardcomment);
donotedit.setText("");
Button button1 = (Button) dia.findViewById(R.id.donotboardbutton);
button1.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
r = donotedit.getText().toString();
String boardingComment = getString(R.string.donotboard) + " " + r;
PostCommentForAC(groupposition, boardingComment);
Intent intent = new Intent(getBaseContext(), TestExList.class);
intent.putExtra("EmpID", empid);
startActivity(intent);
rcomment = "true";
dia.cancel();
// stop waiting.
synchronized(waitOnMe) {
waitOnMe.notify();
}
}
});
Button button2 = (Button) dia.findViewById(R.id.boardbutton);
button2.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
rcomment = "false";
dia.cancel();
// stop waiting.
synchronized(waitOnMe) {
waitOnMe.notify();
}
}
});
dia.show();
// this wait's until someone calls notify
synchronized (waitOnMe) {
try {
waitOnMe.wait();
} catch (InterruptedException e) {}
}
return rcomment;
}
It's problematic though. You could miss the notify() and thus never stop waiting (e.g. when you close the dialog via the "back" button). A much cleaner and safer solution would be to use some Callback mechanism (you call some method in your program from each onClick) to get a value from the dialog.
In you application
the program flows to
return rcomment;
directly after going to
dia.show();
Remember it does not wait for the button to be clicked before it goes to the return statement!!! It goes to return statement directly after the dialog is shown (before the button is clicked)
Try using this string.equals(data) it should find out if the string is the same. Since rcomment is a string. Also like Soham said it will not update only until it is clicked.
I suggest that in the future you should change to Boolean rcomment. Since it only looks like you are doing either true or false status.

Categories

Resources