应用程序空指针异常

时间:2014-10-02 15:09:49

标签: 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 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>

我的值和styles.xml也有问题。 Maybye是因为我在学校和家里工作,但我仍然不知道问题出在哪里。在styles.xml中,<style name="AppBaseTheme" parent="Theme.AppCompat.Light">行中出现“找不到资源”错误。我该如何解决,在哪里寻找它?当我改变位置时,我也有一个参考R文件的问题。

根据需要,activity_main文件:

<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>

1 个答案:

答案 0 :(得分:5)

您没有指定代码中的哪一行是第98行(您的logcat所说的是NullPointerException发生的位置),但我猜这是您调用br.readLine()的地方,在这里&# 39;为什么:

第一个问题是你在try-catch块中实例化br,并在try-catch之后使用它。如果br = new BufferedReader(new FileReader(fileName));抛出异常,那么您的第一个块将捕获异常,但br仍然不会被实例化。因此,当您的代码进入第二个try-catch块时,只要您尝试使用br,它就会因NullPointerException而崩溃。

第二个问题是你的第一个try-catch块几乎肯定会抛出一个异常,告诉你文件不存在,但由于你忽略了那个例外,你不会看到它。至少,您应该调用fnfe.printStackTrace();,以便在logcat消息中看到异常。

这里的问题是我相当确定您的questions.txt文件不在您期望的位置,并且/或FileReader没有找到您期望的文件。您应该花些时间查看此文件实际驻留的位置以及如何正确访问它。