Android Runtime error on passing info between activities - java

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.

Related

EditText to integer in android

i checked this web site on how to convert from string to integer type in java(android).... one of suggestion was to use (integer.parseint) i used it and when i run my application it says my app has stopped working my code below .
public void clickable (View view){
EditText mytext = (EditText) findViewById(R.id.Creat);
int number = Integer.parseInt(mytext.getText().toString());
Toast.makeText(getApplicationContext(), number ,Toast.LENGTH_LONG).show();
}
i cant figure out what is the problem with the code ?!
Declare EditText mytext variable as a global variable and then initialize it in Oncreate() method of your Activity. Then your clickable method looks like this:
public void clickable (View view){
int number = Integer.parseInt(mytext.getText().toString());
Toast.makeText(getApplicationContext(), mytext.getText().toString(), Toast.LENGTH_LONG).show();
}
Obeserve Toast.makeText() method's second argument is the resource id of the string resource to use or it can be formatted text. In your code you have passed an integer as a resource id which does not exist. So you get ResourcesNotFoundException.
What string are you passing into the Integer.parseInt()? If it's not an integer, your program will experience a NumberFormatException. I'm not sure if that's the issue here, but I'm not sure what you're passing into the Integer.parseInt().
There are many implementations of Toast.makeText. As you are passing an int as the second argument, the following implementation will execute:
Toast makeText(Context context, #StringRes int resId, #Duration int duration)
This implementation will throw a ResourcesNotFoundException if it cannot find a resource with the id of resId.
To output number as a String you need to convert it:
Toast.makeText(getApplicationContext(), String.valueOf(number), Toast.LENGTH_LONG).show();

Extract.String Null? No Luck.

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!

Making a TextView visible at runtime in java (Android)

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. :)

getStringExtra() always throws NullPointerException

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

Finish, reload activities

I have application where Activity A allows to set some options and starts (after click on button) Activity B. User can do something in B and when he finishes, he has choice (RadioButtons):
repeat - it means the B Activity will run again with the same options (taken from A),
new - it means application finishes B Activity and goes back to A, where user can set options again and start B again,
end - it goes out from application (I suppose it should finish B and then A Activity).
First I have done this way:
Intent intent = getIntent();
finish();
startActivity(intent);
Another way I could use is to clean all parameters in this Activity, but above was more quickly.
Second is just a finish().
Third is the biggest problem and i don't know how to to this. I tried with startActivityForResult(), onActivityResult() and setResult() but i saw it's impossible to set different results depending on selected RadioButton.
Other method I found is
public static void closeAllBelowActivities(Activity current) {
boolean flag = true;
Activity below = current.getParent();
if (below == null)
return;
System.out.println("Below Parent: " + below.getClass());
while (flag) {
Activity temp = below;
try {
below = temp.getParent();
temp.finish();
} catch (Exception e) {
flag = false;
}
}
}
source
But don't know how to put in current Activity.
Could you help me with this?
"i saw it's impossible to set different results depending on selected RadioButton" isn't really clear to me. Anyway, I suggest you what I would do: Activity A starts Activity B with startActivityForResult() and A wait for a bundle coming from B. When you build the exit function from B to A, create a bundle with your result. In A, you will analyze the bundle coming from B and decide what to do with. If you would exit, call finish().
Edit: Ok this could be your case:
Activity A:
public class XY extends Activity {
// you need that as a flag to go back and forth:
protected static final int SUB_ACTIVITY_REQUEST_CODE_04 = 5337; // choose the number you want...
int result_from_B; // I usually use an int, choose as you want....
static final String KEY_FROM_B = "mKey";
#Override
protected void onActivityResult(int result,int resultCode,Intent data) {
super.onActivityResult(result, resultCode, data);
if (result == SUB_ACTIVITY_REQUEST_CODE_04) {
if (data!=null){
Bundle extras = data.getExtras();
result_from_B = extras.getInt(XY.KEY_FROM_B);
if (result_from_B==1) {
// do what you want
} else {
// do somthing else...
}
}
To call the Activity B, use this:
Intent i = new Intent(this,
ActB.class);
this.startActivityForResult(i,SUB_ACTIVITY_REQUEST_CODE_04);
In the Activity B:
public class ActB extends Activity{
protected final int SUCCESS_RETURN_CODE = 1; // you need it to come back
int result; // this is the result to give to activity A
}
// in the function to build the output:
// I suppose you have already put something in result:
Bundle bundle = new Bundle();
bundle.putInt(XY.KEY_FORM_B, result);
Intent mIntent = new Intent();
mIntent.putExtras(bundle);
ActB.this.setResult(SUCCESS_RETURN_CODE,mIntent);
finish();
This is basic. You can manage also booleans back and forth, arrays, all you want (admitted by a bundle). Just put it in a bundle and go :)
Don't forget to declare your classes (activities) in the Manifest otherwise it will throw an exception runtime.
First of all, you need to keep track of the Intent used to call B. Try the putExtra() method of the intent to B. You can also package everything into a Bundle and restore it with getExtras() (if I recall correctly, that's the method name). When on B, read the Intent used to call it and save the parameters. You also need to startActivityForResult(B) for the following to work.
repeat - it means the B Activity will run again with the same options
(taken from A),
You probably want to call, from B, Activity B again using the FLAG_ACTIVITY_SINGLE_TOP flag in this case. I assume you don't want to have two B instances. Otherwise, just don't use the flag.
Put the Bundle you received from the Intent (from A) again, and catch it (if using single top) in the onNewIntent() method (or just normally, onCreate, if not single top). It goes like this: B -> B onPause() -> B onNewIntent() -> B onResume().
new - it means application finishes B Activity and goes back to A,
where user can set options again and start B again,
Depending on the exact behavior you want, you could call A with FLAG_ACTIVITY_REORDER_TO_FRONT. In this case, you end up with A in the foreground and B in the background (pressing back will go back to B).
Or you could call finish() if you just don't want B anymore, and want to go back to A.
end - it goes out from application (I suppose it should finish B and
then A Activity).
Do nothing on B, setResult() to something like "RESULT_FINISH_EVERYTHING", and when taking care of the results in A (override "onActivityResult()", IIRC), finish activity A also.
but i saw it's impossible to set different results depending on
selected RadioButton.
You could setResult() depending on thw button checked in the radio button. You can set listeners to the radio group and read which button is selected. See RadioGroup.OnCheckedChangeListener or View.OnClickListener if you need actions for eadch individual radio button.
Really, not too complicated. It just depends on what you want. I can clarify all this if you want.
Good luck!

Categories