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.
Related
I have two activity ChatRoom activity and chat_message activty. Inside ChatRoom activity
I have an alertDialog which ask user for their user_name and pass the user_name as string to next activity which is chat_message.
The code for alertDialog Box is
private void request_user_name() {
AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setTitle("Enter name:");
final EditText input_field = new EditText(this);
builder.setView(input_field);
builder.setPositiveButton("OK", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialogInterface, int i) {
name = input_field.getText().toString();
}
});
builder.setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialogInterface, int i) {
dialogInterface.cancel();
request_user_name();
}
});
builder.show();
}
and I use below code to pass the user_name string
intent.putExtra("user_name",name);
Below is code in second activity where i receive the extras
user_name = getIntent().getExtras().get("user_name").toString();
But when user_name is not set, then it app crash with error of java null pointer Exception.
So how to handle the getIntent or how to set the Default username when it receives null value or no value at all??
Thanks in advance.
Suggestion : Always use constants for put extra keys. like
public static final String EXTRA_USER_NAME = "user_name";
Your solution : check if bundle has that key.
String user_name = null;
if (getIntent()!=null && getIntent().getExtras() !=null && getIntent().hasExtra(EXTRA_USER_NAME))
user_name = getIntent().getStringExtra(EXTRA_USER_NAME);
if (!TextUtils.isEmpty(user_name)) {
// TODO: DO HERE YOUR STUFF
}
Also add getIntent()!=null && getIntent().getExtras() !=null if you are not sure to pass extras.
What is happening is that one of the models along the way is returning null because it doesn't exist. Now, depending on your code, it could be the intent, the extras or the name.
You have to preemptively check for each value, before assigning the name string.
if (getIntent().getExtras() != null
&& getIntent().getExtras().get("user_name")!=null) {
user_name = getIntent().getExtras().get("user_name");
}
But this is really a crude way to do it. What you really want to do is something along the lines of:
String name = "";
Intent intent = getIntent();
if (intent != null) {
ExtrasModel extras = intent.getExtras();
if (extras != null) {
name = extras.get("user_name");
}
}
Try this :
String user_name="" ;
if(getIntent()!=null){
if(getIntent().hasExtra("user_name")){
user_name = getIntent().getStringExtra("user_name");
}
}
if(!TextUtils.isEmpty(user_name)){
user_name = "Default"; // Or set your default name
}
TextUtils checks if user_name is null of Empty , if yes then you can set your default username otherwise you have your name passed from previous activity.
Hope this helps!
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).
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.
I FIGURED OUT WHAT I WAS DOING. I HAD THE VARIABLE NAME IN QUOTES WITH THE REST OF THE URL STRING.
How do you save the value of a Radio button into a variable and use that variable later.
I can see the variable Day_Item in my LogCat and the value is in there but when try using Day_Item later it does not show the valuable.
Below is a section of my code that shows the buttons.
String Day_Item = null;
public class SearchDB extends Activity {
private static final String TAG = "MyApp";
String start_log = "STARTED";
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.search_layout);
final RadioButton radio_monday = (RadioButton) findViewById(R.id.monday);
radio_monday.setOnClickListener(radio_listener);
cityspinner.setOnItemSelectedListener(new OnItemSelectedListener() {
#Override
public void onItemSelected(AdapterView<?> parent, View view, int position,long arg3)
{
int id = parent.getId();
if (spinner2_count2 < spinner2_count1 ) {
spinner2_count2++; }
else
{
String city_spinner_log = "CITY SPINNER";
Log.d(TAG, city_spinner_log);
String item = cityspinner.getSelectedItem().toString();
String nameContentType = "name";
String cityURL = "GetRestaurant.php?day=Day_Item&city=" + item;
Log.d(TAG, cityURL);
String shop_data = DataCall.getJSON(cityURL,nameContentType);
Log.d(TAG, shop_data);
Bundle bundle = new Bundle();
bundle.putString("shopData", shop_data);
Intent myIntent = new Intent(SearchDB.this, ShowRestaurant.class);
myIntent.putExtras(bundle);
startActivityForResult(myIntent, 0);
}
}
}
//ONCLICKLISTENER that saves RADIO value into a variable.
public OnClickListener radio_listener = new OnClickListener() {
public void onClick(View v) {
// Perform action on clicks
RadioButton rb = (RadioButton) v;
Day_Item = (String) rb.getText();
Log.d(TAG,Day_Item);
Toast.makeText(SearchDB.this, Day_Item, Toast.LENGTH_SHORT).show();
}
};
}
You would need a bit more code to get a good solid answer. Such as how is Day_Item allocated? And is it's scope global? Are you calling it from another activity or the one it's allocated within? These are just guesses at this point:
1) Are you sure your onClickListener isn't firing multiple times? Thus setting Day_Item to an undesired text or nothing at all?
2) Rather a question/answer,
"but when try using Day_Item later it does not show the valuable"
I'm assuming this means that it is null? Well if it's being set properly, and then it is being null'd... it either is being explicitly null'd by you somewhere (such as (1)) or else the allocation and scope are the issue area I believe...
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