-1

I'm trying to set a textview to a editText text. When I do that I have this error:

    Process: com.example.game, PID: 9829
    java.lang.NullPointerException: Attempt to invoke virtual method 'void android.widget.TextView.setText(java.lang.CharSequence)' on a null object reference
        at com.example.game.MainActivity.onClick(MainActivity.java:79)
        at android.view.View.performClick(View.java:5637)
        at android.view.View$PerformClick.run(View.java:22429)
        at android.os.Handler.handleCallback(Handler.java:751)
        at android.os.Handler.dispatchMessage(Handler.java:95)
        at android.os.Looper.loop(Looper.java:154)
        at android.app.ActivityThread.main(ActivityThread.java:6119)
        at java.lang.reflect.Method.invoke(Native Method)
        at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:886)
        at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:776)

It's strange because when I do system.out.println with the text I get

I/System.out: Player1

Can someone help me ? My code:

        System.out.println(p1.getText().toString());
        System.out.println(p1.getEditableText().toString());
        j1.setText(p1.getEditableText().toString());
        j2.setText(p2.getEditableText().toString());

p1 and p2 are editText and j1 and j2 are TextView. I don't know if it's the problem but they are in different resource layout.

Phantômaxx
  • 37,901
  • 21
  • 84
  • 115
Raffon
  • 3
  • 1

1 Answers1

1

All your views are needed to be initialized after setting setContentView(R.layout.activity_main)

However in your case you have them in different resource layout.

let's say you want to have views of layout_xyz in activity_main.

in activity_main

<include
   android:id="@+id/xyzView"
   android:layout_width="match_parent"
   android:layout_height="wrap_content"
   layout="@layout/layout_xyz" />

In MainActivity.java

initialize views from layout_xyz

View xyzView = findViewById(R.id.xyzView);

TextView j1FromXyz = xyzView.findViewById(R.id.j1);
TextView j2FromXyz = xyzView.findViewById(R.id.j2);

For more: Re-using layouts with <include/>

shb
  • 5,957
  • 2
  • 15
  • 32