Return value from onClick() In returner method - android

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.

Related

Return Boolean value from Android AlertDialog function

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.

How to transfer parameters value from dialog box to activity in android?

I have an activity (Main) and I inserted a button in it.
When button the user press it, a dialog box with 2 Radio boxes appear. I want to set "1" or "0" value to "ntv", based on which radiobutton is selected, and then use "ntv" value in Main activity, but it seems that this doesnot transfer "ntv" value to Main activity, what is wrong with my code?
final CharSequence[] chan = {"Minutes", "Seconds"};
builder = new AlertDialog.Builder(Main.this);
builder.setTitle("Please Select:");
builder.setSingleChoiceItems(chan, 0, new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int item) {
if(chan[item]=="Minutes")
{
Toast.makeText(getApplicationContext(), "Minutes", Toast.LENGTH_SHORT).show();
ntv="1";
}
else if (chan[item]=="Seconds")
{
Toast.makeText(getApplicationContext(), "Seconds", Toast.LENGTH_SHORT).show();
ntv="0";
}
}
});
AlertDialog alert = builder.create();
alert.show();
I defined "ntv" as string and this is part of code when "ntv" is compared to check if it is "0" or "1"
ImageView set1= (ImageView) findViewById(R.id.set1);
ImageView set2= (ImageView) findViewById(R.id.set2);
if (ntv.equals("0")) {
set1.setVisibility(View.INVISIBLE);
}
if (ntv.equals("1")) {
set2.setVisibility(View.INVISIBLE);
}
and because neither (set1) nor (set2) doesnot go invisible I realize that "ntv" have no value.
This all looks OK (except the suggestion to use equals() instead of == for the string compares, although, as you say, it does work (it just isn't good practice).
The only thing I can think of (without seeing all the code) is that the scope of variable ntv is wrong. Have you declared the variable inside a method? It needs to be defined as an instance variable in your class (ie: not within a method).
you should be doing .equals on the string comparison NOT ==
It is unlikely that your if statements will trigger because of this.
if(chan[item].equals("Minutes"))
{
Toast.makeText(getApplicationContext(), "Minutes", Toast.LENGTH_SHORT).show();
ntv="1";
}
else if (chan[item].equals("Seconds"))
{
Toast.makeText(getApplicationContext(), "Seconds", Toast.LENGTH_SHORT).show();
ntv="0";
}
it's not clear the complete code you use and how you call the code that change visibility. Below an example
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
AlertDialog.Builder builder;
final CharSequence[] chan = {"Minutes", "Seconds"};
builder = new AlertDialog.Builder(MainActivity.this);
builder.setTitle("Please Select:");
builder.setSingleChoiceItems(chan, 0, new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int item) {
if(chan[item].equals("Minutes")) {
showToast("Minutes");
} else if (chan[item].equals("Seconds")) {
showToast("Seconds");
}
}
});
AlertDialog alert = builder.create();
alert.show();
}
private void showToast(String s){
Toast.makeText(getApplicationContext(), s, Toast.LENGTH_SHORT).show();
}
instead of showToast function you can use a your function to change visibility

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.

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