Hello stack overflow community. i am working on a quiz game and im getting the following error which i think is due to the fact that the textview im trying to create keeps going to null
java.lang.NullPointerException: Attempt to invoke virtual method 'void android.widget.TextView.setTypeface(android.graphics.Typeface)' on a null object reference
at com.practechs.kubetnew28_05.GameActivity.addView(GameActivity.java:83)
at com.practechs.kubetnew28_05.GameActivity.doValidate(GameActivity.java:137)
at com.practechs.kubetnew28_05.GameActivity.access$200(GameActivity.java:20)
at com.practechs.kubetnew28_05.GameActivity$1.onClick(GameActivity.java:104)
at android.view.View.performClick(View.java:7441)
here is my layout file for the game activity
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
android:id="@ id/layoutParent"
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
android:background="@drawable/bgapp"
tools:context=".GameActivity">
<TextView
android:id="@ id/textScreen"
android:layout_marginTop="40dp"
android:layout_gravity="center"
android:textColor="#FFF"
android:textSize="22sp"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="In Fight Battle" />
<LinearLayout
android:layout_marginTop="50dp"
android:layout_gravity="center"
android:background="@drawable/bgquestion"
android:orientation="vertical"
android:gravity="center"
android:layout_width="290dp"
android:layout_height="150dp">
<TextView
android:textAlignment="center"
android:id="@ id/textQuestion"
android:textColor="#332FA2"
android:textSize="26sp"
android:layout_width="220dp"
android:lineSpacingExtra="6dp"
android:layout_height="wrap_content"
android:text="Guess Animals in English language" />
</LinearLayout>
<EditText
android:id="@ id/editText"
android:layout_marginBottom="70dp"
android:padding="10dp"
android:clickable="false"
android:focusable="false"
android:textColor="#332FA2"
android:textSize="32sp"
android:gravity="center"
android:layout_gravity="center"
android:layout_marginTop="70dp"
android:background="@drawable/bgpurple"
android:layout_width="200dp"
android:layout_height="80dp" />
<TextView
android:id="@ id/textTitle"
android:text="Ammo"
android:textSize="24sp"
android:textColor="#FFF"
android:layout_marginRight="28dp"
android:layout_marginLeft="28dp"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginBottom="16dp"
/>
<LinearLayout
android:layout_marginLeft="24dp"
android:layout_marginRight="24dp"
android:orientation="horizontal"
android:layout_width="match_parent"
android:layout_height="wrap_content">
</LinearLayout>
</LinearLayout>
and here is the code for the app.
import android.annotation.SuppressLint;
import android.content.Intent;
import android.graphics.Typeface;
import android.os.Bundle;
import android.view.Gravity;
import android.view.View;
import android.view.animation.Animation;
import android.view.animation.AnimationUtils;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;
import androidx.appcompat.app.AppCompatActivity;
import java.util.Random;
public class GameActivity extends AppCompatActivity {
private int presCounter = 0;
private int maxPresCounter = 4;
private String[] keys = {"R", "I", "B", "D", "X"};
private String textAnswer = "BIRD";
TextView textScreen, textQuestion, textTitle;
Animation smallbigforth;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_game);
smallbigforth = AnimationUtils.loadAnimation(this, R.anim.smallbigforth);
keys = shuffleArray(keys);
for (String key : keys) {
addView(((LinearLayout) findViewById(R.id.layoutParent)), key, ((EditText) findViewById(R.id.editText)));
}
maxPresCounter = 4;
}
private String[] shuffleArray(String[] ar) {
Random rnd = new Random();
for (int i = ar.length - 1; i > 0; i--) {
int index = rnd.nextInt(i 1);
String a = ar[index];
ar[index] = ar[i];
ar[i] = a;
}
return ar;
}
private void addView(LinearLayout viewParent, final String text, final EditText editText) {
LinearLayout.LayoutParams linearLayoutParams = new LinearLayout.LayoutParams(
LinearLayout.LayoutParams.WRAP_CONTENT,
LinearLayout.LayoutParams.WRAP_CONTENT
);
linearLayoutParams.rightMargin = 30;
final TextView textView = new TextView(this);
textView.setLayoutParams(linearLayoutParams);
textView.setBackground(this.getResources().getDrawable(R.drawable.bgpink));
textView.setTextColor(this.getResources().getColor(R.color.colorPurple));
textView.setGravity(Gravity.CENTER);
textView.setText(text);
textView.setClickable(true);
textView.setFocusable(true);
textView.setTextSize(32);
Typeface typeface = Typeface.createFromAsset(getAssets(), "fonts/FredokaOneRegular.ttf");
textQuestion = (TextView) findViewById(R.id.textQuestion);
textScreen = (TextView) findViewById(R.id.textScreen);
textTitle = (TextView) findViewById(R.id.textTitle);
textQuestion.setTypeface(typeface);
textScreen.setTypeface(typeface);
textTitle.setTypeface(typeface);
editText.setTypeface(typeface);
textView.setTypeface(typeface);
textView.setOnClickListener(new View.OnClickListener() {
@SuppressLint("SetTextI18n")
@Override
public void onClick(View v) {
if(presCounter < maxPresCounter) {
if (presCounter == 0)
editText.setText("");
editText.setText(editText.getText().toString() text);
textView.startAnimation(smallbigforth);
textView.animate().alpha(0).setDuration(300);
presCounter ;
if (presCounter == maxPresCounter)
doValidate();
}
}
});
viewParent.addView(textView);
}
private void doValidate() {
presCounter = 0;
EditText editText = findViewById(R.id.editText);
LinearLayout linearLayout = findViewById(R.id.layoutParent);
if(editText.getText().toString().equals(textAnswer)) {
// Toast.makeText(MainActivity.this, "Correct", Toast.LENGTH_SHORT).show();
Intent a = new Intent(GameActivity.this,BossAct.class);
startActivity(a);
editText.setText("");
} else {
Toast.makeText(GameActivity.this, "Wrong", Toast.LENGTH_SHORT).show();
editText.setText("");
}
keys = shuffleArray(keys);
linearLayout.removeAllViews();
for (String key : keys) {
addView(linearLayout, key, editText);
}
}
}
This issue, i think , is caused by the text view setting to null. ive tried almost all answers ive found on stack overflow. pls help
CodePudding user response:
as the Exception states, you are invoking a method on an object which is null. According to the line
at com.practechs.kubetnew28_05.GameActivity.addView(GameActivity.java:83)
the textTitle object seems to be null. But you may check all the objects on which the method setTypeface(typeface) is invoked from line 81 to 85.
The problem thus seems to have nothing to do with Android Fonts, but rather just a null object. Hope this helps!
Kind regards, 403
CodePudding user response:
I checked the code you provided and found that the java.lang.NullPointerException
problem you were experiencing probably did not occur when the GameActivity.java
is opened for first time. That problem pops up when the answer given is wrong.
Do I understand exactly?
If so, then the reason is here:
private void doValidate (){
....
linearLayout.removeAllViews ();
....
}
In above code, you've removed all child views and then you have called
for (String key : keys) {
addView(linearLayout, key, editText);
}
The editText
you have referenced here, that has also been removed.
So, as expected, java.lang.NullPointerException
is coming up here:
textQuestion = (TextView) findViewById(R.id.textQuestion);
textScreen = (TextView) findViewById(R.id.textScreen);
textTitle = (TextView) findViewById(R.id.textTitle);
textQuestion.setTypeface(typeface);
textScreen.setTypeface(typeface);
textTitle.setTypeface(typeface);
editText.setTypeface(typeface);
As textQuestion
, textScreen
, textTitle
and editText
don't exists anymore.
What should be done then?
In fact, the real problem is elsewhere. And that is you have mistakenly named wrong LinearLayout
as R.id.layoutParent
. Just add the below line to last LinearLayout
instead of root LinearLayout
android:id="@ id/layoutParent"
Just like below:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
android:background="@drawable/bgapp"
tools:context=".GameActivity">
<TextView
android:id="@ id/textScreen"
android:layout_marginTop="40dp"
android:layout_gravity="center"
android:textColor="#FFF"
android:textSize="22sp"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="In Fight Battle" />
<LinearLayout
android:layout_marginTop="50dp"
android:layout_gravity="center"
android:background="@drawable/bgquestion"
android:orientation="vertical"
android:gravity="center"
android:layout_width="290dp"
android:layout_height="150dp">
<TextView
android:textAlignment="center"
android:id="@ id/textQuestion"
android:textColor="#332FA2"
android:textSize="26sp"
android:layout_width="220dp"
android:lineSpacingExtra="6dp"
android:layout_height="wrap_content"
android:text="Guess Animals in English language" />
</LinearLayout>
<EditText
android:id="@ id/editText"
android:layout_marginBottom="70dp"
android:padding="10dp"
android:clickable="false"
android:focusable="false"
android:textColor="#332FA2"
android:textSize="32sp"
android:gravity="center"
android:layout_gravity="center"
android:layout_marginTop="70dp"
android:background="@drawable/bgpurple"
android:layout_width="200dp"
android:layout_height="80dp" />
<TextView
android:id="@ id/textTitle"
android:text="Ammo"
android:textSize="24sp"
android:textColor="#FFF"
android:layout_marginRight="28dp"
android:layout_marginLeft="28dp"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginBottom="16dp"
/>
<LinearLayout
android:id="@ id/layoutParent"
android:layout_marginLeft="24dp"
android:layout_marginRight="24dp"
android:orientation="horizontal"
android:layout_width="match_parent"
android:layout_height="wrap_content">
</LinearLayout>
</LinearLayout>
One more thing that you should take care about.
Every time you call addView
, TypeFace
will be generated from asset and will be assigned to textviews again and again.
You should create class wise variables that can be used later.
Your GameActivity.java
should be like below:
import android.annotation.SuppressLint;
import android.content.Intent;
import android.graphics.Typeface;
import android.os.Bundle;
import android.view.Gravity;
import android.view.View;
import android.view.animation.Animation;
import android.view.animation.AnimationUtils;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;
import androidx.appcompat.app.AppCompatActivity;
import java.util.Random;
public class GameActivity extends AppCompatActivity {
private int presCounter = 0;
private int maxPresCounter = 4;
private String[] keys = {"R", "I", "B", "D", "X"};
private String textAnswer = "BIRD";
private TextView textScreen, textQuestion, textTitle;
private Animation smallbigforth;
// Create variables here
private Typeface typeface;
private EditText editText;
private LinearLayout linearLayout;
private LinearLayout.LayoutParams linearLayoutParams;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_game);
//--------------------------------------------------------------------------------------------
// Get typeface from asset
// then assign it to desired views
typeface = Typeface.createFromAsset(getAssets(), "fonts/FredokaOneRegular.ttf");
// find views and save it for later references
textQuestion = findViewById(R.id.textQuestion);
textScreen = findViewById(R.id.textScreen);
textTitle = findViewById(R.id.textTitle);
editText = findViewById(R.id.editText);
linearLayout = findViewById(R.id.layoutParent);
// set typeface of another views
textQuestion.setTypeface(typeface);
textScreen.setTypeface(typeface);
textTitle.setTypeface(typeface);
editText.setTypeface(typeface);
// You should initiate linearLayoutParams here
// it will be used later
linearLayoutParams = new LinearLayout.LayoutParams(
LinearLayout.LayoutParams.WRAP_CONTENT,
LinearLayout.LayoutParams.WRAP_CONTENT,
);
linearLayoutParams.rightMargin = 30;
//--------------------------------------------------------------------------------------------
smallbigforth = AnimationUtils.loadAnimation(this, R.anim.smallbigforth);
keys = shuffleArray(keys);
for (String key : keys) {
addView(linearLayout, key);
}
maxPresCounter = 4;
}
private String[] shuffleArray(String[] ar) {
Random rnd = new Random();
for (int i = ar.length - 1; i > 0; i--) {
int index = rnd.nextInt(i 1);
String a = ar[index];
ar[index] = ar[i];
ar[i] = a;
}
return ar;
}
private void addView(LinearLayout viewParent, final String text) {
final TextView textView = new TextView(this);
textView.setLayoutParams(linearLayoutParams);
textView.setBackground(this.getResources().getDrawable(R.drawable.bgpink));
textView.setTextColor(this.getResources().getColor(R.color.colorPurple));
textView.setGravity(Gravity.CENTER);
textView.setText(text);
textView.setClickable(true);
textView.setFocusable(true);
textView.setTextSize(32);
// set type of newly created textView
textView.setTypeface(typeface);
textView.setOnClickListener(new View.OnClickListener() {
@SuppressLint("SetTextI18n")
@Override
public void onClick(View v) {
if (presCounter < maxPresCounter) {
if (presCounter == 0)
editText.setText("");
editText.setText(editText.getText().toString() text);
textView.startAnimation(smallbigforth);
textView.animate().alpha(0).setDuration(300);
presCounter ;
if (presCounter == maxPresCounter)
doValidate();
}
}
});
viewParent.addView(textView);
}
private void doValidate() {
presCounter = 0;
if (editText.getText().toString().equals(textAnswer)) {
//Toast.makeText(MainActivity.this, "Correct", Toast.LENGTH_SHORT).show();
Intent a = new Intent(GameActivity.this, BossAct.class);
startActivity(a);
editText.setText("");
} else {
Toast.makeText(GameActivity.this, "Wrong", Toast.LENGTH_SHORT).show();
editText.setText("");
}
keys = shuffleArray(keys);
linearLayout.removeAllViews();
for (String key : keys) {
addView(linearLayout, key);
}
}
}
And that' all I know. Hope this will help.