数据库是在模拟器上创建的,但不是在设备上创建的

时间:2018-08-24 18:13:00

标签: android

在下面的课程中,我创建了创建和操作数据库的方法

package com.ashish.testquiz2;

import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
import android.util.Log;


public class QuestionAdapter {

static final String KEY_ID = "id";
static final String KEY_OPTION1 = "option1";
static final String KEY_OPTION2 = "option2";
static final String KEY_OPTION3 = "option3";
static final String KEY_OPTION4 = "option4";
static final String KEY_QUE = "question";
static final String KEY_ANS = "answer";
static final String TAG = "DBAdapter";

static final String DATABASE_NAME = "quizdb2";
static final String DATABASE_TABLE = "quiztb2";
static final int DATABASE_VERSION = 1;

static final String DATABASE_CREATE = "create table " + DATABASE_TABLE + " 
(" + KEY_ID + " integer(10) not null primary key, " + KEY_QUE + " 
varchar(150) not null, " + KEY_OPTION1 + " varchar(50) not null, " + 
KEY_OPTION2 + " varchar(50) not null, " + KEY_OPTION3 + " varchar(50) not 
null, " + KEY_OPTION4 + " varchar(50) not null," + KEY_ANS + " varchar(50) 
not null);";

final Context context;

DatabaseHelper DBHelper;
SQLiteDatabase db;

public QuestionAdapter(Context ctx){
    this.context = ctx;
    DBHelper = new DatabaseHelper(context);

}

public static class DatabaseHelper extends SQLiteOpenHelper{

    public DatabaseHelper(Context context) {
        super(context, DATABASE_NAME, null, DATABASE_VERSION);
    }

    @Override
    public void onCreate(SQLiteDatabase db) {
    try {
        //db.execSQL("drop table if already exists " + DATABASE_TABLE);
        //db.execSQL(DATABASE_CREATE);
    } catch (Exception e) {
        e.printStackTrace();

    }

    }

    @Override
    public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) 
{
        Log.w(TAG, "upgrading database from version " + oldVersion + " to 
version " + newVersion + " which will destroy all old data");
        //db.execSQL("drop table if already exists " + DATABASE_TABLE);
        onCreate(db);

    }
}

//opens the database
public QuestionAdapter open() throws Exception{
    db = DBHelper.getWritableDatabase();
    return this;
}

//closes the database
public void close() {
    DBHelper.close();
}

//insert into database
public void insertitem() {
    db = DBHelper.getWritableDatabase();
    db.execSQL("drop table " + DATABASE_TABLE);
    db.execSQL(DATABASE_CREATE);

    String sql1 = "insert into " + DATABASE_TABLE + " (" + KEY_ID + " , " + 
KEY_QUE + " , " + KEY_OPTION1 + " , " + KEY_OPTION2 + " , " + KEY_OPTION3 + 
" , " + KEY_OPTION4 + " , " + KEY_ANS + 
            " ) values(1,'Nobel prize is awarded for which of the following 
disciplines:', 'Literature,Peace and Economics','Medicine and 
Physiology','Chemistry and Physics','All of the above','All of the 
above');";

    String sql2 = "insert into " + DATABASE_TABLE + " (" + KEY_ID + " , " + 
KEY_QUE + " , " + KEY_OPTION1 + " , " + KEY_OPTION2 + " , " + KEY_OPTION3 + 
" , " + KEY_OPTION4 + " , " + KEY_ANS + 
            " ) values(2,'Galileo was an astronomer who:', 'developed the 
telescope','discovered four satellites of Jupiter','discovered that the 
movement of pendulum produces a regular time interval','All of the 
above','discovered four satellites of Jupiter');";

    String sql3 = "insert into " + DATABASE_TABLE + " (" + KEY_ID + " , " + 
KEY_QUE + " , " + KEY_OPTION1 + " , " + KEY_OPTION2 + " , " + KEY_OPTION3 + 
" , " + KEY_OPTION4 + " , " + KEY_ANS + 
            " ) values(3,'Who is the father of geometry:', 
'Aristotle','Euclid','Pythagoras','Kepler','Euclid');";

    String sql4 = "insert into " + DATABASE_TABLE + " (" + KEY_ID + " , " + 
KEY_QUE + " , " + KEY_OPTION1 + " , " + KEY_OPTION2 + " , " + KEY_OPTION3 + 
" , " + KEY_OPTION4 + " , " + KEY_ANS + 
            " ) values(4,'Who is popularly called as Iron Man of India:', 
'Subhash Chandra Bose','Sardar Vallabhai Patel','Tony Stark','Govind Vallabh 
Pant','Sardar Vallabhai Patel');";

    String sql5 = "insert into " + DATABASE_TABLE + " (" + KEY_ID + " , " + 
KEY_QUE + " , " + KEY_OPTION1 + " , " + KEY_OPTION2 + " , " + KEY_OPTION3 + 
" , " + KEY_OPTION4 + " , " + KEY_ANS + 
            " ) values(5,'Ball-point pen, used in day-to-day life was 
invented by:', 'Waterman brothers','Write brothers','Biro brothers','Bicc 
brothers','Biro brothers');";

    String sql6 = "insert into " + DATABASE_TABLE + " (" + KEY_ID + " , " + 
KEY_QUE + " , " + KEY_OPTION1 + " , " + KEY_OPTION2 + " , " + KEY_OPTION3 + 
" , " + KEY_OPTION4 + " , " + KEY_ANS + 
            " ) values(6,'The metal whose salts are sensitive to light is:', 
'Zinc','Silver','Copper','Aluminium','Silver');";

    String sql7 = "insert into " + DATABASE_TABLE + " (" + KEY_ID + " , " + 
KEY_QUE + " , " + KEY_OPTION1 + " , " + KEY_OPTION2 + " , " + KEY_OPTION3 + 
" , " + KEY_OPTION4 + " , " + KEY_ANS + 
            " ) values(7,'Worlds largest desert is:', 
'Thar','Kalahari','Sahara','Sonoran','Sahara');";

    String sql8 = "insert into " + DATABASE_TABLE + " (" + KEY_ID + " , " + 
 KEY_QUE + " , " + KEY_OPTION1 + " , " + KEY_OPTION2 + " , " + KEY_OPTION3 + 
" , " + KEY_OPTION4 + " , " + KEY_ANS + 
            " ) values(8,'Black soil is best suited foe the cultivation 
of:', 'Cotton','Rice','Cereals','Sugarcane','Cotton');";

    String sql9 = "insert into " + DATABASE_TABLE + " (" + KEY_ID + " , " + 
KEY_QUE + " , " + KEY_OPTION1 + " , " + KEY_OPTION2 + " , " + KEY_OPTION3 + 
" , " + KEY_OPTION4 + " , " + KEY_ANS + 
            " ) values(9,'The first chairman of Atomic Energy Comission 
was:', 'Dr. C.V. Raman','Dr. H.J. Bhabha','Dr. A.P.J. Abdul Kalam','Dr. 
Vikram Sarabhai','Dr. H.J. Bhabha');";

    String sql10 = "insert into " + DATABASE_TABLE + " (" + KEY_ID + " , " + 
KEY_QUE + " , " + KEY_OPTION1 + " , " + KEY_OPTION2 + " , " + KEY_OPTION3 + 
" , " + KEY_OPTION4 + " , " + KEY_ANS + 
            " ) values(10,'Which is considered the biggest port of India:', 
'Kolkata','Coachin','Chennai','Mumbai','Mumbai');";


    try {
        Log.i("sql1", sql1);
        Log.i("sql2", sql2);
        db.execSQL(sql1);
        db.execSQL(sql2);
        db.execSQL(sql3);
        db.execSQL(sql4);
        db.execSQL(sql5);
        db.execSQL(sql6);
        db.execSQL(sql7);
        db.execSQL(sql8);
        db.execSQL(sql9);
        db.execSQL(sql10);
    } catch (Exception e) {

        e.printStackTrace();
    }
}

//retrieve question
public Cursor getQuestion() {
    Cursor cursor = db.query(DATABASE_TABLE, new String[] {KEY_ID,KEY_QUE, 
KEY_OPTION1, KEY_OPTION2, KEY_OPTION3, KEY_OPTION4, KEY_ANS}, null, null, 
null, null, null);
    if(cursor!=null){
        cursor.moveToFirst();
    }
    return cursor;

}

//retrieve first question
public Cursor getFirstQue() throws Exception{
    Cursor cursor = db.query(true, DATABASE_TABLE, new String[] 
{KEY_ID,KEY_QUE, KEY_OPTION1, KEY_OPTION2, KEY_OPTION3, KEY_OPTION4, 
KEY_ANS}, KEY_ID + " = 1", null, null, null, null, null);
    return cursor;
}


}

我删除了该表,并在insert方法中再次创建了该表,因为该表以前没有用。使用上面的代码,它可以在模拟器上运行,但不能在设备上运行。 上面的代码在下面的类中使用

    package com.ashish.testquiz2;

    import android.app.Activity;
    import android.content.Intent;
    import android.database.Cursor;
    import android.os.Bundle;
    import android.view.View;
    import android.view.View.OnClickListener;
    import android.widget.Button;
    import android.widget.RadioButton;
    import android.widget.RadioGroup;
    import android.widget.Toast;
    import android.widget.RadioGroup.OnCheckedChangeListener;
    import android.widget.TextView;

    public class NewActivity extends Activity{

    TextView tvNextQue;
    RadioGroup rg1;
    RadioButton rbOption1,rbOption2,rbOption3,rbOption4;
    Button bNextQue,bPreQue;

    QuestionAdapter qa;
    Cursor cur = null;
    Cursor cur1 = null;

    int score =0,id;
    String answer = "";
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.newactivity);

        tvNextQue = (TextView) findViewById(R.id.tvNextQue);
        rg1 = (RadioGroup) findViewById(R.id.radioGroup1);
        rbOption1 = (RadioButton) findViewById(R.id.rbOption1);
        rbOption2 = (RadioButton) findViewById(R.id.rbOption2);
        rbOption3 = (RadioButton) findViewById(R.id.rbOption3);
        rbOption4 = (RadioButton) findViewById(R.id.rbOption4);
        bNextQue = (Button) findViewById(R.id.bNextQue);
        bPreQue = (Button) findViewById(R.id.bPreQue);
        qa = new QuestionAdapter(NewActivity.this);

        try {
            qa.open();
            cur1 = qa.getFirstQue();
            cur1.moveToNext();

            tvNextQue.setText("Q. " + 
    cur1.getString(cur1.getColumnIndex("question")));
            rbOption1.setText("" + 
    cur1.getString(cur1.getColumnIndex("option1")));
            rbOption2.setText("" + 
    cur1.getString(cur1.getColumnIndex("option2")));
            rbOption3.setText("" + 
    cur1.getString(cur1.getColumnIndex("option3")));
            rbOption4.setText("" + 
    cur1.getString(cur1.getColumnIndex("option4")));
            id = cur1.getInt(cur1.getColumnIndex("id"));
            answer = cur1.getString(cur1.getColumnIndex("answer"));

        } catch (Exception e) {
            e.printStackTrace();
        }
        cur1.close();

        try {
            qa.open();
            cur = qa.getQuestion();
        } catch (Exception e) {
            e.printStackTrace();
        }
        cur.moveToPosition(1);

        bNextQue.setOnClickListener(new OnClickListener() {

            @Override
            public void onClick(View v) {

                if(!cur.isAfterLast()){

                    tvNextQue.setText("Q. " + 
    cur.getString(cur.getColumnIndex("question")));
                    rbOption1.setText("" + 
    cur.getString(cur.getColumnIndex("option1")));
                    rbOption2.setText("" + 
    cur.getString(cur.getColumnIndex("option2")));
                    rbOption3.setText("" + 
    cur.getString(cur.getColumnIndex("option3")));
                    rbOption4.setText("" + 
    cur.getString(cur.getColumnIndex("option4")));
                    id = cur.getInt(cur.getColumnIndex("id"));
                    answer = cur.getString(cur.getColumnIndex("answer"));
                    cur.moveToNext();

                    rbOption1.setChecked(false);
                    rbOption2.setChecked(false);
                    rbOption3.setChecked(false);
                    rbOption4.setChecked(false);
                }
                else {
                    Intent i = new Intent(NewActivity.this, 
    EndActivity.class);
                    i.putExtra("score", score);
                    startActivity(i);


                }
                qa.close();
            }

        });

        rg1.setOnCheckedChangeListener(new OnCheckedChangeListener() {

            @Override
            public void onCheckedChanged(RadioGroup group, int id) {

                if(rbOption1.isChecked() || rbOption2.isChecked() || 
    rbOption3.isChecked() || rbOption4.isChecked()){
                    String ans = "";
                    switch (id) {
                    case R.id.rbOption1:
                        ans = rbOption1.getText().toString();
                        break;
                    case R.id.rbOption2:
                        ans = rbOption2.getText().toString();
                        break;
                    case R.id.rbOption3:
                        ans = rbOption3.getText().toString();
                        break;
                    case R.id.rbOption4:
                        ans = rbOption4.getText().toString();
                        break;

                    //default:
                        //break;
                    }
                    if(ans.equals(answer)){
                        score++;
                    }
                    Toast.makeText(NewActivity.this, ans, 
     Toast.LENGTH_SHORT).show();
                    //Toast.makeText(NewActivity.this, answer, 
     Toast.LENGTH_SHORT).show();
                }
            }
        });

        bPreQue.setOnClickListener(new OnClickListener() {

            @Override
            public void onClick(View v) {
                if(!cur.isBeforeFirst()){

                    tvNextQue.setText("Q. " + 
    cur.getString(cur.getColumnIndex("question")));
                    rbOption1.setText("" + 
    cur.getString(cur.getColumnIndex("option1")));
                    rbOption2.setText("" + 
    cur.getString(cur.getColumnIndex("option2")));
                    rbOption3.setText("" + 
    cur.getString(cur.getColumnIndex("option3")));
                    rbOption4.setText("" + 
    cur.getString(cur.getColumnIndex("option4")));
                    id = cur.getInt(cur.getColumnIndex("id"));
                    answer = cur.getString(cur.getColumnIndex("answer"));
                    cur.moveToPrevious();
                }
            }
        });
      }
    }

我认为某种程度上没有在设备中创建数据库。(只是一种意见)

1 个答案:

答案 0 :(得分:0)

如果您更改了表的架构,则必须从设备/仿真器中卸载应用程序并重新运行,以便重新创建数据库。
然后将执行数据库类的onCreate()并创建表。
因此,您必须在数据库帮助程序类的onCreate()中包括所有必要的语句。