Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

- java.lang.NullPointerException - setText on null object reference [duplicate]

This is what I'm trying to do for several hours: I've got a MainActivity.java file (listing below) and a fragment_start.xml file with a start button. Tapping the start-button should display the activity_main.xml file with points-/round- and countdown-Textviews. It doesn't work and this is what is happening:

The logcat tells me: PID: 1240 java.lang.NullPointerException: Attempt to invoke virtual method 'void android.widget.TextView.setText(java.lang.CharSequence)' on a null object reference

The emulator displays: Unfortunately, GAME has stopped.

Necessary to mention that I'm rather new in programming?

Thanks for any advice!

import android.app.Activity; import android.os.Bundle; import android.view.View; import android.view.ViewGroup; import android.widget.TextView;   public class MainActivity extends Activity implements View.OnClickListener {  private int points; private int round; private int countdown;  @Override protected void onCreate(Bundle savedInstanceState) {     super.onCreate(savedInstanceState);     setContentView(R.layout.activity_main);     showStartFragment(); }  private void newGame () {     points=0;     round=1;     initRound(); }  private void initRound() {     countdown = 10;     update(); }  private void update () {     fillTextView(R.id.points, Integer.toString(points));     fillTextView(R.id.round, Integer.toString(round));     fillTextView(R.id.countdown, Integer.toString(countdown * 1000)); }  private void fillTextView (int id, String text) {     TextView tv = (TextView) findViewById(id);     tv.setText(text); }  private void showStartFragment() {     ViewGroup container = (ViewGroup) findViewById(R.id.container);     container.removeAllViews();     container.addView(             getLayoutInflater().inflate(R.layout.fragment_start, null) );     container.findViewById(R.id.start).setOnClickListener(this); }  @Override public void onClick(View view) {     if(view.getId() == R.id.start) {         startGame();     } }  public void startGame() {     newGame(); } } 
like image 781
George Avatar asked Jan 12 '15 21:01

George


1 Answers

The problem is the tv.setText(text). The variable tv is probably null and you call the setText method on that null, which you can't. My guess that the problem is on the findViewById method, but it's not here, so I can't tell more, without the code.

like image 152
JustOneJavaDev Avatar answered Sep 20 '22 23:09

JustOneJavaDev