Got a problem here on exiting onclick.
The program uses shared preferences to get inputs,
and if String name = "User", the program wouldn't let the user click this button and just display an alert dialog box.
This is my code below:
public void onClick(View v) {
name = shared.getString("sharedname", "User");
gender = shared.getInt("sharedgender", 0);
age = shared.getInt("sharedage", 0);
weight =shared.getInt("sharedweight", 0);
height = shared.getInt("sharedheight", 0);
if(name=="User")
{
new AlertDialog.Builder(cont)
.setMessage("Please input your information first")
.setNeutralButton("OK", null).show();
break;//error
}
//code code code, rest of the code to be cancelle
use equals(Object) method instead of == operator
if(name.equals("User"))
{
new AlertDialog.Builder(cont)
.setMessage("Please input your information first")
.setNeutralButton("OK", null).show();
return ;
}
The equals() method of java.lang.Object acts the same as the == operator; that is, it tests for object identity rather than object equality. The implicit contract of the equals() method, however, is that it tests for equality rather than identity. Thus most classes will override equals() with a version that does field by field comparisons before deciding whether to return true or false.
use :
if(name.equalsIgnoreCase("User")){
// your code
return;
}
AlertDialog.Builder builder = new Builder(ValueSelling.this);
AlertDialog alertDialog = builder.create();
alertDialog.setTitle(getResources().getString(R.string.termsTitle));
alertDialog.setMessage(getResources().getString(R.string.terms));
alertDialog.setCancelable(false);
alertDialog.setButton("Okay", new DialogInterface.OnClickListener(){
#Override
public void onClick(DialogInterface dialog, int which) {
finish();
}});
alertDialog.setButton2("Cancel", new DialogInterface.OnClickListener(){
#Override
public void onClick(DialogInterface dialog, int which) {
}});
alertDialog.show();
Instead of using break, simply use a return; statement.
Related
Currently struggling to handle the user input from my AlertDialog box. Everything works fine, but I don't know what to do with the user input in order to save it and access it within another function.
private void promptUser() {
LinearLayout layout = new LinearLayout(this);
layout.setOrientation(LinearLayout.VERTICAL);
final EditText promptTitle = new EditText(this);
promptTitle.setHint("Title");
layout.addView(promptTitle);
userPrompt = new AlertDialog.Builder(this);
userPrompt.setView(layout);
userPrompt.setTitle("Enter map information").setView(layout);
userPrompt.setPositiveButton("Create", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int whichButton) {
Log.i("AlertDialog", "Create button was hit");
Log.i("AlertDialog", "This is the text that was entered:" + promptTitle.getText().toString());
userInputs = promptTitle.getText().toString();
}
});
userPrompt.setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int whichButton) {
Log.i("AlertDialog", "Cancel button was hit");
}
});
userPrompt.show();
}
and where I call the function:
public void onMapClick( LatLng point ) {
promptUser()
//Log.d(userInputs.get(0), "COOL");
}
The main error I'm encountering is that after calling my method promptUser(), everything runs but the next several lines of code don't wait for the user to click the PositiveButton. e.g, my Log shows "User inputs: null", since tempString isn't yet available. How can I make my function wait until the user has hit submit before running the next line of code?
Put the call to onMapClick inside the positive button callback.
userPrompt.setPositiveButton("Create", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int whichButton) {
userInputs = promptTitle.getText().toString();
onMapClick();
}
});
It's a bit hard to tell if this is exactly what you want since you haven't provided enough code, but this is what you asked for.
I want to build a function that creates an AlertDialog and returns the string that the user entered, this the function I have for creating the dialog, how do I return the value?
String m_Text = "";
private String openDialog(String title) {
AlertDialog.Builder builder = new AlertDialog.Builder(view.getContext());
builder.setTitle(title);
final EditText input = new EditText(view.getContext());
input.setInputType(InputType.TYPE_CLASS_TEXT | InputType.TYPE_TEXT_VARIATION_NORMAL);
builder.setView(input);
builder.setPositiveButton("OK", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
m_Text = input.getText().toString();
}
});
builder.setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
dialog.cancel();
}
});
builder.show();
// return string
}
The call builder.show() which opens your AlertDialog is not a blocking call, meaning the next instructions will be executed without waiting for the AlertDialog to finish (return). The way you should interact with it is by using some sort of callback. For instance, your OnClickListeners are an implementation of such a pattern.
A simple callback pattern
One clean way to achieve what you want is to create a Functional Interface which is an interface having only one method. You would use it for handling your callbacks.
Example
interface OnOK{
void onTextEntered(String text);
}
And then you would alter you method to be like:
private void openDialog(String title, final OnOK onOK) {
AlertDialog.Builder builder = new AlertDialog.Builder(view.getContext());
builder.setTitle(title);
final EditText input = new EditText(view.getContext());
input.setInputType(InputType.TYPE_CLASS_TEXT | InputType.TYPE_TEXT_VARIATION_NORMAL);
builder.setView(input);
builder.setPositiveButton("OK", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
//Oi, look at this line!
onOK.onTextEntered(input.getText().toString());
}
});
builder.show();
}
You can use it like this:
openDialog("Title", new OnOK() {
#Override
onTextEntered(String text) {
Log.i("LOG", text);
}
});
This looks to me like you have stored the value of the inputted text in the m_Text field. You can either just return that field or have a variable within the function in which you store the value to be returned.
Where you have:
//Return string
simply replacing with:
return m_Text;
should do the job.
Create another method in the same class that accepts a string value, then call that function providing the value of input.getText().toString() from your setPositiveButton onclick event
I have implemented a dialog box, I also get the text field as a string. Now the problem I have is that I want to compare the text input to a String and exit the app if the text on the dialog box matches either a string under (R.strings.stringname) or either a private String variable.
I have implemented this code but it does not seem to work.
public void onBackPressed(){
AlertDialog.Builder alert = new AlertDialog.Builder(this);
alert.setIcon(R.drawable.ic_about_logo);
alert.setTitle("Phoebus Club");
alert.setMessage("Please Insert Security Key");
// Set an EditText view to get user input
final EditText input = new EditText(this);
alert.setView(input);
alert.setPositiveButton("Enter", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int whichButton) {
securityKey = input.getText().toString();
if(securityKey == "oneplc"){
System.exit(0);
}
}
});
alert.setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int whichButton) {
// Canceled.
}
});
alert.show();
}
Have a look at this question
The == operator doesn't really compare values, rather reference equality. You should use the equals() method of the String object instead:
if(securityKey.equels("oneplc")){
System.exit(0);
}
if static string then instead of
securityKey == "oneplc"
do
securityKey.equals("oneplc");
if from strings.xml then
securityKey.equals(getResources().getString(R.string.stringname));
I have the following code:
protected void showSelectToDialog() {
boolean[] checkedDate = new boolean[toDate.length];
int count = toDate.length;
DialogInterface.OnClickListener setD2 = new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
//TODO Auto-generated method stub
onChangeSelectedTo(which);
}
};
AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setTitle("Select To Year");
builder.setSingleChoiceItems(toDate, count, setD2);
builder.setCancelable(true);
builder.setPositiveButton("Cancel", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
dialog.dismiss();
}
});
dialog2 = builder.create();
dialog2.show();
}
protected void onChangeSelectedTo(int j) {
bTo.setText(toDate[j]);
sTo = ((AlertDialog)dialog2).getListView().getCheckedItemPosition();
blTo = true;
displayToast(String.valueOf(sTo));
to = j;
dialog2.dismiss();
}
What I am looking to do is, when the dialog loads the first time and the user selects a choice it is stored. So the next time the user opens the dialog, it will remember what was select and scroll to that choice.
How do I accomplish that?
Save the selected choice's position for the first time using Shared Preferences.
Then at the start of showSelectToDialog() check if any value exists in Shared Preferences, if so, then set the value of count from the Shared Preferences else set value of count to toDate.length.
I can't see the rest of your code, but all you have to do is save the user's choice in a variable somewhere else, and then read that choice every time you open the dialogue. It could be a static variable on the class, or it could be an instance variable of the class, or it could be a public field of some other class you have access to, like a parent object. You just need to assign it when you close the dialogue, and read it back and initialize the value to what you read when you open the dialogue.
I have the following code for checking empty edit text in an alert dialog, but it is not working
if (mPhoneNumber == null) {
mPhoneNumber = GetNumber();
if (mPhoneNumber == "Error") {
final AlertDialog.Builder alert = new AlertDialog.Builder(this);
alert.setTitle("Warrning");
alert.setMessage("Please Set Your Phone number");
final EditText input = new EditText(this);
input.setInputType(InputType.TYPE_CLASS_PHONE);
alert.setView(input);
alert.setPositiveButton("Ok",new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog,int whichButton) {
String value = input.getText().toString();
while (value.isEmpty())
{
alert.setTitle("Warrning");
alert.setMessage("Please Set Your Phone number");
alert.setView(input);
alert.setPositiveButton("Ok",new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog,int whichButton) {
String value = input.getText().toString();}});
}
String Result = SetNumber(value);
mPhoneNumber = value;
int UserServiceId = CallLogin(mPhoneNumber);
if (UserServiceId > 0) {
Intent Service = new Intent(MainScreeen.this,
RecipeService.class);
Service.putExtra("UserId", UserServiceId);
startService(Service);
} else {
Intent Reg = new Intent(MainScreeen.this,Regsteration.class);
Reg.putExtra("PhoneNumber", mPhoneNumber);
startActivity(Reg);
}
}
});
alert.show();
I need to enforce the user to inter his/her phone number and not leaving the edit text being empty, I used a while loop but it is not working
It looks like you are trying to compare String values. You can't do it like this
if (mPhoneNumber == "Error")
change that to
if("Error".equals(mPhoneNumber))
== compares if they are the same object for Strings but not if they have the same value. Doing it this way you shouldn't need the null check because "Error" won't equal mPhoneNumber if mPhoneNumber is null
Instead of using a while loop, why don't you make your AlertDialog building a separate method and call that method, then in the onClick of your AlertDialog button use an if else to check if that value is empty and if it is make a recursive call on your AlertDialog method.