Java 应用程序空指针异常
我已经写了这样一个应用程序(仍在进行中…)。 这是日志:Java 应用程序空指针异常,java,android,file-io,Java,Android,File Io,我已经写了这样一个应用程序(仍在进行中…)。 这是日志: 10-02 13:38:18.714: D/AndroidRuntime(637): Shutting down VM 10-02 13:38:18.714: W/dalvikvm(637): threadid=1: thread exiting with uncaught exception (group=0x40a13300) 10-02 13:38:18.734: E/AndroidRuntime(637): FATAL EXCEP
10-02 13:38:18.714: D/AndroidRuntime(637): Shutting down VM
10-02 13:38:18.714: W/dalvikvm(637): threadid=1: thread exiting with uncaught exception (group=0x40a13300)
10-02 13:38:18.734: E/AndroidRuntime(637): FATAL EXCEPTION: main
10-02 13:38:18.734: E/AndroidRuntime(637): java.lang.RuntimeException: Unable to start activity ComponentInfo{com.example.test1/com.example.test1.MainActivity}: java.lang.NullPointerException
10-02 13:38:18.734: E/AndroidRuntime(637): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2059)
10-02 13:38:18.734: E/AndroidRuntime(637): at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2084)
10-02 13:38:18.734: E/AndroidRuntime(637): at android.app.ActivityThread.access$600(ActivityThread.java:130)
10-02 13:38:18.734: E/AndroidRuntime(637): at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1195)
10-02 13:38:18.734: E/AndroidRuntime(637): at android.os.Handler.dispatchMessage(Handler.java:99)
10-02 13:38:18.734: E/AndroidRuntime(637): at android.os.Looper.loop(Looper.java:137)
10-02 13:38:18.734: E/AndroidRuntime(637): at android.app.ActivityThread.main(ActivityThread.java:4745)
10-02 13:38:18.734: E/AndroidRuntime(637): at java.lang.reflect.Method.invokeNative(Native Method)
10-02 13:38:18.734: E/AndroidRuntime(637): at java.lang.reflect.Method.invoke(Method.java:511)
10-02 13:38:18.734: E/AndroidRuntime(637): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:786)
10-02 13:38:18.734: E/AndroidRuntime(637): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:553)
10-02 13:38:18.734: E/AndroidRuntime(637): at dalvik.system.NativeStart.main(Native Method)
10-02 13:38:18.734: E/AndroidRuntime(637): Caused by: java.lang.NullPointerException
10-02 13:38:18.734: E/AndroidRuntime(637): at com.example.test1.MainActivity.readFile(MainActivity.java:98)
10-02 13:38:18.734: E/AndroidRuntime(637): at com.example.test1.MainActivity.onCreate(MainActivity.java:52)
10-02 13:38:18.734: E/AndroidRuntime(637): at android.app.Activity.performCreate(Activity.java:5008)
10-02 13:38:18.734: E/AndroidRuntime(637): at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1079)
10-02 13:38:18.734: E/AndroidRuntime(637): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2023)
10-02 13:38:18.734: E/AndroidRuntime(637): ... 11 more
10-02 13:38:21.984: I/Process(637): Sending signal. PID: 637 SIG: 9
我对它很陌生,但我找不到哪里不对。上次我跑的时候一切都很好。
我主要关心的是它是否能正确读取文件。
代码如下:
public class MainActivity extends ActionBarActivity {
private int currentQuestion;
//private String [] questions2;
private String [] answers;
private Button answerButton;
private Button questionButton;
private TextView questionView;
private TextView answerView;
private EditText answerText;
private Question [] questions;
private Button buttonA;
private Button buttonB;
private Button buttonC;
private Button buttonD;
//private ContextWrapper context;
//AssetManager am = context.getAssets();
//InputStream is = am.open("questions.txt");
String fileName = "questions.txt";
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
try {
questions=readFile(fileName);
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
init();
}
Question[] readFile(String fileName) throws IOException {
String line, content,a,b,c,d,correct;
int id, x = 0;
StringTokenizer st = null;
BufferedReader br = null;
//opens the file to read
try {
br = new BufferedReader(new FileReader(fileName));
}
catch(FileNotFoundException fnfe) {
//JOptionPane.showMessageDialog(null,"There is NOT such a file!");
}
try {
if((line=br.readLine())==null){ // checks if the file is empty
// JOptionPane.showMessageDialog(null,"Data File is empty!");
}
else { // reads the file if not empty
//int size = Integer.parseInt(line);
//array = new Person[size];
}
while((line=br.readLine())!=null) {
st= new StringTokenizer(line, ",");
id = Integer.parseInt(st.nextToken());
content = st.nextToken();
a = st.nextToken();
b = st.nextToken();
c = st.nextToken();
d = st.nextToken();
correct = st.nextToken();
questions[x++] = new Question(id, content, a, b, c, d, correct);
}
}
catch(NullPointerException npe){}
br.close();
return questions;
}
// http://stackoverflow.com/questions/5771366/reading-a-simple-text-file
public void init()
{
//questions = new String[]{"What is the capital of Egypt?","What class are you in right now?"};
//answers = new String[]{"Cairo","IST380"};
//currentQuestion = -1;
// TextView ecie = (TextView)findViewById(R.id.QuestionTextView);
answerButton = (Button)findViewById(R.id.AnswerButton);
questionButton = (Button)findViewById(R.id.QuestionButton);
questionView = (TextView)findViewById(R.id.QuestionTextView);
answerView = (TextView) findViewById(R.id.AnswerTextView);
answerText = (EditText) findViewById(R.id.AnswerText);
buttonA = (Button)findViewById(R.id.buttonA);
buttonB = (Button)findViewById(R.id.buttonB);
buttonC = (Button)findViewById(R.id.buttonC);
buttonD = (Button)findViewById(R.id.buttonD);
//String pecie = questions[0].getContent();
//ecie.setText(pecie);
answerButton.setOnClickListener(new OnClickListener()
{
public void onClick(View v) {
checkAnswer();
}});
questionButton.setOnClickListener(new OnClickListener(){
@Override
public void onClick(View v) {
showQuestion();
}});
}
/*
* This method * 1: increment currentQuestion index
* 2: check if it is equal to the size of the array and rest
if necessary
* 3: display the question at currentQuestion index in
question view
* 4: Empty answer view
*/
public void showQuestion()
{
currentQuestion++;
if(currentQuestion == questions.length)
currentQuestion =0;
questionView.setText(/*questions[currentQuestion]*/questions[currentQuestion].getContent());
answerView.setText("");
answerText.setText("");
}
/*
* This method return true if the answer equals to correct
answer
* (Ignoring case)
*/
public boolean isCorrect(String answer)
{
return (answer.equalsIgnoreCase(questions[currentQuestion].getCorrect()));
}
/* this method :
* 1: Read the text ( answer) from the answerTextEdit
* 2: call the isCorrect method
* 3: display the appropriate message.
*/
public void checkRight()
{
// String right
}
public void checkAnswer()
{
String answer = questions[currentQuestion].getCorrect();
if(isCorrect(answer))
answerView.setText("You're right!");
else
answerView.setText("Sorry, the correct answer is "+answers[currentQuestion]);
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
}
舱单:
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.example.test1"
android:versionCode="1"
android:versionName="1.0" >
<uses-sdk
android:minSdkVersion="8"
android:targetSdkVersion="21" />
<application
android:allowBackup="true"
android:icon="@drawable/ic_launcher"
android:label="@string/app_name"
android:theme="@style/AppTheme" >
<activity
android:name=".MainActivity"
android:label="@string/app_name" >
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
</application>
</manifest>
我的values和styles.xml也有问题。也许是因为我在学校和家里工作,但我仍然不知道问题出在哪里。在styles.xml中,我在
行中有一个错误“找不到资源”。我如何修理它,在哪里找它?而且,当我改变位置时,我对R文件的引用也有问题
根据需要,活动_主文件:
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:paddingBottom="@dimen/activity_vertical_margin"
android:paddingLeft="@dimen/activity_horizontal_margin"
android:paddingRight="@dimen/activity_horizontal_margin"
android:paddingTop="@dimen/activity_vertical_margin"
tools:context="com.example.test1.MainActivity"
android:orientation="vertical"
android:background="#ff8400" >
<TextView
android:id="@+id/QuestionTextView"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="@string/hello_world" />
<EditText
android:id="@+id/AnswerText"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentLeft="true"
android:layout_alignParentRight="true"
android:layout_below="@+id/QuestionTextView"
android:ems="10" >
<requestFocus />
</EditText>
<Button
android:id="@+id/QuestionButton"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_alignLeft="@+id/AnswerText"
android:layout_below="@+id/AnswerText"
android:text="Show Next Question" />
<Button
android:id="@+id/AnswerButton"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_alignLeft="@+id/AnswerTextView"
android:layout_below="@+id/AnswerTextView"
android:layout_marginTop="18dp"
android:text="Check Answer" />
<EditText
android:id="@+id/AnswerTextView"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_alignLeft="@+id/QuestionButton"
android:layout_below="@+id/QuestionButton"
android:layout_marginTop="18dp"
android:ems="10" />
<Button
android:id="@+id/buttonA"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignLeft="@+id/AnswerButton"
android:layout_below="@+id/AnswerButton"
android:text="A" />
<Button
android:id="@+id/buttonB"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="@+id/AnswerButton"
android:layout_marginLeft="22dp"
android:layout_toRightOf="@+id/buttonA"
android:text="B" />
<Button
android:id="@+id/buttonC"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignLeft="@+id/buttonA"
android:layout_below="@+id/buttonA"
android:layout_marginTop="36dp"
android:text="C" />
<Button
android:id="@+id/buttonD"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignBaseline="@+id/buttonC"
android:layout_alignBottom="@+id/buttonC"
android:layout_alignLeft="@+id/buttonB"
android:text="D" />
</RelativeLayout>
您没有指定代码中的哪一行是第98行(您的日志猫说这是发生NullPointerException的地方),但我猜这是您调用
br.readLine()
的地方,原因如下:
第一个问题是,您正在try-catch块中实例化br
,并在try-catch之后使用它。如果br=new BufferedReader(new FileReader(fileName))
抛出异常,然后您的第一个块将捕获异常,但br
仍不会被实例化。因此,当您的代码进入第二个try-catch块时,只要您尝试使用br
,它就会因NullPointerException而崩溃
第二个问题是,您的第一个try-catch块几乎肯定会抛出一个异常,告诉您该文件不存在,但由于您忽略了该异常,所以您看不到该异常。至少,您应该调用fnfe.printStackTrace()代码>以便您可以在logcat消息中看到异常
这里的问题是,我相当确定您的questions.txt
文件不是您期望的文件,并且/或者FileReader
没有在您期望的地方查找文件。您应该花一些时间研究此文件实际驻留的位置以及如何正确访问它。您没有指定代码中的哪一行是第98行(您的日志猫说这是发生NullPointerException的地方),但我猜这是您调用br.readLine()
的地方,原因如下:
第一个问题是,您正在try-catch块中实例化br
,并在try-catch之后使用它。如果br=new BufferedReader(new FileReader(fileName))
抛出异常,然后您的第一个块将捕获异常,但br
仍不会被实例化。因此,当您的代码进入第二个try-catch块时,只要您尝试使用br
,它就会因NullPointerException而崩溃
第二个问题是,您的第一个try-catch块几乎肯定会抛出一个异常,告诉您该文件不存在,但由于您忽略了该异常,所以您看不到该异常。至少,您应该调用fnfe.printStackTrace()代码>以便您可以在logcat消息中看到异常
这里的问题是,我相当确定您的questions.txt
文件不是您期望的文件,并且/或者FileReader
没有在您期望的地方查找文件。您应该花一些时间查看此文件的实际位置以及如何正确访问它。您需要学习读取stacktraces。。。哪一行是MainActivity.java:98
?此外,捕捉NPE通常不是一个好主意。请以可读的方式格式化您的代码,谢谢。难道您没有忘记清单文件吗?请显示活动_main中的代码。您需要学习阅读stacktraces。。。哪一行是MainActivity.java:98
?此外,捕捉NPE通常不是一个好主意。请以可读的方式格式化您的代码,谢谢。难道您没有忘记清单文件吗?请展示活动_main中的代码。另外:变量“questions”的使用非常。。。有问题。您还在readFile中捕获了一个NPE,以捕获问题[n++]的不当使用,但仍然继续返回未初始化的questions变量…谢谢您的回答。然而,我有一个关于文件的问题。我读过,它应该在资产中。这是一个小的txt文件。它仍然抛出空指针异常。怎么办?是的,txt文件应该在APK的/assets文件夹中。但是,您使用的路径(仅为questions.txt
)对于该文件夹不正确。请参阅以了解如何正确打开该目录中的文件。另外:变量“questions”的使用非常。。。有问题。您还在readFile中捕获了一个NPE,以捕获问题[n++]的不当使用,但仍然继续返回未初始化的questions变量…谢谢您的回答。然而,我有一个关于文件的问题。我读过,它应该在资产中。这是一个小的txt文件。它仍然抛出空指针异常。怎么办?是的,txt文件应该在APK的/assets文件夹中。但是,您使用的路径(仅为questions.txt
)对于该文件夹不正确。请参阅以了解如何正确打开该目录中的文件。