我是Android新手。我在运行它时收到此错误(应用程序崩溃)。 我试图通过调用getResources()来访问main.java中的字符串数组。 但是抛出了Resource Not Found Exception。请看下面给出的代码:
import android.os.Bundle;
import android.content.res.Resources;
import android.app.Activity;
import android.view.Menu;
import android.view.ViewGroup;
import android.widget.*;
//import com.packtpub.kitchendroid.R;
public class QuestionActivity extends Activity {
private Button[] buttons;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_question);
initQuestionScreen();
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.question, menu);
return true;
}
private static int getQuestionId(final Resources res,final int index)
{
final String[] questions = res.getStringArray(R.array.questions);
return res.getIdentifier(questions[index],"array","com.packtub.kitchendroid");
}
private int getQuestionIndex()
{
return getIntent().getIntExtra("KitchenDroid.Question", 0);
}
private void initQuestionScreen()
{
TextView question = (TextView)findViewById(R.id.question);
ViewGroup answers = (ViewGroup)findViewById(R.id.answers);
Resources resources1 = getResources();
int questionID = getQuestionId(resources1, getQuestionIndex());
String[] questionData = resources1.getStringArray(questionID);
question.setText(questionData[0]);
int answerCount = questionData.length -1;
buttons = new Button[answerCount];
for(int i=0;i<answerCount;i++)
{
String answer = questionData[i+1];
Button button = new Button(this);
button.setText(answer);
answers.addView(button);
buttons[i]=button;
}
}
}
我的xml如下:
<?xml version="1.0" encoding="utf-8"?>
<resources>
<string name="app_name">Kitchen Droid</string>
<string name="action_settings">Settings</string>
<string name="question">Please wait</string>
<string name="skip">Skip Question</string>
<string name="feedme">Feed Me!..</string>
<string-array name="questions">
<item>vegetarian</item>
<item>size</item>
</string-array>
<string-array name="vegetarian">
<item>Are you a vegeterian?</item>
<item>Yes</item>
<item>No</item>
<item>I\'m a vegetarian</item>
</string-array>
<string-array name="size">
<item>How much do you feel like eating?</item>
<item>A large meal</item>
<item>Just a nice single serving of food</item>
<item>Some finger foods</item>
<item>Just a snack</item>
</string-array>
</resources>
请帮助我解决这个问题。如果问题不合适,可能是因为我对Android完全陌生
答案 0 :(得分:3)
您的包裹名称是否有拼写错误?好像是
res.getIdentifier(questions[index],"array","com.packtub.kitchendroid");
应该是
res.getIdentifier(questions[index],"array","com.packtpub.kitchendroid");
或者,您可以使用:
res.getIdentifier(questions[index], "array", QuestionActivity.this.getPackageName());