NullPointerException onClick for Android Fragment

时间:2015-08-15 04:00:35

标签: android android-fragments nullpointerexception onclick onclicklistener

我在使用onCLick方法处理片段中的按钮时遇到问题。它抛出NullPointerException,我无法解决这个问题。

IqDbHelper.java代码:

package com.example.scientia;
import java.util.ArrayList;
import java.util.List;
import com.example.scientia.Question;
import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;

public class IqDbHelper extends SQLiteOpenHelper {

    private static final int DATABASE_VERSION = 1;
    // Database Name
    private static final String DATABASE_NAME = "iqQuiz";
    // tasks table name
    private static final String TABLE_QUEST = "quest";
    // tasks Table Columns names
    private static final String KEY_ID = "id";
    private static final String KEY_QUES = "question";
    private static final String KEY_ANSWER = "answer"; //correct option
    private static final String KEY_OPTA= "opta"; //option a
    private static final String KEY_OPTB= "optb"; //option b
    private static final String KEY_OPTC= "optc"; //option c
    private static final String KEY_OPTD= "optd"; //option d
    private SQLiteDatabase dbase;

    public IqDbHelper(Context context) {
        super(context, DATABASE_NAME, null, DATABASE_VERSION);
    }
    @Override
    public void onCreate(SQLiteDatabase db) {
        dbase=db;
        String sql = "CREATE TABLE IF NOT EXISTS " + TABLE_QUEST + " ( "
                + KEY_ID + " INTEGER PRIMARY KEY AUTOINCREMENT, " + KEY_QUES
                + " TEXT, " + KEY_ANSWER+ " TEXT, "+KEY_OPTA +" TEXT, "
                +KEY_OPTB +" TEXT, "+KEY_OPTC+" TEXT, "+KEY_OPTD+" TEXT);";
        db.execSQL(sql);        
        addQuestions();
//      db.close();
    }
    private void addQuestions()
    {
        Question q1=new Question("We need to cut a cake in more than 6 pieces. How many cuts we must make atleast to get this?","2", "3", "4","5", "3");
        this.addQuestion(q1);
        Question q2=new Question("(896)²-(205)² is divisible by 691", "691", "1101", "Both a and b","None","Both a and b");
        this.addQuestion(q2);
        Question q3=new Question("Reindeer: Fawn:: Llama:?","Colt", "Foal","Cria"," Anubhav", "Cria" );
        this.addQuestion(q3);
        Question q4=new Question("How many meters will I be away from my home if I travel 5 metres towards north, take a right and travel 4 metres and travel 5 metres towards south?", "5", "4", "10","15","4");
        this.addQuestion(q4);
        Question q5=new Question("Cake: Bakery:: Beer: X","Distillery","Wine shop","Brewery","XYZ","Brewery");
        this.addQuestion(q5);
    }
    @Override
    public void onUpgrade(SQLiteDatabase db, int oldV, int newV) {
        // Drop older table if existed
        db.execSQL("DROP TABLE IF EXISTS " + TABLE_QUEST);
        // Create tables again
        onCreate(db);
    }
    // Adding new question
    public void addQuestion(Question quest) {
        //SQLiteDatabase db = this.getWritableDatabase();
        ContentValues values = new ContentValues();
        values.put(KEY_QUES, quest.getQUESTION()); 
        values.put(KEY_ANSWER, quest.getANSWER());
        values.put(KEY_OPTA, quest.getOPTA());
        values.put(KEY_OPTB, quest.getOPTB());
        values.put(KEY_OPTC, quest.getOPTC());
        values.put(KEY_OPTD, quest.getOPTD());
        // Inserting Row
        dbase.insert(TABLE_QUEST, null, values);        
    }
    public List<Question> getAllQuestions() {
        List<Question> quesList = new ArrayList<Question>();
        // Select All Query
        String selectQuery = "SELECT  * FROM " + TABLE_QUEST;
        dbase=this.getReadableDatabase();
        Cursor cursor = dbase.rawQuery(selectQuery, null);
        // looping through all rows and adding to list
        if (cursor.moveToFirst()) {
            do {
                Question quest = new Question();
                quest.setID(cursor.getInt(0));
                quest.setQUESTION(cursor.getString(1));
                quest.setANSWER(cursor.getString(2));
                quest.setOPTA(cursor.getString(3));
                quest.setOPTB(cursor.getString(4));
                quest.setOPTC(cursor.getString(5));
                quest.setOPTD(cursor.getString(6));
                quesList.add(quest);
            } while (cursor.moveToNext());
        }
        // return quest list
        return quesList;
    }
    public int rowcount()
    {
        int row=0;
        String selectQuery = "SELECT  * FROM " + TABLE_QUEST;
        SQLiteDatabase db = this.getWritableDatabase();
        Cursor cursor = db.rawQuery(selectQuery, null);
        row=cursor.getCount();
        return row;
    }

}

包含Fragment的IqQuiz.java和一个抛出NullPointerException的按钮编码如下:

package com.example.scientia;

import android.app.Fragment;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import java.util.List;
import android.content.Intent;
import android.util.Log;
import android.widget.Button;
import android.widget.RadioButton;
import android.widget.RadioGroup;
import android.widget.TextView;
import com.example.scientia.IqDbHelper;

public class IqQuiz extends Fragment implements View.OnClickListener{

    List<Question> quesList;
    int score=0;
    int qid=0;
    Question currentQ;
    TextView txtQuestion;
    RadioButton rda, rdb, rdc, rdd;
    Button butNext;


    @Override
    public void onCreate(Bundle savedInstanceState) {
        // TODO Auto-generated method stub
        super.onCreate(savedInstanceState);
    }
    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        // TODO Auto-generated method stub
        IqDbHelper db = new IqDbHelper(getActivity());
        View v=inflater.inflate(R.layout.iqquiz, container, false);
        quesList=db.getAllQuestions();
        currentQ=quesList.get(qid);
        txtQuestion=(TextView)v.findViewById(R.id.textView1);
        rda=(RadioButton)v.findViewById(R.id.radio0);
        rdb=(RadioButton)v.findViewById(R.id.radio1);
        rdc=(RadioButton)v.findViewById(R.id.radio2);
        rdd=(RadioButton)v.findViewById(R.id.radio3);
        butNext=(Button)v.findViewById(R.id.button1);
        setQuestionView();

        butNext.setOnClickListener(this);

        return v;

}

    private void setQuestionView()
{
    txtQuestion.setText(currentQ.getQUESTION());
    rda.setText(currentQ.getOPTA());
    rdb.setText(currentQ.getOPTB());
    rdc.setText(currentQ.getOPTC());
    rdd.setText(currentQ.getOPTD());
    qid++;
}
    @Override
    public void onClick(View v) {
        if(v==butNext){
        RadioGroup grp=(RadioGroup)v.findViewById(R.id.radioGroup1);
        RadioButton answer=(RadioButton)v.findViewById(grp.getCheckedRadioButtonId());          
        Log.d("yourans", currentQ.getANSWER()+" "+answer.getText());
        if(currentQ.getANSWER().equals(answer.getText()))
        {
            score++;
            Log.d("score", "Your score"+score);
        }
        if(qid<5){                  
            currentQ=quesList.get(qid);
            setQuestionView();
        }else{
            Intent intent = new Intent(getActivity(), ResultActivity.class);
            Bundle b = new Bundle();
            b.putInt("score", score); //Your score
            intent.putExtras(b); //Put your score to your next Intent
            startActivity(intent);
//          finish();
        }
    }
    }   
}

没有编译错误。应用程序在按钮单击时崩溃,LogCat显示其点击时抛出NullPointerException。

logcat的:

08-14 23:40:45.486: D/AndroidRuntime(1974): Shutting down VM
08-14 23:40:45.496: W/dalvikvm(1974): threadid=1: thread exiting with uncaught exception (group=0xb0cdeb20)
08-14 23:40:45.496: E/AndroidRuntime(1974): FATAL EXCEPTION: main
08-14 23:40:45.496: E/AndroidRuntime(1974): Process: com.example.scientia, PID: 1974
08-14 23:40:45.496: E/AndroidRuntime(1974): java.lang.NullPointerException
08-14 23:40:45.496: E/AndroidRuntime(1974):     at com.example.scientia.IqQuiz.onClick(IqQuiz.java:67)
08-14 23:40:45.496: E/AndroidRuntime(1974):     at android.view.View.performClick(View.java:4438)
08-14 23:40:45.496: E/AndroidRuntime(1974):     at android.view.View$PerformClick.run(View.java:18422)
08-14 23:40:45.496: E/AndroidRuntime(1974):     at android.os.Handler.handleCallback(Handler.java:733)
08-14 23:40:45.496: E/AndroidRuntime(1974):     at android.os.Handler.dispatchMessage(Handler.java:95)
08-14 23:40:45.496: E/AndroidRuntime(1974):     at android.os.Looper.loop(Looper.java:136)
08-14 23:40:45.496: E/AndroidRuntime(1974):     at android.app.ActivityThread.main(ActivityThread.java:5001)
08-14 23:40:45.496: E/AndroidRuntime(1974):     at java.lang.reflect.Method.invokeNative(Native Method)
08-14 23:40:45.496: E/AndroidRuntime(1974):     at java.lang.reflect.Method.invoke(Method.java:515)
08-14 23:40:45.496: E/AndroidRuntime(1974):     at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:785)
08-14 23:40:45.496: E/AndroidRuntime(1974):     at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:601)
08-14 23:40:45.496: E/AndroidRuntime(1974):     at dalvik.system.NativeStart.main(Native Method)

我尝试过几件事。请帮忙:(

1 个答案:

答案 0 :(得分:0)

无论如何,你的按钮变量为null,因此你在null上调用一个函数。这就是它给你错误的原因。尝试查看logcat并检查代码以查找错误。