ANDROID: Adding items from an arraylist to an AlertDialog - android

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.

Related

How can we pass any value (selected one) from dialog to activity in android?

I need help to pass values from a custom dialog to an activity.
I cannot understand what should i use. I already used intent, but dialog doesn't support intent value passing .
So anyone can help me here, i am totally stucked.If you have any basic example for it, then that will be excellent.
Thank You.
Snippet from the Google Documentation:
// Alert Dialog code (mostly copied from the Android docs
AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setTitle("Pick a color");
builder.setItems(items, new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int item) {
myFunction(item);
}
});
AlertDialog alert = builder.create();
// Now elsewhere in your Activity class, you would have this function
private void myFunction(int result){
// Now the data has been "returned" (as pointed out, that's not
// the right terminology)
}

how to set different message on application startup in android?

I am creating one application for student. I need to set the different message whenever
user open application.I don't understand how to do this or which method use for this.
I search lot of articles but i didn't found anything.
So please provide me some reference or code.
You can store your messages using any storage like sqlite,file or sharedprefrences and retrive message randomly on app opning..
Save your messages in a persistent storage. In android, you could use SharedPreference http://developer.android.com/reference/android/content/SharedPreferences.html, or a Sqlite databse http://developer.android.com/reference/android/database/sqlite/package-summary.html depending on your specific need. Store the messages in either of them and read back a different message each time.
Store some msgs in a SharedPreference at some point in your Activity:
SharedPreferences pref = getPreferences(Context.MODE_PRIVATE);
Editor ed =pref.edit();
ed.putString("0","msg0");
ed.putString("1","msg1");
ed.putString("2","msg2");
ed.putString("3","msg3");
ed.commit();
Then in onCreate(), retrieve a random sg and diplay to the user:
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
SharedPreferences pref = getPreferences(Context.MODE_PRIVATE);
Random r = new Random();
String msg = pref.getString(r.nextInt(4)+"", "none");
Toast.makeText(this, msg, Toast.LENGTH_LONG ).show();
}
You should read the about the fundamentals of android, this would guide you on how to do this. You're not going to spout garbage at the user, there will be a pattern. Once you find the pattern then you turn that logic into java.
Use AlertDialog
Code example below taken from:
http://www.mkyong.com/android/android-alert-dialog-example/
AlertDialog.Builder alertDialogBuilder = new AlertDialog.Builder(context);
// set title
alertDialogBuilder.setTitle("Your Title");
// set dialog message
alertDialogBuilder.setMessage("Click yes to exit!").setCancelable(false)
.setPositiveButton("Yes", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
// if this button is clicked, close
// current activity
MainActivity.this.finish();
}
}).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();
}
});
// create alert dialog
AlertDialog alertDialog = alertDialogBuilder.create();
// show it
alertDialog.show();

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.

AlertDialog with a Cursor

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

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