I am using this function to insert into the database. I'd like to validate inputs from two edittext fields. Whenever I push ok button without giving any inputs, the program crashes.I tried to print the values as well, but it didnt display in logcat.Am i doing anything wrong?
private void add() {
LayoutInflater inflater=LayoutInflater.from(this);
final View addView=inflater.inflate(R.layout.add_country, null);
new AlertDialog.Builder(this)
.setTitle("Add new country/year")
.setView(addView)
.setPositiveButton("OK",
new DialogInterface.OnClickListener() {
public void onClickDialogInterface dialog,int whichButton) {
/* Read alert input */
EditText editCountry =(EditText)addView.findViewById(R.id.editCountry);
String country = editCountry.getText().toString();
EditText editYear =(EditText)addView.findViewById(R.id.editYear);
int year = Integer.parseInt( editYear.getText().toString() );
if(editCountry.getText().toString().trim().length()>0 && editYear.getText().toString().trim().length()>0){
/* Open DB and add new entry */
db.open();
db.insertEntry(country,year);
/* Create new cursor to update list. Must be possible to handle
* in a better way. */
entryCursor = db.fetchAllEntries(); // all country/year pairs
adapter = new SimpleCursorAdapter(CountryEditor.this,
R.layout.country_row,entryCursor,
new String[] {"country", "year"},
new int[] {R.id.country, R.id.year});
setListAdapter(adapter);
db.close();
}
else{
Toast.makeText(CountryEditor.this,
"You need to enter Country AND Year.", Toast.LENGTH_LONG).show();
}
}
})
.setNegativeButton("Cancel",
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog,int whichButton) {
// ignore, just dismiss
}
})
.show();
}
You are calling editBlah.getText().toString() which can return "";
When parsing this to an integer an Exception will be thrown.
( It could also be, if you call .getText() on a view which has initialised to null (ie, you have incorrectly specified the id for the ID you want) a NullPointerException will be thrown. Without the Stacktrace you wouldn't be able to tell which - try and post your stack trace with the question where possible ).
You're question is correct - What you need to do is validate the input you're getting: ie:
int year = Integer.parseInt( editYear.getText().toString() );
should be:
if(editYear.getText().toString().equalsIgnoreCase("")) {
// Cannot parse into an int therefore perform some action which will notify the
// user they haven't entered the correct value.
}
Or even the following if you are already going to be validating your int values:
int year = Integer.parseInt( editYear.getText().toString().equalsIgnoreCase("") ?
"-1" : editYear.getText().toString());
editCountry.getText() equals with nullstring? nullponterexception
Related
In my app i have a function that checks the entered text from a displayed AlertDialog with an input text. If the text is equal to a string variable, return True, else return False, and catch this resulting value to continue conditional code.
But it seems its a little difficult to do this as i've read in other posts asking how to solve the same problem.
I've already done this:
private boolean checkAdministratorPassword() {
final enterPasswordResult[0] = false;
AlertDialog.Builder alert = new AlertDialog.Builder(mContext);
alert.setTitle("Confirm action");
alert.setIcon(R.drawable.ic_launcher);
alert.setMessage("Enter administrator pass to continue");
final EditText input = new EditText(mContext);
input.setPadding(5, 0, 5, 0);
alert.setView(input);
alert.setPositiveButton("Accept", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int whichButton) {
String strPass = input.getEditableText().toString();
if (strPass.length() == 0) {
dialog.cancel();
}
if (strPass.equalsIgnoreCase(Constantes.ADMIN_PASS)) {
enterPasswordResult[0] = true;
dialog.cancel();
} else {
Toast.makeText(mContext, "Invalid pass..!!", Toast.LENGTH_LONG).show();
dialog.cancel();
}
}
});
alert.setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int whichButton) {
dialog.cancel();
}
});
AlertDialog alertDialog = alert.create();
alertDialog.show();
return enterPasswordResult[0];
}
And i call the function this way:
If ( checkAdministratorPassword() == True ){
//true conditions
}
But the problem is that the check function doesnt wait for the result to continue with the code, it just continue by itself and i dont get the appropiate behavior.
The issue is you're trying to handle an async event in the logcal flow of your program. You can do this if you make the Dialog it's own class and use an Interface to callback to your host activity. Check out the documentation on DialogFragment.
public interface PasswordCheckListener{
public void valid(boolean check);
}
private static class PasswordDialog extends DialogFragment {
private PasswordCheckListener listener;
public static PaswordDialog newInstance(PasswordCheckListener listener){
this.listener = listener;
}
#Override
public Dialog onCreateDialog(Bundle savedInstanceState) {
//Put your dialog creation code here
}
private checkAdminPassword(){
//Whatever your check passowrd code is
listener.valid(result);
}
}
I realize I didn't implement all the code for you but that's the general idea. By using an interface you can call back to your host Activity or Fragment when the user enters the password and presses submit. You can then handle the event as it happens, rather than having to deal with it in your program flow.
Thank you all for your answers!! i've found the right way to achieve this problem by creating an Activity whith theme "Theme.Dialog", an input text and two buttons (Accept, Cancel), i start this activity for result asking the user to enter the administrator pass to continue, checking the string and then returning again to onActivityResult() from previous activity with the correct information to proceed.
I'm have some problem about return value from onClick method In DialogInterface.OnClickListener().
Can I return string form edittext in dialog.When I call this method in one time without assign it to other var later.
//Exam Code
public String getPhoneNumber(){
String phoneNumber = "";
AlertDialog.Builder alert = new AlertDialog.Builder(context);
alert.setTitle("Please input phone number");
alert.setMessage("ex. 66898765432");
final EditText phoneNumberEditText = new EditText(context);
phoneNumberEditText.setInputType(InputType.TYPE_CLASS_NUMBER);
alert.setView(phoneNumberEditText);
alert.setPositiveButton("Submit",new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int whichButton) {
phoneNumber = phoneNumberEditText.getText().toString();
{
});
alert.show();
return phoneNumber;
}
in exam code it will return "" back .How I solve this problem.
Thank for all answer :)
Your problem is that you are trying to return a value from the OnClickListener. The listener is supposed to wait for use action whereas the remaining code runs sequentially. You need to pass the value from the OnClickListener to some other method or to a global variable.
See this for a discussion on various ways to achieve this.
I'm not sure if this is a side effect of your formatting or the way your code is structured, but change your alert.setPositiveButton.. section to the following:
alert.setPositiveButton("Submit",new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int whichButton) {
phoneNumber = phoneNumberEditText.getText();
}
});
Remember that phoneNumberEditText.getText() already returns a String, so you don't need .toString() as well. This should work just fine if you've entered numbers in your AlertDialog. Here's a clean example you can use.
I am looking for some help in understanding the workings of the Alert Dialog. I currently have a working dialog that retrieves a listing of players from the SQLite database. The idea is for the user to select a listed player from the list and I store that name in a variable. The snipet of code below gives me the position integer of the name.
return new AlertDialog.Builder(this)
.setCancelable(false)
.setTitle("Choose a Player")
.setSingleChoiceItems(dba.getAllPlayers(), -1, Constants.playerName, new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int item) {
***** get the name of the player selected ****
dialog.dismiss();
startMenu();
}
})
.create();
I need the syntax to reference a cursor. I understand the more basic listing of an array and referencing the selected item from that array (items[item]) as per the doco (http://developer.android.com/guide/topics/ui/dialogs.html), but how do I reference the listing from my call to the database?
Tried playerName = dba.getAllPlayers().getString(item); but I get a "CursorIndexOutOfBoundsException: Index -1 requested, with a size of 1" type error.
Thanks in advance and hope someone might shed some light on this for me. Cheers.
Glenn
Aging Cobol Programmer
Very New to Android
If your do:
playerName = dba.getAllPlayers().getString(item);
You are telling android to search the string in the column number item from the Cursor. This of course makes no sense at all. What you need is to ask for the position, thus this looks better:
final Cursor cursor = dba.getAllPlayers()
.setSingleChoiceItems(cursor, -1, Constants.playerName, new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int item) {
cursor.moveToPosition(item);
String blah = cursor.getString(cursor.getColumnIndex(Constants.playerName));
so I'm creating this android app that reads files. One feature that I want is to allow the user to enter a page number and then have the app open up that specific page number. Because I'm new to Android, I looked up some information online and found some information regarding Edittext and AlertDialog. In my code, if the User opens the menu and hits "Go To" then an AlertDialog opens asking the user to enter a page number. I convert that string into an int, and then the app SHOULD jump to that page. However, for some odd reason, it only jumps to the specified page if the user hits GO TO again from the menu. I'm confused as to why the user has to hit GO TO again for the specified action to take place.
AlertDialog.Builder alert = new AlertDialog.Builder(this);
alert.setTitle("Go to page number...");
alert.setMessage("Enter page number:");
// Set an EditText view to get user input
final EditText input = new EditText(this);
input.setInputType(InputType.TYPE_CLASS_NUMBER);
alert.setView(input);
alert.setPositiveButton("Ok", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int whichButton) {
try {
num = Integer.parseInt(input.getText().toString());
} catch(NumberFormatException nfe) {
System.out.println("Could not parse " + nfe);
}
// Do something with value!
}
});
alert.setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int whichButton) {
// Canceled.
}
});
alert.show();
c = -1;
For this code, I set up a try/catch block to initiate the function. Basically when hitting GO TO from the menu, the variable c becomes equal to -1, I then have an if statement that performs the jump to Nth page only if c = -1.
I just don't get why c isn't set to -1 right after the AlertDialog opens and the user enters a number. Why must it be set to -1 after the user clicks GO TO one more time. Thanks!
What I would do is in the onClick handler for the positive button (Ok), once the num is set, send that number to a method that jumps to the nth page. So something like this:
alert.setPositiveButton("Ok", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int whichButton) {
try {
num = Integer.parseInt(input.getText().toString());
} catch(NumberFormatException nfe) {
System.out.println("Could not parse " + nfe);
}
jumpToPage(num);
}
});
public void jumpToPage(num) {
// jump to page
}
I cannot understand this code in page number 68-69 in Hello Android book. Some methods used in the code are new to me. Can anybody elaborate and explain the code.
private static final String TAG = "Sudoku" ;
private void openNewGameDialog() {
new AlertDialog.Builder(this)
.setTitle(R.string.new_game_title)
.setItems(R.array.difficulty, new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialoginterface,int i) {
startGame(i);
}
})
.show();
}
private void startGame(int i) {
Log.d(TAG, "clicked on " + i);
// Start game here...
}
All it does is when you call openNewGameDialog() it will create an alertdialog with an assigned title and list of options from a resource file ("R.array.difficulty" is an integer value ultimately pointing to a string-array declared in the file /res/values/arrays.xml). An AlertDialog is a simple to create way of getting input from the user. It can also be used for output, but many prefer Toast for that task. The
.show() at the end of it brings the dialog to the foreground.
When the items are added in that call they are assigned an onClick listener which when an item is clicked it sends the index of that item to startGame. In that function it only sends a message including the index to the logcat debug system.