0

I've written such an app (its still in progress...). This is the log:

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

Im quite new to it, but I cannot find what is wrong. Last time I ran it it was all fine. I am mainly concerned whether it reads the file properly. Below the code:

    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);
    }
}

Manifest:

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

I have also a problem with my values and styles.xml. Maybye it is due to the fact, that I am working in school and at home, but still I do not know where is the problem. In styles.xml I have an error "no resource found" in <style name="AppBaseTheme" parent="Theme.AppCompat.Light"> line. How can I fix it, where to look for it? And also I have a problem with reference to the R file when I change places.

And as required, activity_main file:

<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>
user3795517
  • 52
  • 3
  • 8
  • 7
    You need to learn to read stacktraces... What line is `MainActivity.java:98`? Also to catch NPE is usually not a good idea. And please format your code in a readable manner, thanks. – m0skit0 Oct 02 '14 at 15:11
  • Didn't you not forget about manifest file? Please show your code from activity_main – QArea Oct 02 '14 at 15:20

1 Answers1

5

You didn't specify which line in your code is line 98 (which your logcat says is where the NullPointerException occured), but I am going to guess it is where you call br.readLine(), and here's why:

The first problem is that you are instantiating br in a try-catch block, and using it after the try-catch. If br = new BufferedReader(new FileReader(fileName)); throws an exception, then your first block will catch the exception, but br will still not be instantiated. Thus when your code proceeds into the second try-catch block, it will crash with a NullPointerException as soon as you try to use br.

The second problem is that your first try-catch block is almost certainly throwing an exception telling you that the file doesn't exist, but since you are ignoring that exception, you don't see that. At the very least, you should call fnfe.printStackTrace(); so you can see the exception in your logcat messages.

The issue here is that I am fairly certain that your questions.txt file is not where you expect it, and/or FileReader is not looking for the file where you expect it. You should spend some time looking into where this file actually resides and how to properly access it.

Bryan Herbst
  • 66,602
  • 10
  • 133
  • 120
  • Also: the use of the variable "questions" is quite... questionable. You're also catching a NPE in readFile to catch the improper use of questions[n++] but proceed to return the uninitialized questions variable anyway... – DigCamara Oct 02 '14 at 16:36
  • Thank you for your answer. However, I have a question about the file. I've read that it should be in assets. It is a small txt file. And still it throws Null Pointer Exception. What to do with it? – user3795517 Oct 02 '14 at 19:46
  • Yes, the txt file should be in your APK's /assets folder. However, the path you are using (just `questions.txt`) is not correct for that folder. See [this answer](http://stackoverflow.com/a/4789699/1253844) to see how to properly open a file in that directory. – Bryan Herbst Oct 02 '14 at 19:49