EditText getText() returns empty string - android

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.

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 make a Edit-text box in set error message using without toast ( Alter dialog box ) using Android?

Hey every one has i am create rename application in android ,I will set a Edit-text box in set error message using without toast using Alert Dialog box
Sample Code :
AlertDialog.Builder alert = new AlertDialog.Builder(getActivity());
alert.setTitle(R.string.rename_title);
folderManager = new FolderManager(getActivity());
folderManager.open();
Cursor c = folderManager.queryAll(itemPos);
if (c.moveToFirst()) {
do {
Newnamefolder = c.getString(1);
} while (c.moveToNext());
}
// Set an EditText view to get user input
final EditText input = new EditText(getActivity());
input.setText(Newnamefolder);
alert.setView(input);
alert.setPositiveButton(R.string.rename_position_button, new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int whichButton)
{
Newnamefolder = input.getText().toString();
String Mesage_one = getResources().getString(R.string.folder_already_exit);
String Mesage_two = getResources().getString(R.string.types_minimum_eight_charcter);
String Mesage_three = getResources().getString(R.string.folder_empty);
String Matchnamerename = folderManager.getmatchfoldername(Newnamefolder);
if(Newnamefolder.equals(Matchnamerename))
{
input.setError(Mesage_one);
}
else if(Newnamefolder.length()>12)
{
input.setError(Mesage_two);
}
else if(Newnamefolder.equals(""))
{
input.setError(Mesage_three);
}
else
{
int newfolder = folderManager.update(itemPos,Newnamefolder);
reload();
}
}
});
alert.show();
But the problem once in click the OK button Don't show error message to exit the Alert Dialog box...
give me any solution ... Friends ?
You can extend Dialog and create your own dialog
public class CustomDialog extends Dialog implements View.OnClickListener {
private boolean success = false;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.custom_dialog);
Button positive = (Button) findViewById(R.id.button_positive);
Button negative = (Button) findViewById(R.id.button_negative);
EditText field = (EditText) findViewById(R.id.field);
positive.setOnClickListener(this);
negative.setOnClickListener(this);
}
#Override
public void onClick(View v) {
switch(v.getId()) {
case R.id.button_positive:
onPositiveButtonClicked();
break;
case R.id.button_negative:
//onNegativeButtonClicked();
break;
}
}
private void onPositiveButtonClicked() {
if(verifyForm()) {
success = true;
dismiss();
}
}
public boolean isSuccess() {
return success;
}
private boolean verifyForm() {
boolean valid = true;
/* verify each field and setError() if not valid */
if(!TextUtils.isEmpty(field.getText())) { //or any other condition
valid = false;
field.setError("error message");
}
return valid;
}
}
You can show your CustomDialog like this
final CustomDialog customDialog = new CustomDialog();
dialog.setOnDismissListener(new DialogInterface.OnDismissListener() {
#Override
public void onDismiss(DialogInterface dialog) {
if(customDialog.isSuccess()) {
//update your folder manager
}
}
}
customDialog.show();

EditText in dialog returning null string

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

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.

User input alertdialog not opening after button click in BluetoothChat

Hi I'm an android newbie and I've been stuck for a week on this. Any help would be appreciated! I've done a lot of research and can't figure out what is wrong. I've successfully run the bluetoothchat sample code on two phones and successfully communicated via bluetooth. I've also successfully written and run a standalone app that, after a button click on the main activity, opens a custom alertdialog which accepts user input, and passes the input back to the main activity. But when I write the alertdialog code into the BluetoothChat code, nothing happens when I click the button. I've tried to step through the debugger with the phone but with no luck. It doesn't seem to step to the code containing the button click. There are no errors showing. Why won't the alertdialog pop up on button click? Here's the BluetoothChat.java code I've modified :
public class BluetoothChat extends Activity implements OnClickListener{
final Context context = this;
private Button rButton;
View rScreen;
private EditText mAlertDialog;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
if(D) Log.e(TAG, "+++ ON CREATE +++");
// Set up the window layout
setContentView(R.layout.main);
// Get local Bluetooth adapter
mBluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
// If the adapter is null, then Bluetooth is not supported
if (mBluetoothAdapter == null) {
Toast.makeText(this, "Bluetooth is not available", Toast.LENGTH_LONG).show();
finish();
return;
}
//components from main.xml
//When button is clicked, the alert dialog is pulled up
rButton = (Button)findViewById(R.id.buttonr);
mAlertDialog = (EditText)findViewById(R.id.edittextresultm);
//add button listener
rButton.setOnClickListener(new OnClickListener() {
//#Override
public void onClick_register(View view) {
String title = "title";
String buttonOk = "OK";
String buttonCancel = "Cancel";
String madd, name;
//get review.xml view
LayoutInflater li = LayoutInflater.from(context);
View rView = li.inflate(R.layout.review, null);
//AlertDialog dialog;
AlertDialog.Builder adRegister = new AlertDialog.Builder(context);
//set review.xml to adRegister builder
adRegister.setView(rView);
//set title
adRegister.setTitle(title);
//Set EditText views to get user input
final EditText mField = (EditText)rView.findViewById(R.id.editTextm);
final EditText nField = (EditText)rView.findViewById(R.id.editTextn);
//set dialog message
adRegister.setMessage("Message")
.setCancelable(false)
.setPositiveButton(buttonOk, new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
String madd = mField.getText().toString();
String name = nField.getText().toString();
//get user input and set it to result on main activity
mAlertDialog.setText(mField.getText());
}
})
.setNegativeButton(buttonCancel, new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
// TODO Auto-generated method stub
//if this button is clicked, close current activity
dialog.cancel();
}
});
//Create alert dialog
AlertDialog alertDialog = adRegister.create();
//dialog= adRegister.create();
//show it
adRegister.show();
//dialog.show();
}
public void onClick(View arg0) {
// TODO Auto-generated method stub
}
});
}
}
Write your inputDialog code in OnClick Method.
Enjoy!!

Categories

Resources