Я не уверен, почему я получаю NullPointerException. Метод getQuestion() в настоящее время указывает на жестко закодированную строку для устранения неполадок. Im пытается сгенерировать другую строку перед запуском setContentView(), чтобы избежать необходимости обновлять пользовательский интерфейс.
Сначала я вызываю метод getQuestion()
TextView t=new TextView(this);
t=(TextView)findViewById(R.id.textView4);
try {
//above executes well :) ... problem is below
t.setText(quiz.getQuestion());
} catch (Exception e1) {
// TODO Auto-generated catch block
Toast.makeText(AlarmReceiverActivity.this, "getQuestion() failed", Toast.LENGTH_LONG).show();
e1.printStackTrace();
}
setContentView(R.layout.main);
Это некоторые из моих Question.class:
Question(){
question="null";
answer="null";
try {
newQuestion();
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}//Question constructor
String getQuestion(){
return "This is a question?";
}//get question
вы не можете вызвать t=(TextView)findViewById(R.id.textView4);
перед вызовом setContentView(R.layout.main);
, Сначала вам нужно установить свой макет, а затем findViewById может найти представление из вашего определенного макета
Вызовите метод setContentView()
перед вызовом метода findViewById()
.
Вы должны установить макет содержимого своей деятельности, прежде чем пытаться найти Views, поэтому он дает вам NullPointerException
setContentView(R.layout.main);//should be called before any findViewById()
TextView t=new TextView(this);
t=(TextView)findViewById(R.id.textView4);
try {
//above executes well :) ... problem is below
t.setText(quiz.getQuestion());
} catch (Exception e1) {
// TODO Auto-generated catch block
Toast.makeText(AlarmReceiverActivity.this, "getQuestion() failed", Toast.LENGTH_LONG).show();
e1.printStackTrace();
}
Первый звонок
setContentView(R.layout.main);
а затем позвоните
TextView t = (TextView)findViewById(R.id.textView4);
LogCat
пожалуйста