Android :: SQLIte Db不要插入数据

时间:2015-06-18 11:50:08

标签: android database sqlite

我有问题!

我是一个测验应用程序,几乎没有问题从代码生成的问题,但我创建了一个Activity,我可以在运行程序的SQLite Db中向其他人提出一些问题。

我写了一个插入代码,但是当我加载SaveDataActivity时,填写表单,并按下Save按钮,程序崩溃了。

我不知道如何修复我的代码,我厌倦了许多技巧。

这是我的活动代码:

package com.example.jvstgs;

import android.support.v7.app.ActionBarActivity;
import android.text.TextUtils;
import android.content.Intent;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;

public class SaveDataActivity extends ActionBarActivity {

    DbHelper dbase;
    EditText kerdes, valaszA, valaszB, valaszC, valaszD, helyesValasz;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_save_data);

        kerdes = (EditText) findViewById(R.id.editText5);
        valaszA = (EditText) findViewById(R.id.editText1);
        valaszB = (EditText) findViewById(R.id.editText2);
        valaszC = (EditText) findViewById(R.id.editText3);
        valaszD = (EditText) findViewById(R.id.editText4);
        helyesValasz = (EditText) findViewById(R.id.editText6);
        openDb();


        Button button = (Button) findViewById(R.id.button1);
        button.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View v) {
                // TODO Auto-generated method stub
                Intent intent = new Intent(SaveDataActivity.this, ResultActivity.class);
                startActivity(intent);      
                finish();
            }
        });

        Button button2 = (Button) findViewById(R.id.Button01);
        button2.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View v) {
                // TODO Auto-generated method stub
                Intent intent = new Intent(SaveDataActivity.this, ResultActivity.class);
                startActivity(intent);      
                finish();
            }
        });
    }



    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(R.menu.save_data, menu);
        return true;
    }

    private void openDb()
    {
        dbase = new DbHelper(this);
        dbase.open();
    }

    public void onClick_mentes(View v){
        if (!TextUtils.isEmpty(kerdes.getText().toString())){
            dbase.insertRow(null, kerdes.getText().toString(), valaszA.getText().toString()
                    , valaszB.getText().toString(), valaszC.getText().toString()
                    , valaszD.getText().toString());
        }
    }

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

...和我的DbHelper,在哪里控制Db:

package com.example.jvstgs;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.SQLException;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
import android.widget.EditText;
public class DbHelper extends SQLiteOpenHelper {
    private static final int DATABASE_VERSION = 1;
    // Database Name
    private static final String DATABASE_NAME = "triviaQuiz";
    // 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"; 
    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 DbHelper(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("Mire jó a UPS?"
            ,"Vészenegergiaforrás", "Hálózat típus", "TV-netes rendszer","Csatlakozó", "Vészenegergiaforrás");
        this.addQuestion(q1);

        Question q2=new Question("Merevlemezen az adatok ... helyezkednek el. " 
            , "sugárirányban", "fentről lefelé, függőlegesen", "koncentrikus körön", "spirális körön", "koncentrikus körön");
        this.addQuestion(q2);

        Question q3=new Question("Mi a VGA kártya teljes neve?"
            ,"Video Games Adapter", "Video Graphic Array","Video Graphic Adapter","Video Gambling Automat", "Video Graphic Array");
        this.addQuestion(q3);

        Question q4=new Question("Melyik a kakkuktojás?"
            ,"Bigtorony", "Slimház", "Babyház","Miditorony", "Bigtorony");
        this.addQuestion(q4);

        Question q5=new Question("Melyik nem interpretált nyelv" +
            " a felsoroltak közül?","Ruby","BASIC","Perl","Python","BASIC");
        this.addQuestion(q5);

        Question q6=new Question("Mennyivel egyenlő 1 petabyte?" 
            ,"100MB","1000TB","1024TB","1024GB","1024TB");
        this.addQuestion(q6);

        Question q7=new Question("Melyik operációs rendszer rendelkezett először aero kinézettel?"
            ,"Linux Mint","Windows Vista","Mac OS-X 10.2","Windows 7","Windows Vista");
        this.addQuestion(q7);

        Question q8=new Question("Hogy hívták az első kompletten legyártott PC-t?"
            ,"Z71","IBM PC XT","Commodore 64","Apple II","Apple II");
        this.addQuestion(q8);

        Question q9=new Question("Minek a mértékegysége a baud?"
            ,"Adatátvitel sebesség","Busz sebesség","A nyomtató képfelbontása","Az adattípusú fájl mérete","Adatátvitel sebesség");
        this.addQuestion(q9);

        Question q10=new Question("Mekkora az XT busz adatszélessége?"
            ,"8 bit","32 bit","64 bit","16 bit","8 bit");
        this.addQuestion(q10);

    }
    @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 + " ORDER BY RANDOM()";
        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 getrowCount() {
        String countQuery = "SELECT  * FROM " + TABLE_QUEST;
        SQLiteDatabase db = this.getReadableDatabase();
        Cursor cursor = db.rawQuery(countQuery, null);
        int cnt = cursor.getCount();
        cursor.close();
        return cnt;
    }
    public DbHelper open() {
        SQLiteDatabase db = this.getWritableDatabase();
        return this;
    }

    public void close(){
        this.close();
    }
    public long insertRow(String kerdes, String valaszA, String valaszB
            , String valaszC, String valaszD, String helyesValasz) {
        ContentValues initialValues = new ContentValues();
        initialValues.put(KEY_QUES, kerdes);
        initialValues.put(KEY_OPTA, valaszA);
        initialValues.put(KEY_OPTB, valaszB);
        initialValues.put(KEY_OPTC, valaszC);
        initialValues.put(KEY_OPTD, valaszD);
        initialValues.put(KEY_ANSWER, helyesValasz);

        return dbase.insert(TABLE_QUEST, null, initialValues);

    }



}

onClick_mentes是一个onclick方法,我通过insertRow将数据提供给DbHelper,但是在我测试时崩溃了。

我错在哪里&amp;&amp;如何解决? :/

//// //// EDITED 我的LogCat:

06-18 11:38:46.964: E/AndroidRuntime(615): FATAL EXCEPTION: main
06-18 11:38:46.964: E/AndroidRuntime(615): java.lang.RuntimeException: Unable to start activity ComponentInfo{com.example.jvstgs/com.example.jvstgs.ResultActivity}: java.lang.NullPointerException
06-18 11:38:46.964: E/AndroidRuntime(615):  at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2059)
06-18 11:38:46.964: E/AndroidRuntime(615):  at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2084)
06-18 11:38:46.964: E/AndroidRuntime(615):  at android.app.ActivityThread.access$600(ActivityThread.java:130)
06-18 11:38:46.964: E/AndroidRuntime(615):  at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1195)
06-18 11:38:46.964: E/AndroidRuntime(615):  at android.os.Handler.dispatchMessage(Handler.java:99)
06-18 11:38:46.964: E/AndroidRuntime(615):  at android.os.Looper.loop(Looper.java:137)
06-18 11:38:46.964: E/AndroidRuntime(615):  at android.app.ActivityThread.main(ActivityThread.java:4745)
06-18 11:38:46.964: E/AndroidRuntime(615):  at java.lang.reflect.Method.invokeNative(Native Method)
06-18 11:38:46.964: E/AndroidRuntime(615):  at java.lang.reflect.Method.invoke(Method.java:511)
06-18 11:38:46.964: E/AndroidRuntime(615):  at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:786)
06-18 11:38:46.964: E/AndroidRuntime(615):  at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:553)
06-18 11:38:46.964: E/AndroidRuntime(615):  at dalvik.system.NativeStart.main(Native Method)
06-18 11:38:46.964: E/AndroidRuntime(615): Caused by: java.lang.NullPointerException
06-18 11:38:46.964: E/AndroidRuntime(615):  at com.example.jvstgs.ResultActivity.onCreate(ResultActivity.java:25)
06-18 11:38:46.964: E/AndroidRuntime(615):  at android.app.Activity.performCreate(Activity.java:5008)
06-18 11:38:46.964: E/AndroidRuntime(615):  at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1079)
06-18 11:38:46.964: E/AndroidRuntime(615):  at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2023)
06-18 11:38:46.964: E/AndroidRuntime(615):  ... 11 more

///已编辑2 /// 我的ResultActivity:

package com.example.jvstgs;
import android.os.Bundle;
import android.app.Activity;
import android.content.Intent;
import android.view.Menu;
import android.widget.Button;
import android.widget.RatingBar;
import android.widget.TextView;
import android.view.View;
import android.view.View.OnClickListener;

public class ResultActivity extends Activity {
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_result);
        //get rating bar object
        RatingBar bar=(RatingBar)findViewById(R.id.ratingBar1); 
        bar.setNumStars(5);
        bar.setStepSize(0.5f);
        //get text view
        TextView t=(TextView)findViewById(R.id.textResult);
        //get score
        Bundle b = getIntent().getExtras();
        int score= b.getInt("score");
        //display score
        bar.setRating(score);
        switch (score)
        {
        case 1:
        case 2: t.setText("Horrible!!!!");
        break;
        case 3:
        case 4:t.setText("So so....");
        break;
        case 5:t.setText("It's a nice try!");
        break;
        }
        /// Try again the game bring to the first Activity
        Button button1 = (Button) findViewById(R.id.button1);
        button1.setOnClickListener(new OnClickListener() {

            @Override
            public void onClick(View v) {
                // TODO Auto-generated method stub
                Intent intent = new Intent(ResultActivity.this, QuizActivity.class);
                startActivity(intent);      
                finish();
            }
        });
        // Its bring to the SaveDataActivity where Somebody can put the questions to the Db.
        Button button2 = (Button) findViewById(R.id.button2);
        button2.setOnClickListener(new OnClickListener() {

            @Override
            public void onClick(View v) {
                // TODO Auto-generated method stub
                Intent intent = new Intent(ResultActivity.this, SaveDataActivity.class);
                startActivity(intent);      
                finish();
            }
        });

        // Exit from the application
        Button button4 = (Button) findViewById(R.id.button4);
        button4.setOnClickListener(new OnClickListener() {

            @Override
            public void onClick(View v) {
                // TODO Auto-generated method stub
                finish();
                System.exit(0);
            }
        });


    }
    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(R.menu.result, menu);
        return true;
    }
}

感谢您的帮助!

2 个答案:

答案 0 :(得分:0)

你的b是空的。你并没有把任何意图放在意图中,而是你从意图中获取。

Put&#34;得分&#34;在SaveDataActivity中意图然后从ResultActivity中的intent中获取。

How to use putExtra() and getExtra() for string data

答案 1 :(得分:0)

在调用意图时

    Intent intent = new Intent(SaveDataActivity.this,ResultActivity.class);     intent.putExtra(&#34;得分&#34;,putYourScorehere);     startActivity(意向);