-1

I'm working on activities communication.

This is my main2activity class:

public class Main2Activity extends AppCompatActivity {
TextView textView ;


@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main2);
    textView =(TextView) findViewById(R.id.textView2);
    Intent intent = getIntent();
    String received = intent.getStringExtra("input");

    textView.setText(received);
}
protected void changeActivity(View view){

    Intent intent = new Intent(getApplicationContext(),MainActivity.class);
    startActivity(intent);

}}

I am using a editText at mainActivity. Write something on editText than

protected void changeActivity(View view){

    userInput = findViewById(R.id.editText);
    Intent intent = new Intent(getApplicationContext(),Main2Activity.class);

    intent.putExtra("input",userInput.getText().toString());

    startActivity(intent);

}

Mainactivity buttoncommand like this press button and send what am i write on editText. But i dont understand something. if i change place textView =(TextView) findViewById(R.id.textView2); this code to out of the method. I am use it under the class. like this

public class Main2Activity extends AppCompatActivity {
TextView textView =(TextView) findViewById(R.id.textView2);


@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main2);
    Intent intent = getIntent();
    String received = intent.getStringExtra("input");

    textView.setText(received);
}
protected void changeActivity(View view){

    Intent intent = new Intent(getApplicationContext(),MainActivity.class);
    startActivity(intent);

}}

application doesn't work on emulator i write something on editText and click button then app go wrong. I don't understand this. Reality(For real smartphones not emulator) is that true? İf reality doesn't work. why what is my mistake?

AskNilesh
  • 67,701
  • 16
  • 123
  • 163

1 Answers1

3

You can call findViewById() after setContentView() Because android load xml in setContentView()

and after that you can use findViewById()

AskNilesh
  • 67,701
  • 16
  • 123
  • 163
Rofie Sagara
  • 289
  • 5
  • 17