AlertDialog with a Cursor - android

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));

Related

How exactly to act on a confirmation dialog?

New to Android... I understand Dialogs are asynchronous. But I really can't get my head around the flow for confirming an action. Can someone please explain the flow?
I want to save a file on the sdcard. The Activity prompts the used for the filename. Then it checks to see if the file exists. If it exists, it needs to prompt the user to confirm if they want to overwrite it. Then it proceeds to erase and write the file.
I know you can't hold execution waiting for the response. How then would this common flow work in Android?
Thanks
I am not 100% it is what you are looking for, but here is a link to the Android documentation explaining how we should display Confirmation and Acknowledgement popups using the "Android standard way":
http://developer.android.com/design/patterns/confirming-acknowledging.html
I do not know the exact flow, I suppose it would depend on how the application was written. I would check for the file if it existed call the dialog windows then if the Ok/Yes/Confirm is pressed overwrite the file.
Dialogs | Android Developers - Has an excellent code example
public class FireMissilesDialogFragment extends DialogFragment {
#Override
public Dialog onCreateDialog(Bundle savedInstanceState) {
// Use the Builder class for convenient dialog construction
AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());
builder.setMessage(R.string.dialog_fire_missiles)
.setPositiveButton(R.string.fire, new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
// FIRE ZE MISSILES! AKA Overwrite your file.
}
})
.setNegativeButton(R.string.cancel, new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
// User cancelled the dialog AKA do nothing
}
});
// Create the AlertDialog object and return it
return builder.create();
}
}
I know it's slightly silly example but basically check for the file (if exist) > Call Dialog (if yes)> Overwrite.

ANDROID: Adding items from an arraylist to an AlertDialog

I am trying to add the contents of my array list to an AlertDialog, but it comes up with error:
java.lang.IllegalStateException: Could not execute method of the activity
Here is my code snippet that I am having problems with:
public void ShowOnlineUserDialog(){
CharSequence[] users = {_onlineUsers.get(1), _onlineUsers.get(2), _onlineUsers.get(3), _onlineUsers.get(4)};
AlertDialog.Builder onlineUser = new AlertDialog.Builder(this);
onlineUser.setTitle("Online Users");
onlineUser.setItems(users, new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
System.out.println("User clicked!");
}
});
onlineUser.setPositiveButton("OK", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
dialog.cancel();
}
});
onlineUser.show();
}
Moreover, is there a more efficient way of adding to the alertbox, for loop maybe? I'm sorry but my lack of knowledge in arrays fails me.
Any help would be amazing! Thank you!
EDIT: If I set my code out this way:
String user1 = _onlineUsers.get(1);
String user2 = _onlineUsers.get(0);
CharSequence[] users = {user1, user2};
It works perfectly, but I would like to find a more efficient way?
You can do something like this:
Take String[] users instead of the CharSequence[] users
and do like below:
users = new String[_onlineUsers.size()];
System.out.println("Total Item is: "+_onlineUsers.size());
users = _onlineUsers.toArray(users);
System.out.println("USERS :"+_onlineUsers.toArray(users));
That will convert your whole ArrayList<String> _onlineUsers to String[] users.
Hope it will help you.
Be Free to ask any question if it is not solve your issue.
Your code is correct and has no bug. I think you have to check it -
CharSequence[] users = {_onlineUsers.get(1), _onlineUsers.get(2), _onlineUsers.get(3), _onlineUsers.get(4)};
Check that it is able to fetch string from it or not.

Return value from onClick() In returner method

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.

validate the edittext field inside alertdialog

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

Can any body explain this code from Hello Android book

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.

Categories

Resources