Reputation: 50
I having trouble with making a Textview change text when i push a button from another activity, the button is working from within the same activity as its own but it shuts down my app as soon as I tell it to change text from another activity, my code looks like this:
this is the button code from my main activity:
go = (Button)findViewById(R.id.go);
go.setOnClickListener(new View.OnClickListener()
{
public void onClick(View v)
{
InventoryActivity.fire.setText("1 fire");
}
});
and this is the code from the activity with the TextView I wish to change:
public class InventoryActivity extends Activity
{
public static TextView fire;
@Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_inventory);
fire = (TextView) findViewById(R.id.fire);
}
}
ok thanks again
Upvotes: 0
Views: 1766
Reputation: 20155
fire
Textview in InventoryActivity
will be null
, until it will get its reference in onCreate
after setContentView
setContentView(R.layout.activity_inventory);
this is where your view will be inflated and drawn to the screen.
so it is not possible to Access TextView fire
util the layout inflation takes place.
Solution
What you can do this second piece of string you want to show in the second screen in intent Extra and the get that extra in second activity and set it to the fire
textview.
Upvotes: 1
Reputation: 714
Unfortunately, you wont be able to access view objects from one activity in another activity, when the current inflated layout is from second activity. More info here
My recommended approach: Assuming InventoryActivity will start your SecondActivity, use startActivityForResult()
and onActivityResult()
in InventoryActivity. In your Second Activity use setResult()
with a extra string parameter for the updated text. Example here
You could use shared preferences in other scenarios.
Upvotes: 3