when I try to generate this code, this error:
Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'void android.widget.TextView.setText(java.lang.CharSequence)' on a null object reference.
That is my code:
public class MainActivity extends AppCompatActivity implements View.OnTouchListener{
private Tablero fondo;
int x;
int y;
private boolean activo = true;
int intento = 10;
String numerointentos;
@Override
protected void onCreate(Bundle savedInstanceState) {
requestWindowFeature(Window.FEATURE_NO_TITLE);
getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,WindowManager.LayoutParams.FLAG_FULLSCREEN);
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
LinearLayout linearLayout1 = (LinearLayout) findViewById(R.id.linearLayout1);
TextView Tiradas = (TextView) findViewById(R.id.Intentos) ;
numerointentos = Integer.toString(intento);
Tiradas.setText(numerointentos);
fondo = new Tablero(this);
fondo.setOnTouchListener(this);
linearLayout1.addView(fondo);
fondo.casillas = new Casilla[8][8];
for (int f = 0; f < 8; f++){
for (int c = 0; c < 8; c++){
fondo.casillas[f][c] = new Casilla();
}
}
And this is the .xml code:
<?xml version= "1.01" encoding="utf-8"?>
<LinearLayout
android:id="@+id/linearLayout1"
android:layout_width= "fill_parent"
android:layout_height="fill_parent"
android:orientation="vertical"
xmlns:android="http://schemas.android.com/apk/res/android"
android:weightSum="1">
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="@string/reiniciar"
android:id="@+id/btnReiniciar"
android:onClick="presionado"
android:layout_gravity="center_horizontal" />
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textAppearance="?android:attr/textAppearanceMedium"
android:id="@+id/Intentos"
android:layout_gravity="center_horizontal" />
Obviously there is more code and code and clases, but that is the unique that contains the setText.
And another question. If I want to modify the value of the TextView in another public voids or methods what should I do?
I appreciate your help guys, I searched for anwsers on that web but I can't solve it. I don't know the reason. Thanks!
Move the declaration of the TextView
as the class' property
public class MainActivity extends AppCompatActivity implements View.OnTouchListener {
public TextView Tiradas;
@Override
protected void onCreate(Bundle savedInstanceState) {
setContentView( ... );
Tiradas = (TextView) findViewById(R.id.Intentos);
Tiradas.setText(numerointentos);
}
}
EDIT:
Make sure that you have no other variants of activity_main.xml
file (such as for landscape or bigger screen size). If you have, add the missing views to that layout file.
Because findViewById(int) will return null
if the view is not found in the referenced layout.