0

I have one button (buttton1) in the first activity and the second activity has a textview (textView1). This is the code that I wrote:

public void buttton1 (View v){

Intent buttton1 = new Intent (MainActivity.this, Back.class);

startActivity(buttton1);

TextView textView = (TextView)findViewById(R.id.textView1);

textView.setText("Hello");

finish();

}

When I run the application and when I click on the button, it force-closes. So please help me where is the fault?

Lundin
  • 195,001
  • 40
  • 254
  • 396
BasILyoS
  • 995
  • 1
  • 10
  • 15
  • do you have a layout for main activity which has a textview with id textView1? and post stack trace/logcat – Raghunandan Aug 15 '13 at 11:45
  • 1
    It might help to tell us what the error is. In your IDE, you should get some kind of exception, which will indicate where the problem occured. – Ewald Aug 15 '13 at 11:46
  • you will need a seperate class for your second activity, else it will never work. – bofredo Aug 15 '13 at 11:52
  • http://stackoverflow.com/questions/15859445/how-do-you-pass-a-string-from-one-activity-to-another/15859488#15859488. pass you string to second activity. in second activity set the content to the activity initialize textview and set the text. – Raghunandan Aug 15 '13 at 11:52

3 Answers3

1

textView is probably null, because it's not in the activity you're trying to access it from, but in the one you're opening. You should use putExtra to send the text to the next activity, and update the textview in that activity.

Ben Williams
  • 6,027
  • 2
  • 30
  • 54
0

If i am getting it right. the textview belongs to the second activity which is back.class. so whatever you have to do with a component of back.class, it must be done in the code of that class.

To make it clearer, let me tell you the two concepts: 1)once you start another acitivty A from another activity B, the control shifts from B to A, hence components of activity A must be defined and controlled in activity A. 2) to make a button do two functions, even if it may actually be possible,it applies to the components of the same activity and not the next activity (back.class).

I hope it cleared few points.

Salik
  • 508
  • 6
  • 17
  • 35
0

Because textView1 belongs to your second activity not the first. According to your codes they try to access textView1 in your first activity, it return null while working with findViewById, first activity can not find a "view" whose ID is textView1. It is absolute wrong!

TeeTracker
  • 7,064
  • 8
  • 40
  • 46