check empty edit text in an alert dialog android - java

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.

Related

Returning A Value From AlertDialog

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

Assign value to variable using popup edit text on android studio

I'm trying to make a popup box with edit text field on Android Studio and would like to store the data entered by the user in a variable used in that class.
Something like this:
new AlertDialog.Builder(this)
.setIcon(android.R.drawable.ic_dialog_alert)
.setTitle("New player")
.setMessage("Input new player's name")
.setView(input)
.setPositiveButton("Register", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
name = input.getText().toString(); //<---HERE !want to use this variable
}
})
.setNegativeButton("Cancel", null)
.show();
This doesn't work, so how could I extract the value of name from my popup window to use it in the main code?
Do it this way:
final String[] name = new String[1];
final EditText input = new EditText(this);
new AlertDialog.Builder(this)
.setIcon(android.R.drawable.ic_dialog_alert)
.setTitle("New player")
.setMessage("Input new player's name")
.setView(input)
.setPositiveButton("Register", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
name[0] = input.getText().toString(); <---HERE! want to use this variable
}
})
.setNegativeButton("Cancel", null)
.show();
Access it using name[0]
Clarification for the followup question by Jox in the comment below: To access the variable inside onClick it needs to be final. But, you cannot assign a value to a simple final variable. However, you can assign a value to a Array member. Hence, the array and not a string variable. Btw, Andriod Studio will do it for you this way itself, just follow the suggested fixes for erroring-out code.
You should declare the DialogInterface.OnCLickListener inside of your Activity. By either creating a listener and assingning it or having your activity implement the interface. And then you won't need to declare name as final.
The reason you have to declare name as final is because you're anonmously creating an object to listen to the click, which require a contract of anything external being used by this anonymous class must be declared as final.
I would recommend creating a listener in your Activity and then assign it to the setOnClickListener(x)
Try this, it works for me :
public class Activity extends AppCompatActivity implements DialogInterface.OnClickListener {
private EditText input;
private String str = "";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_result);
input = new EditText(this);
}
public void onClickAlert(View v) {
new AlertDialog.Builder(this)
.setIcon(android.R.drawable.ic_dialog_alert)
.setTitle("New player")
.setMessage("Input new player's name")
.setView(input)
.setPositiveButton("Register", this)
.setNegativeButton("Cancel", null)
.show();
//variable str still equal to "" here
}
#Override
public void onClick(DialogInterface dialog, int which) {
str = input.getText().toString(); /*<---HERE! want to use this variable*/
//use it here
Log.d("Activity", "User input : " + str);
}
}
Implement the OnClickListener in your Activity and read the value of the text field in the callback fonction.

System Exit if dialog textfield matches private text field

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

Local variable not visible inside OnClickListener

I'm developing an Android application and I have a problem:
I have this method:
// User has introduced an incorrect password.
private void invalidPassword()
{
// R.id.string value for alert dialog title.
int dialogTitle = 0;
// R.id.string value for alert dialog message.
int dialogMessage = 0;
boolean hasReachedMaxAttempts;
clearWidgets();
numIntents++;
hasReachedMaxAttempts = (numIntents > maxNumIntents);
// Max attempts reached
if (hasReachedMaxAttempts)
{
dialogTitle = R.string.dialog_title_error;
dialogMessage = R.string.dialog_message_max_attempts_reached;
}
else
{
dialogTitle = R.string.dialog_title_error;
dialogMessage = R.string.dialog_message_incorrect_password;
}
AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setMessage(dialogMessage)
.setTitle(dialogTitle);
builder.setPositiveButton(R.string.ok, new DialogInterface.OnClickListener()
{
public void onClick(DialogInterface dialog, int id)
{
// TODO: User clicked OK button
if (hasReachedMaxAttempts)
{
}
else
{
}
}
});
AlertDialog dialog = builder.create();
dialog.show();
}
How can I make visible boolean hasReachedMaxAttempts; inside onClick?
you need that variable to be final;
final boolean hasReachedMaxAttemptsFinal = hasReachedMaxAttempts;
AlertDialog.Builder builder = new AlertDialog.Builder(this);
if (hasReachedMaxAttemptsFinal)
Declare your final boolean hasReachedMaxAttempts; variable at class level and it should get the task done
It is visible, but it needs to be set to final.
final boolean hasReachedMaxAttempts = (numIntents > maxNumIntents);

how to quit a loop or onClick(android)?

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.

Categories