I'm getting this error "Attempt to invoke virtual method 'java.lang.String eecs1022.caps.Game.qa()' on a null object reference"
I just want to know why im getting this error and how I can work around it.
The game object is returns a string but for some reason it says its a null object. Here is my main class and my game class.
MAIN:
private Game game;
private String question = "";
private String answer = "";
private int score = 1;
private int qNum = 1;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
ask();
}
public void ask(){
String apple = game.qa();
int indexanswer = apple.indexOf("\n");
answer = apple.substring(indexanswer);
question = apple.substring(0,indexanswer);
((TextView)findViewById(R.id.question)).setText(question);
}
public void onDone (View v){
if (qNum == 10){
finish();
}
String answerinput = ((EditText)findViewById(R.id.answer)).toString();
if (answer.equalsIgnoreCase(answerinput)){
score++;
}
String oldlog = ((TextView)findViewById(R.id.log)).toString();
String a = oldlog + "\n" + "Q# " + qNum + ": " + question + "\n" + "Your answer" + answerinput.toUpperCase() + "\n" + "Correct Answer: " + answer + "\n";
((TextView)findViewById(R.id.log)).setText(a);
qNum++;
String orange = "SCORE = " + score;
String banana = "Q# " + qNum;
((TextView)findViewById(R.id.score)).setText(orange);
((TextView)findViewById(R.id.qNum)).setText(banana);
ask();
}
}
GAME:
public class Game {
public String capitalanswer = "";
public String countryanswer = "";
private CountryDB db;
public Game(){
this.db = new CountryDB();
}
public String qa(){
List<String> countries = db.getCapitals();
int n = countries.size();
int index = (int)( n * Math.random());
String c = countries.get(index);
capitalanswer = c;
System.out.println(capitalanswer);
Map<String, Country> data = db.getData();
Country ref = data.get(c);
countryanswer = ref.toString();
System.out.println(countryanswer);
if (Math.random() < 0.5){
return "What country has the capital " + ref.getCapital() + " ?" + "\n" + ref.getName();
}else{
return "What is the capital of " + ref.getName() + " ?" + "\n" + ref.getCapital();
}
}
}
Any help is appreciated!