调用类方法的空指针异常

时间:2016-01-15 04:25:27

标签: android class parse-platform nullpointerexception

我正在使用解析云数据库为Android创建一个测验应用程序。我在我的一个活动中得到一个空指针异常。这是我的代码..pls help..i还包括我的日志......如果需要,我会提供进一步的细节

import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.view.KeyEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.RadioGroup;
import android.widget.TextView;
import android.widget.Toast;



 public class QuestionActivity extends Activity implements OnClickListener{

private Question currentQ;
private Exam currentExam;


@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_question);

    currentExam = ((MyApp)getApplication()).getCurrentExam(); //app crashes here
    currentQ = currentExam.getNextQuestion();

    Button nextBtn = (Button) findViewById(R.id.nextBtn);
    nextBtn.setOnClickListener(this);


    setQuestions();

}
private void setQuestions() {
    //set the question text from current question
    String question = currentQ.getQuestion() + "?";
    TextView qText = (TextView) findViewById(R.id.question);
    qText.setText(question);

    //set the available options
    TextView option1 = (TextView) findViewById(R.id.answer1);
    option1.setText( currentQ.getOptionOne() );

    TextView option2 = (TextView) findViewById(R.id.answer2);
    option2.setText( currentQ.getOptionTwo() );

    TextView option3 = (TextView) findViewById(R.id.answer3);
    option3.setText( currentQ.getOptionThree() );

    TextView option4 = (TextView) findViewById(R.id.answer4);
    option4.setText( currentQ.getOptionFour() );
}


@Override public void onClick(View v) {
    //validate a checkbox has been selected
    if (!checkAnswer()) return;

    // check if end of game
    if (currentExam.isExamOver()){
        Toast.makeText(getApplicationContext(),"finish",Toast.LENGTH_LONG).show();
        finish();
    } else {
        Intent i = new Intent(this, QuestionActivity.class);
        startActivity(i);
        finish();
    }
}


@Override public boolean onKeyDown(int keyCode, KeyEvent event) {
    switch (keyCode) {
        case KeyEvent.KEYCODE_BACK : return true;
    }
    return super.onKeyDown(keyCode, event);
}



private boolean checkAnswer() {
    RadioGroup options = (RadioGroup)findViewById(R.id.group1);
    Integer selected = options.getCheckedRadioButtonId();
    if ( selected < 0){
        return false;
    } else {
        if (currentQ.getCorrectAnswer() == selected+1 ) {
            currentExam.incrementRightAnswers();
        } else {
            currentExam.incrementWrongAnswers();
        }
        return true;
    }
}

}

继承我的日志

01-15 09:46:04.508 2909-2909/me.ashif.preparation E/AndroidRuntime:    FATAL EXCEPTION: main
 01-15 09:46:04.508 2909-2909/me.ashif.preparation E/AndroidRuntime:      Process: me.ashif.preparation, PID: 2909
 01-15 09:46:04.508 2909-2909/me.ashif.preparation E/AndroidRuntime:     java.lang.RuntimeException: Unable to start activity      ComponentInfo{me.ashif.preparation/me.ashif.preparation.QuestionActivity}: java.lang.NullPointerException: Attempt to invoke virtual method    'me.ashif.preparation.Exam me.ashif.preparation.Exam.getCurrentExam()' on   a null object reference
   01-15 09:46:04.508 2909-2909/me.ashif.preparation E/AndroidRuntime:     at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2416)
   01-15 09:46:04.508 2909-2909/me.ashif.preparation E/AndroidRuntime:     at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2476)
    01-15 09:46:04.508 2909-2909/me.ashif.preparation E/AndroidRuntime:     at android.app.ActivityThread.- wrap11(ActivityThread.java)
   01-15 09:46:04.508 2909-2909/me.ashif.preparation E/AndroidRuntime:     at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1344)
   01-15 09:46:04.508 2909-2909/me.ashif.preparation E/AndroidRuntime:     at android.os.Handler.dispatchMessage(Handler.java:102)
   01-15 09:46:04.508 2909-2909/me.ashif.preparation E/AndroidRuntime:     at android.os.Looper.loop(Looper.java:148)
   01-15 09:46:04.508 2909-2909/me.ashif.preparation E/AndroidRuntime:     at android.app.ActivityThread.main(ActivityThread.java:5417)
   01-15 09:46:04.508 2909-2909/me.ashif.preparation E/AndroidRuntime:     at java.lang.reflect.Method.invoke(Native Method)
   01-15 09:46:04.508 2909-2909/me.ashif.preparation E/AndroidRuntime:     at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:726)
    01-15 09:46:04.508 2909-2909/me.ashif.preparation E/AndroidRuntime:     at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:616)
  01-15 09:46:04.508 2909-2909/me.ashif.preparation E/AndroidRuntime:  Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'me.ashif.preparation.Exam me.ashif.preparation.Exam.getCurrentExam()' on a null object reference
   01-15 09:46:04.508 2909-2909/me.ashif.preparation E/AndroidRuntime:     at me.ashif.preparation.QuestionActivity.onCreate(QuestionActivity.java:35)
  01-15 09:46:04.508 2909-2909/me.ashif.preparation E/AndroidRuntime:     at android.app.Activity.performCreate(Activity.java:6237)

我的app类代码

import android.app.Application;
import android.widget.Toast;

 import com.parse.FindCallback;
 import com.parse.Parse;
  import com.parse.ParseACL;
  import com.parse.ParseException;
 import com.parse.ParseObject;
import com.parse.ParseQuery;

 import java.util.List;

/**
* Created by ashif on 15/1/16.
 */
 public class MyApp extends Application {

private Exam currentExam;
public void setCurrentExam(Exam currentGame) {
    this.currentExam = currentExam;
}
public Exam getCurrentExam() {
    return currentExam;
}


@Override
public void onCreate() {
    super.onCreate();

    ParseObject.registerSubclass(Question.class);


    Parse.enableLocalDatastore(this);


    Parse.initialize(this, "NsvQwd2jpTunUlpsb4SrkzzKOXoPYwiWEOBgg9Ly", "HdSfQm9uDNyCyzxQBlH6jPmy6nvbmxxttuCtAVRz");

    ParseACL defaultACL = new ParseACL();


    defaultACL.setPublicReadAccess(true);
    ParseACL.setDefaultACL(defaultACL, true);
    ParseQuery<Question> query = ParseQuery.getQuery("Question");
    final Application app = this;
    query.findInBackground(new FindCallback<Question>() {
        @Override public void done(List<Question> questions, ParseException e) {
            if (e == null) {
                //We have updated questions from the cloud so we will cache them all
                ParseObject.unpinAllInBackground("QUESTIONS");
                ParseObject.pinAllInBackground("QUESTIONS", questions);
            } else {
                //alert the user that unable to fetch questions -this should be more robust in production apps
                Toast.makeText(app,
                        "Error updating questions - please make sure you have internet connection",
                        Toast.LENGTH_LONG).show();
            }
        }
    });
}

}

检查我的清单

   <?xml version="1.0" encoding="utf-8"?>
  <manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="me.ashif.preparation" >
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission    android:name="android.permission.ACCESS_NETWORK_STATE" />
<application
    android:allowBackup="true"
    android:icon="@mipmap/ic_launcher"
    android:label="@string/app_name"
    android:name=".MyApp"
    android:supportsRtl="true"
    android:theme="@style/AppTheme" >
    <activity
        android:name=".MainActivity"
        android:label="@string/app_name"
        android:theme="@style/AppTheme.NoActionBar" >
        <intent-filter>
            <action android:name="android.intent.action.MAIN" />

            <category android:name="android.intent.category.LAUNCHER" />
        </intent-filter>
    </activity>
    <activity
        android:name="me.ashif.preparation.QuestionActivity"
        android:label="@string/app_name"
        />
    <meta-data
        android:name="com.parse.APPLICATION_ID"
        android:value="NsvQwd2jpTunUlpsb4SrkzzKOXoPYwiWEOBgg9Ly" />
    <meta-data
        android:name="com.parse.CLIENT_KEY"
        android:value="HdSfQm9uDNyCyzxQBlH6jPmy6nvbmxxttuCtAVRz" />
</application>

4 个答案:

答案 0 :(得分:2)

根据日志,NullPointerException位于onCreate函数下方的{}}位置

currentExam = ((MyApp)getApplication()).getCurrentExam();

您是否在清单文件的申请标记中声明了MyApp

答案 1 :(得分:2)

与日志一样:

  

尝试调用虚方法'me.ashif.preparation.Exam   关于空对象引用的me.ashif.preparation.Exam.getCurrentExam()'

表示可能忘记在MyApp AndroidManifest.xmlapplication tag文件中添加android:name课程,其中<application android:label="@string/app_name" android:name=".MyApp"> .... </application> 属性为:

MyApp

同样在currentExamExam中,currentQ = currentExam.getNextQuestion(); 类的对象不会在任何地方初始化,所以请确保它已初始化:

NPE

行将抛出<ul> <li ng-repeat="album in albums"> <input type="checkbox" ng-model="album.selected" value={{album.name}} ng-click="save()"/> {{album.name}} </li>

答案 2 :(得分:0)

确保您在AndroidManifest中定义了MyApp:

<application
        android:name="MyApp"

答案 3 :(得分:0)

在清单中声明应用程序标记,它将解决问题

     <application
    android:name="me.ashif.preparation.MyApp"