AlertDialog EditText input validation does not work - android

I created a Dialog with a TextEdit as a number input to convert it to a double value.
I want to prevent an exception by checking, if the TextEdit input is empty but it always jumps to the else statement and therefore creates an exception when the EditText is blank.
final Builder builder = new Builder(this);
final EditText input = new EditText(this);
input.setKeyListener(DigitsKeyListener.getInstance(false, true));
builder
.setTitle(R.string.dialog_title_addmark)
.setMessage(R.string.dialog_addmark)
.setView(input)
.setPositiveButton(android.R.string.ok, new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
if (input.toString().trim().length() == 0) {
Toast.makeText(Marks.this, R.string.input_empty, Toast.LENGTH_SHORT).show();
} else {
Double value = Double.valueOf(input.getText().toString());
db.insertMark(selection, value);
getData();
}
}
})
.setNegativeButton(android.R.string.cancel, new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
}
})
.show();
I also tried it checking
(input.toString() != null)
but that does not work either.
Thanks for your help

If you want the text from a EditText object, you should use the following line of code:
input.getText().tostring();
where input is a EditText-object.
Using the code
input.toString();
will give you a string representation of the object, and as long as the object is not null, the toString of that object will be not null, so using input.toString() != null will not give you any useful information.
That means that you should do the following validation:
if (input.getText().toString().trim().length() == 0) to figure out if the input object contains some text.

Try this way..
if (input.toString().trim().length()< 0) {
Toast.makeText(Marks.this, R.string.input_empty, Toast.LENGTH_SHORT).show();
} else {
Double value = Double.valueOf(input.getText().toString());
db.insertMark(selection, value);
getData();
}

input.toString() will return the reference value of the Edittext not the text inside the Edittext.
Use below condition
if(input.getText().toString() != null || !input.getText().toString().isEmpty())

Related

how to show values in the second edittext only if user puts all the correct values in the first edit text

what should add in the code so that values are shown in the other text box only when the user have entered only corrected values...because with this code it is showing both the corrected values in the text box and incorrect in the dialog box..
String s=editText1.getText().toString();
String z[]=s.split("\\s");
editText2.setText("");
String a = "";
String b = " Not valid";
boolean is_open_dialog=false;
for(int i=0;i<z.length;i++)
{
int j=Integer.parseInt(z[i]);
if(j>=65 && j<=97)
{
editText2.setText(editText2.getText() + "" + String.valueOf((char) j));
}
else {
is_open_dialog = true;
a += z[i]+"\t";
}
}
if(is_open_dialog){
AlertDialog.Builder alertDialogBuilder = new AlertDialog.Builder(this);
alertDialogBuilder.setTitle("Error");
alertDialogBuilder.setCancelable(false);
alertDialogBuilder.setMessage(a+b)
.setPositiveButton("Ok", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
dialog.cancel();
}
});
AlertDialog alertDialog = alertDialogBuilder.create();
alertDialog.show();
}
I do not know if I have clear your problem, but try this:
...
if(is_open_dialog){
editText2.setText("");
AlertDialog.Builder alertDialogBuilder = new AlertDialog.Builder(this);
alertDialogBuilder.setTitle("Error");
...
}

Accessing Variables in AlertDialog in Android

In one of my Activity there are some calculations and total price will be calculated.After pressing the submit button it should show an alert dialog with Are you sure you want to pay Rupees:XXX...? here XXX should be the final price which I'm storing in the variable.
in alertdialog.setTitle() I should able to access the variable.
Please help me to solve this.
public void onPay()
{
getItems();
int rate = 0;
if(spare1_item.equals("Tyres") || qty_1.equals("Quantity"))
{
}
else
{
//Toast.makeText(getApplicationContext(), "Now you can pay", 5000).show();
db = this.openOrCreateDatabase("mobile_cycle_clinic", MODE_PRIVATE, null);
c = db.rawQuery("select price from sparelist where name = '"+spare1_item+"'", null);
if(c.moveToNext())
{
do{
price = c.getInt(c.getColumnIndex("price"));
}
while(c.moveToNext());
}
fianl1_qty = Integer.parseInt(qty_1);
rate = rate + price * fianl1_qty;
db.execSQL("insert into spares_items(cycle_id,item_name,quantity,total_price)values('"+cycle_id+"','"+spare1_item+"',"+fianl1_qty+","+rate+")");
//Toast.makeText(getApplicationContext(), ""+rate, 5000).show();
}
Here rate is a static variable and in another method I should use that variable in alertDialog.setMeaasge().
public void storeData(View v)
{
cycle_id = id.getText().toString();
if(cycle_id.equals("") || cycle_id.equals("null"))
{
Toast.makeText(getApplicationContext(), "Please Scan Cycle",5000).show();
}
else
{
AlertDialog.Builder pauseBuild = new AlertDialog.Builder(this);
pauseBuild.setTitle("Pay Alert");
pauseBuild.setMessage("Do you really want to Pay..?"+rate);
pauseBuild.setPositiveButton("Yes", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
SimpleDateFormat sdf = new SimpleDateFormat("yyyy:MM:dd HH:mm:ss");
//time = sdf.format(new Date());
onPay();
finish();
return;
} });
pauseBuild.setNegativeButton("No",new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog,int id) {
// if this button is clicked, just close
// the dialog box and do nothing
dialog.cancel();
}
});
// show it
pauseBuild.show();
}
You can use a function to show or create the AlertDialog.
For example:
private void showConfirmAlertDialog(int price) {
AlertDialog.Builder builder = new AlertDialog.Builder();
builder.setTitle("Are you sure you want to pay rupees: " + price);
....
builder.show();
}
If you perfer getting an instance of AlertDialog, you can change the function to private AlertDialog createConfirmAlertDialg(int price), and use return builder.create(); at the end of function.

Android: how to send a httppost request after n dialog inputs

I have a method which retrieves an array of user requests. I iterate through this array, showing a Dialog with positive and negative buttons. When the last Dialog has been confirmed whether with yes or no, a httppost is sended to a server to process the data. I builded up the function like this:
private void processRequests(String resJSON){
try {
JSONArray array = new JSONArray(resJSON);
AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setTitle("Neue Herausvorderung");
builder.setCancelable(false);
final int ARRAY_LENGTH = array.length();
for(int i=0; i<array.length(); i++){
JSONObject obj = array.getJSONObject(i);
final String NAME= obj.getString("userName");
final long ID= obj.getLong("userID");
final int INDEX= i;
builder.setMessage(name + " fordert dich zu einem Duell heraus! Willst du annehmen?");
builder.setPositiveButton("JA", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
acceptedUsers.add(new User(ID, NAME));
if(INDEX== ARRAY_LENGTH-1){
sendRequestStuff();
}
}
});
builder.setNegativeButton("NEIN", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
declinedUsers.add(new User(ID, NAME));
if(INDEX== ARRAY_LENGTH-1){
sendRequestStuff();
}
}
});
AlertDialog alert = builder.create();
alert.show();
}
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
The problem is, as soon as the first Dialog is confirmed, sendRequestStuff() gets called. I suspect the Listeners to cause the bug, but I am not sure. How can this be solved?
You send the request after getting a response from the last dialog: if(INDEX== ARRAY_LENGTH-1).
Because you are running a loop over the whole array (from 0 to ARRAY_LENGTH-1) and show a dialog for each, the dialogs will be shown in this order: 0, 1, 2, 3, ...., ARRAY_LENGTH-1, which means that the last one that will be shown is ARRAY_LENGTH-1. This is the first dialog that you confirm/decline, and when you do it, you actually make a callback for setPositiveButton or setNegativeButton, and (INDEX== ARRAY_LENGTH-1) is true.
To solve this, just change the condition in the callbacks: if(INDEX == 0).

AlertDialog in custom Hashmap array adapter

I am creating a custom Hash map array adapter.In that,when the user clicks on an element, an AlertDialog pops up,in that user can see his messaages,
For this I am using this code,
final AlertDialog.Builder alert = new AlertDialog.Builder(this);
alert.setTitle("PassWord Protected Message");
alert.setMessage("Please Enter The Password to See The Messages");
// Set an EditText view to get user input
final EditText input = new EditText(this);
alert.setView(input);
alert.setPositiveButton("Ok", new DialogInterface.OnClickListener(){
public void onClick(DialogInterface dialog, int whichButton)
{
// Editable value = input.getText();
// Do something with value!
String we=input.getText().toString();
// Toast.makeText(getApplicationContext(), we, Toast.LENGTH_SHORT ).show();
if (we.equalsIgnoreCase("password"))
{
try
{
String[] splitted = smsList.get( pos ).split("\n");
String sender = splitted[0];
for ( int i = 1; i < splitted.length; ++i )
{
//some code here
}
}
catch (Exception e)
{
e.printStackTrace();
}
}
}
});
alert.setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int whichButton) {
// Canceled.
}
});
alert.show();
This AlertDialog will ask user to enter a password.Then user will be able to see the messages.
But I am getting error ,
String[] splitted = smsList.get( pos ).split("\n");
In this,I am getting error on split function and the error is "The method split(String) is undefined for the type HashMap".
You'll have to type cast the smsList to String
String[] splitted = ((String)smsList.get( pos )).split("\n");

Android: MessageBox not working

I am trying to do some data verification. In short, when an add button is pressed, if certain fields are not filled in then I want to display a message box and return from further processing.
This is the flow of my code without the messageBox code:
Button add = (Button) findViewById(R.id.addButton);
add.setOnClickListener(new View.OnClickListener() {
public void onClick(View view) {
//local vars
String access;
String gender;
String avail;
String availCode;
// getting values from selected editItems
String name = textName.getText().toString();
String street = textStreet.getText().toString();
String city = textCity.getText().toString();
String state = textState.getText().toString();
String postal = textPostal.getText().toString();
String country = textCountry.getText().toString();
String directions = textDirections.getText().toString();
String comments = textComments.getText().toString();
//verify miniminal data
if((name.equals("")) || (street.equals(""))|| (city.equals("")) || (state.equals("")) || (postal.equals("")) || (country.equals("")))
{
}
I tried pasting in this code:
//verify miniminal data
if((name.equals("")) || (street.equals(""))|| (city.equals("")) || (state.equals("")) || (postal.equals("")) || (country.equals("")))
{
AlertDialog.Builder builder = new AlertDialog.Builder(context);
builder.setCancelable(false);
builder.setTitle("Title");
builder.setInverseBackgroundForced(true);
builder.setMessage("Must enter minimal data.");
builder.setPositiveButton("Ok", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
dialog.dismiss();
return;
}
});
AlertDialog alert = builder.create();
alert.show();
}
But...I cannot get this line to build:
AlertDialog.Builder builder = new AlertDialog.Builder(context);
Eclipse is saying context cannot be resolved to a variable.
I am confused as to what to do. Can someone help?
I don't see a context variable anywhere in the code above, and AlertDialog.Builder's constructor needs a Context instance passed to it.
However, since you're doing this from an OnClickListener's onClick(), you can use View#getContext() to get a Context instance.
AlertDialog.Builder builder = new AlertDialog.Builder(view.getContext());

Categories

Resources