Java /Android Dialog with EditText - Boolean check on strings - java

I have a boolean method returning true or false to check whether or not data exists inside of strings. Everything works ok if the user enters all data or does not run through the dialogs.....BUT....if the user DOES NOT enter data in the "getItemsEditText" dialog popup AND still clicks "OK", this boolean is resolving to true, even though "pricePerItemText" still has nothing stored. This is the boolean method:
public Boolean doesAllDataExistCheckBool ()
{
if (pricePerItemText != "" && itemsPerDayText != "" && sleepTimeText != "" &&
wakeTimeText != "")
{
SharedPreferences.Editor editor = mySharedPreferences.edit
(); //opens shared preference editor
editor.putBoolean("storedDoesAllDataExist", true);
editor.commit(); //commit changes to mySharedPreferences
//End storing shared preferences
return true;
}
else
{
SharedPreferences.Editor editor = mySharedPreferences.edit
(); //opens shared preference editor
editor.putBoolean("storedDoesAllDataExist", false);
editor.commit(); //commit changes to mySharedPreferences
//End storing shared preferences
return false;
}
}
Here is where the boolean is being tested to see if true or false:
if (position == 4)
{
allDataExists = doesAllDataExistCheckBool (); //checks if true or false
if (serviceStarted == true)
{
Context context = getApplicationContext();
String text = "Schedule is already running";
int duration = Toast.LENGTH_SHORT;
Toast toast = Toast.makeText(context, text, duration);
toast.show();
}
if (serviceStarted == false && doesAllDataExistCheckBool () == true)
{
startScheduleService();
}
if (serviceStarted == false && doesAllDataExistCheckBool () == false)
{
Context context = getApplicationContext();
String text = "Please enter all data before starting!";
int duration = Toast.LENGTH_SHORT;
Toast toast = Toast.makeText(context, text, duration);
toast.show();
}
}
Here is how the dialog with EditText and OK/Cancel buttons is written:
case ITEMS_PER_DAY :
LayoutInflater li = LayoutInflater.from(this);
final View itemsEntryView = li.inflate(R.layout.settings_dialog_input, (ViewGroup)
findViewById(R.id.layout_root));
final EditText getItemsEditText = (EditText)itemsEntryView.findViewById
(R.id.DialogEditText);
return new AlertDialog.Builder(SettingsActivity.this)
.setTitle("This is the title")
.setView(itemsEntryView)
.setPositiveButton("Ok", new DialogInterface.OnClickListener()
{
public void onClick(DialogInterface dialog, int whichButton)
{
itemsPerDayText = getItemsEditText.getText().toString(); //gets input from
edittext and saves it to a string itemsPerDayText
//Initialize shared preferences
SharedPreferences.Editor editor = mySharedPreferences.edit(); //opens editor
editor.putString("storedItemsPerDayText", itemsPerDayText);
editor.commit(); //commit changes to mySharedPreferences
//End storing shared preferences
}
})
.setNegativeButton("Cancel", new DialogInterface.OnClickListener()
{
public void onClick(DialogInterface dialog, int whichButton)
{
//user click cancel
}
}).create();
Is there another way to do this? Why can the user still click "OK" if they did not enter anything at all? Any ideas? Thanks guys!

You posted way too much code. But right away I noticed this
pricePerItemText != ""
Assuming pricePerItemText is a string, which we really have no idea since you didn't include that, that's not how you compare strings in java. It needs to be
!pricePerItemText.equals("");
Edit:
In java, the == operator compares objects references, not values. So
String mytext = "text";
if (mytext == "text"){ print "True"}
will never print true because the mytext variable is pointing to some memory location, which is most definitely not the same as where "text" points to.
The fact that
"text == "text"
is true is a an artifact of Java keeping a string pool so it doesn't have to reallocate new strings. This is a major cause of confusion.
Here's a random link which describes it probably better
http://leepoint.net/notes-java/data/expressions/22compareobjects.html

Related

setSingleChoiceItems value doesn't stick after Activity kill

Hello guys and Happy new year to all!
I'm having a weird trouble in my app which I can't seem to fix. It should be a logic error, but I'm not able to somehow catch it.
Here is my code
public String[] str={"Disabled","Sound Quality Prefered","Bass Prefered","Battery Prefered",};
public int ThemePresetValue = 0;
private int SelectedThemePresetValue = 0;
public void presets() {
AlertDialog.Builder alertDialog = new AlertDialog.Builder(this);
alertDialog.setTitle("Select Your Sound Preset");
alertDialog.setNegativeButton("Cancel", null);
alertDialog.setPositiveButton("Select", themePresetDialogPositiveListener);
alertDialog.setSingleChoiceItems(str, ThemePresetValue, PresetListListener);
alertDialog.show();}
DialogInterface.OnClickListener PresetListListener =
new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
SelectedThemePresetValue = which;
}
};
DialogInterface.OnClickListener themePresetDialogPositiveListener =
new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
mPreset = "";
ThemePresetValue = SelectedThemePresetValue;
if (ThemePresetValue == 0) {
mPreset = "Disabled";
} else if (ThemePresetValue == 1) {
mPreset = "Sound Quality Prefered";
} else if (ThemePresetValue == 2) {
mPreset = "Bass Prefered";
} else if (ThemePresetValue == 3) {
mPreset = "Battery Prefered";
}
if (mPreset.equals("Disabled")) {
disabler();
} else if (mPreset.equals("Sound Quality Prefered")) {
SoundQPreset();
} else if (mPreset.equals("Bass Prefered")) {
bassPreset();
} else if (mPreset.equals("Battery Prefered")) {
batteryPreset();
}
}
};
The problem is that after I choose one of the presets the choice sticks until the app is closed from multitasking (MainActivity gets restarted or killed). Then if I re-open the app, the choice of dialog is re-set onto 0 ("Disabled").
Why is this happening? Do you have a solution?
Yes, the field is created each time anew for the respective object and since this object (i.e. the activity) is destroyed the memory holding the field is freed up as well. So the field's lifespan is bounded by that of the object. To make it continuous, you better save the value in SharedPreferences, or in general to write it out to some storage, before destroying the activity, e.g. in onPause() and then fetch it from those preferences in onCreate() or onResume() callbacks. For example:
/*--- Saving ---*/
SharedPreferences prefs =
getApplicationContext().getSharedPreferences(PREFERENCES_NAME, Context.MODE_PRIVATE);
prefs.edit().putInt(KEY_NAME, VALUE).apply();
/*--- Retrieving ---*/
int oldValue =
getApplicationContext().getSharedPreferences(PREFERENCES_NAME, Context.MODE_PRIVATE)
.getInt(KEY_NAME, 0);
PREFERENCES_NAME is the file name of your shared preferences file. KEY_NAME is the key, under which you save and later retrieve the stored value. VALUE is simply the value to save.
Hope this helps!
As you are not persisting the user's choice, the choice remains in memory until activity finishes. You should save the user's choice locally using SharedPreferences or sqlite for instance!
When the activity restarts you can read the saved value and set the option as selected!

Check if intent is empty or not

I have a rating bar in one activity and once a rating is chosen I want it to pass the value through an intent back to the main activity for display in an alert dialog. Here is the code and it works fine:
public void addListenerOnRatingBar() {
ratingBar = (RatingBar) findViewById(R.id.ratingBar);
txtRatingValue = (TextView) findViewById(R.id.txtRatingValue);
//if rating value is changed,
//display the current rating value in the result (textview) automatically
ratingBar.setOnRatingBarChangeListener(new RatingBar.OnRatingBarChangeListener() {
public void onRatingChanged(RatingBar ratingBar, float rating,
boolean fromUser) {
txtRatingValue.setText(String.valueOf(rating));
String numStars = String.valueOf(rating);
Intent a = new Intent(getBaseContext(), MainActivity.class);
a.putExtra("numStars", numStars);
startActivity(a);
}
});
}
On the main activity I am trying to set up an if statement so that the alert dialog only comes up if the string isn't empty but it's crashing the program everytime. Here is the code:
Bundle extra = getIntent().getExtras();
String numStars = extra.getString("numStars");
if (numStars.length() == 0) {
final AlertDialog dialog = new AlertDialog.Builder(this).create();
dialog.setMessage("Thank you for rating this app " + numStars + " Stars! ");
dialog.setButton(DialogInterface.BUTTON_POSITIVE, "Ok", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
dialog.dismiss();
}
}
);
dialog.show();
}
Any idea what I'm doing wrong?
String numStars = extra.getString("numStars");
if (numStars.length() == 0) {
This is not the correct way to check if the value exists or not.
If a value does not exist in a Bundle, attempting to get it returns null, therefore you must check it like this:
String numStars = extra.getString("numStars");
if (numStars == null) {
Keep in mind that if you have not added data to the intent with putExtra(), the bundle will be empty and getIntent().getExtras() will return null. So for that scenario it would be wise to also add a if (extra == null) check.
It is also possible to provide a default value that getString should return if the value wasn't found. In that case you can use numStars.length() == 0):
String numStars = extra.getString("numStars", ""); // default value of ""
if (numStars.length() == 0) {
Switch:
String numStars = extra.getString("numStars");
To this:
String numStars = getIntent().getStringExtra("numStars");
Since you're passing a String to MainActivity & not a bundle, of course your extra bundle will always be null.

Creating app in Android studio but keep getting an error Required Boolean found int

So I'm creating an app that validates a users input but when I did it for the password all it says is Required boolean found int
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_user);
submit = (Button)findViewById(R.id.submit);
name = (EditText)findViewById(R.id.name);
pass = (EditText)findViewById(R.id.pass);
number = (EditText)findViewById(R.id.number);
email = (EditText)findViewById(R.id.email);
submit.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
final String Name = name.getText().toString();
final String Pass = pass.getText().toString();
if(name.length()==0)
{
name.requestFocus();
name.setError("Field cannot be empty");
}
else if(!Name.matches("[a-zA-Z]+"))
{
name.requestFocus();
name.setError("ENTER ONLY ALPHABETICAL CHARACTERS");
}
else if (pass.length())
{
pass.requestFocus();
pass.setError("FIELD CANNOT BE EMPTY");
}
else {
Context context = getApplicationContext();
CharSequence text = "Thank you, your request is being processed!";
int duration = Toast.LENGTH_SHORT;
Toast toast = Toast.makeText(context, text, duration);
toast.show();
}
}
});
}
The error is happening on the line where it says pass.length. Could anyone please help in what the problem is
Use
else if (pass.length()>0)
instead so that you get a boolean value to use inside the if condition
While using conditional statements you have to use boolean variable to check the condition is valid or not.
else if (pass.length())
Here pass.length() returns the length of the variable, which is an integer. You should not use the integer to check the condition.
In contrast with e.g. C/C++ language, Java does not allow numeric values to be used instead of boolean values (0/1 != false/true).

Save radio button selection in Android alert dialog

I can save the choice while I am using the app, but whenever I close the app and restart it, the choices are empty again. Where am I going wrong? It is always loading the default "0" instead of remembering the last selection.
SharedPreferences preferences = PreferenceManager.getDefaultSharedPreferences(this);
final SharedPreferences.Editor editor = preferences.edit();
SharedPreferences choiceSettings = getSharedPreferences("currentChoice", 0);
final int[] currentChoice = {choiceSettings.getInt("currentChoice", 0)};
final CharSequence[] items = {"AT&T", "Tmobile", "Verizon", "Sprint", "Other"};
// Decide which carrier, so we can apply the correct forwarding code.
final AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setTitle("Select your carrier");
builder.setIcon(R.drawable.ic_launcher);
builder.setSingleChoiceItems(items, currentChoice[0],
new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int item) {
// TODO Auto-generated method stub
switch (item) {
case 0:
Toast.makeText(getApplicationContext(),
items[item], Toast.LENGTH_SHORT).show();
// Your code when first option seletced
currentChoice[0] = 0;
editor.putInt(String.valueOf(currentChoice[0]), 0);
editor.putString("fCode", "*67*");
editor.apply();
break;
case 1:
// Your code when 2nd option seletced
Toast.makeText(getApplicationContext(),
items[item], Toast.LENGTH_SHORT).show();
currentChoice[0] = 1;
editor.putInt(String.valueOf(currentChoice[0]), 0);
editor.putString("fCode", "*67*");
editor.apply();
break;
case 2:
// Your code when 2nd option seletced
Toast.makeText(getApplicationContext(),
items[item], Toast.LENGTH_SHORT).show();
currentChoice[0] = 2;
editor.putInt(String.valueOf(currentChoice[0]), 0);
editor.putString("fCode", "*67*");
editor.apply();
break;
}
dialog.cancel();
}
});
AlertDialog alert = builder.create();
alert.show();
}
In the beginning (line 4), you try to load a variable named "currentChoice":
final int[] currentChoice = {choiceSettings.getInt("currentChoice", 0)};
In general you save a variable with editor.putInt(String key, int value). So key is the name used for saving your variable.
When you write
currentChoice[0] = 0;
editor.putInt(String.valueOf(currentChoice[0]), 0);
String.valueOf(currentChoice[0]) becomes "0". You save an int 0 to a variable named "0".
So change the second line to
editor.putInt("currentChoice", currentChoice[0]);
You are using two shared preferences container, the default one and a custom one. Use only the default one.
SharedPreferences preferences = PreferenceManager.getDefaultSharedPreferences(this);
final SharedPreferences.Editor editor = preferences.edit();
final int[] currentChoice = {preferences.getInt("currentChoice", 0)};

check empty edit text in an alert dialog android

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.

Categories