I get a nullPointerException on status variable on this line of code : if (view.getId() == R.id.button && status.equals("Dorado"). Now ive looked on many threads in here and i havnt really gotten much luck with this exception. Like many others, i pass a string from activity 1 to activity 2, except this string is extracted from the textview when it is pressed(Dorado).
Activity 1:
TextView text = (TextView) view;
String selection = text.getText().toString();
Bundle b = new Bundle();
b.putString("Selection", selection);
Intent i = new Intent(MunicipioList.this,SubestacionInfo.class);
i.putExtra("extra", b);
startActivity(i);
Acitivity 2:
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_subestacion_info);
Bundle extras = getIntent().getExtras();
if (extras != null) {
extras = extras.getBundle("extra");
status = extras.getString("Selection");
}
}
I know the bundle isnt necessary i was just experimenting since i was still getting Null with other codes. Ah one more thing, the status varoable is global, declared right at the beginning of the activity as "public String status;" so i dont believe that to be the issue here, Any help? :)
Lets break this down. If you get an NPE in this line:
if (view.getId() == R.id.button && status.equals("Dorado"))
then either:
view is null, or
R.id is null (which I think is impossible), or
status is null.
You should be able to work out which with a debugger, or by adding a traceprint. But I suspect that it is status.
You say:
Ah one more thing, the status variable is global, declared right at the beginning of the activity as "public String status;" so I don't believe that to be the issue here.
That declaration does not initialise status. Did you initialize status following the declaration? If not, its initial value will be null, and that would be sufficient to cause an NPE ... if you never changed it!
Related
I have 2 activities in my assignment: MainActivity and Country_Activity.
I'm trying to pass 2 inputs the user puts in MainActivity:
int counter
String Country
But the app always crashes here: (this is Country_Activity)
private void Update(){
Intent mIntent = getIntent();
int intValue = mIntent.getIntExtra("intCounter", 0);
String country = mIntent.getStringExtra("country");
counterTextView.setText(intValue);
countryTextView.setText(country);
if (country.equals("canada")){
flagView.setImageResource(R.drawable.canada);
}
else if (country.equals("us")){
flagView.setImageResource(R.drawable.us);
}
}
Specifically on the lines "setText" for each variable.
Everything else works. I can't figure out why they wouldn't.
Thanks!
Usually the extras that are passed from one activity to another are read inside on onCreate() where all the needed initialization of variables and views is made.
In your case I see that you get the extras inside another method (maybe it's called inside onCreate()?).
So you forgot to initialize the textviews:
TextView counterTextView = findViewById(R.id.countersomething);
TextView countryTextView = findViewById(R.id.countrysomething);
also another error that you will encounter later is this:
counterTextView.setText(intValue);
change it to:
counterTextView.setText(String.ValueOf(intValue));
Don't pass an integer value inside setText() because it will be treated as the id of a resource.
This question already has answers here:
What is a NullPointerException, and how do I fix it?
(12 answers)
Closed 7 years ago.
Brief description about what I am trying to do:
It's a simple messaging app
In my first activity I have a list-view and few buttons.
User presses any of the button and the information about which button was pressed was stored in shared preferences.
When user presses any list item, an intent is triggered that takes him to new activity where which list item was pressed is analyzed by putExtra() from intent.
In second activity, depending on which value came with intent, a string value for newString is decided.
Problem
When screen rotates, app crashes with this error -
Attempt to invoke virtual method 'int java.lang.String.hashCode()' on a null object reference
Following is the code in second activity -
String newString = "Default_Channel";
public static final String MyPREFERENCES = "MyPrefs" ;
SharedPreferences sharedpreferences;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_chat2);
.
.
.
sharedpreferences = getSharedPreferences(MyPREFERENCES, Context.MODE_PRIVATE);
String restoredText = sharedpreferences.getString("CurrentUser", null);
if (restoredText != null) {
currentUserName = sharedpreferences.getString("CurrentUser", "unknown");//"unknown" is the default value.
.
.
.
}
else
{
currentUser.setText("not signed in");
}
if (savedInstanceState == null)
{
Bundle extras = getIntent().getExtras();
if(extras == null)
{
newString= "Default_Channel";
}
else
{
newString= extras.getString("LIST_ITEM_CLICKED");
}
}
else
{
newString= (String) savedInstanceState.getSerializable("LIST_ITEM_CLICKED");
}
// *** GETTING ERROR HERE On this line *** //
switch (newString)
{
case "User_1":
.
.
.
break;
case "User_2":
.
.
.
break;
case "User_3":
.
.
.
break;
case "Default_Channel":
.
.
.
break;
}
I am getting NULL pointer exception where I have mentioned it in code ! Its Line between Else statement and Switch.
Also, I understand what is NULL pointer exception and this is not what I am asking. I am getting NULL pointer when screen rotates, i.e. when activity restarts without intent.
I am new to android programming and not able to figure out what's going wrong here.
Edit: This is not duplicate question with "What is NULL pointer exception".
I see you use this:
newString= (String) savedInstanceState.getSerializable("LIST_ITEM_CLICKED");
So do you override onSaveInstanceState?
If not, override it and save your current value of "LIST_ITEM_CLICKED".
I think your problem is because when rotate, activity is recreated with a savedInstanceState, but you don't save your value, so a NPE occurs.
Basically you are getting NullPointerException.The code you posted is not clear where actually you are getting this. You need to check whether object on which you are performing operation is null or not and proceed based on that. See What is a NullPointerException, and how do I fix it?
I have two activities; the first activity starts the second one with some data passed through the intent.
Intent i = new Intent(this,BActivity.class);
i.putExtra("identify", "c2f");
startActivityForResult(i, 1);
In the second activity, I want to make some TextViews/EditTexts visible (which are initially set to invisible) based on the information passed from the first activity.
Here's the code for that:
tv1 = (TextView)findViewById(R.id.textView2);
tv2 = (TextView)findViewById(R.id.textView3);
et1 = (EditText)findViewById(R.id.editText1);
et2 = (EditText)findViewById(R.id.editText2);
button = (Button)findViewById(R.id.send_result);
Bundle extras = getIntent().getExtras();
String identifier = extras.getString("identify");
if(identifier == "c2f")
{
tv1.setVisibility(0);
tv1.setText("Celcius");
et1.setVisibility(0);
}
else if(identifier == "f2c")
{
tv1.setVisibility(0);
tv1.setText("Fahrenheit");
et1.setVisibility(0);
}
else if(identifier == "currency")
{
tv1.setVisibility(0);
tv1.setText("Amount");
tv2.setVisibility(0);
tv2.setText("Conv. Rate");
et1.setVisibility(0);
et2.setVisibility(0);
}
Now when the second activity starts, none of these TextViews or EditTexts seem to get visible!
identifier (string) holds the correct value passed from first activity and it even goes into the if conditions, but it doesn't make any view visible.
Am I making any mistake in trying to make these views visible?
Use .equals instead of == to string comparison. You can also use the variable after the quoted string to avoid nullpointer. And you can use TextView.VISIBLE, it's a constant to get it visible.
if("c2f".equals(identifier))
{
tv1.setVisibility(TextView.VISIBLE);
tv1.setText("Celcius");
et1.setVisibility(TextView.VISIBLE);
}
Simply use the View's constants for this.
your_view.setVisibility(View.VISIBLE);
This will make your View visible.
your_view.setVisibility(View.INVISIBLE);
This will make it invisible but still with the layout visible (basically, the space where it goes remains untouched)
your_view.setVisibility(View.GONE);
This will make your View disappear, like it never existed!
As pointed by giacomoni, please use equals for String comparison. Here is a link to explain why.
http://javarevisited.blogspot.in/2012/03/how-to-compare-two-string-in-java.html
Also, try using the standard View.VISIBLE etc constants for showing and hiding views. They are much more easy to use and understand. Happy coding. :)
Main activity:
Intent intent = new Intent(Main.this, Secondary.class);
intent.putExtra("name",value);
startActivity(intent);
Secondary activity:
String value = getIntent().getStringExtra("name")
What's wrong here? I've searched a lot without success...
Thanks
Try this:
In the MainActivity:
//Make sure Secondary is an Activity name. Secondary.class.
Intent intent = new Intent(MainActivity.this, Secondary.class);
intent.putExtra("name",value);
startActivity(intent);
In the Secondary Activity:
String value = getIntent().getExtras().getString("name");
You need to get the bundle first and then extract the string from it.
Bundle bundle = getIntent().getExtras();
if (bundle != null) {
bundle.getString("name");
}
Both should work. The second one is to check if the bundle is null.
When you call putExtra(...), make sure the value object is a String. If you're passing any other object, make sure to explicitly call value.toString(), especially if dealing with GUI components.
See here for more information: Android Intent.getStringExtra() returns null
I have used this method times. Just make sure value has a value or initialized.You can use Log or System.out.println(value); after .putExtra to see(in console tab) if value is null. and in second activity too.
Change this line
String value = getIntent().getStringExtra("name");
TO this line
String value = getIntent().getString("name");
I have discovered I have an issue in my code it was my fault. It wasn't an Intent problem. Thank you all.
You can try this -->
intent.putExtra("name", textView.getText().toString());
If the error still occurs, check-in the Second Activity that you are using the right id path...:-
value = findViewById(R.id.);
I have been having a problem with a Boolean in an if statement all day and it is really starting to irritate me now!! I have looked at other Android threads on here and the solutions just don't seem t work.
My code started off like this:
public class MainActivity extends Activity
{
public static boolean isSignedIn = false;
public final static String USERNAME_MESSAGE = "com.example.libnoise.MESSAGE";
Button btnSignIn;
#Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
btnSignIn = (Button) findViewById(R.id.btnSignIn);
Intent intent = getIntent();
String message = intent.getStringExtra(PlayZone.USERNAME_MESSAGE);
if(isSignedIn == false))
{
btnSignIn.setText("SignIn");
}
else
{
btnSignIn.setText(message);
}
}
Then I had a thought that made it's not like other languages and I only need one "=" sign so I had it as this:
if(isSignedIn = false)
{
btnSignIn.setText("SignIn");
}
else
{
btnSignIn.setText(message);
}
That didn't work and that's when I started looking online, after finding a previous thread on here changed it to the following:
if("false".equals(isSignedIn))
{
btnSignIn.setText("SignIn");
}
else
{
btnSignIn.setText(message);
}
Now that doesn't look right to me in the first place but hoped it would work and it didn't.
As this is the MainActivity it loads first however since I added all this, the app crashes before it will even load when I take out the if statement it work as expected.
Any ideas?
This
if (isSignedIn == false)
is perfectly correct. (You could also write if (!isSignedIn), but that's just a matter of style.)
Note that, since you never change the value of isSignedIn (at least not in the code you have shown us), it will always be false.
i think you can simply use
if(!isSignedIn)
{
btnSignIn.setText("SignIn");
}
else
{
btnSignIn.setText(message);
}
the way you followed is also correct i didn't find any mistake in except you are using extra bracket in condition if(isSignedIn == false))
If statements with boolean are same how you do it in Java, == is the right way to compare
The problem in your code is extra bracket
if (isSignedIn == false))
Just to deviate from the question, but point out what is possibly your problem, your null pointer could be because you are accessing a UI object that may well not be ready to have it's text set yet.
While some API versions cope fine with what you're doing, I've found many device/API combos simply aren't ready to have anything changed from what's in the xml until onStart. The general guidance is to load data in onCreate, but not start doing anything until onStart.