SQLiteOpenHelper类中的sqlite app中的问题

时间:2014-08-13 15:37:09

标签: android sqlite

我正在从slidenerd学习sqlite。毕竟在教程中提到但是问题。
构造函数正常工作但oncreate不起作用。

Openhelper类代码

import android.content.Context;
import android.database.SQLException;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;

public class Kamisqlhelper extends SQLiteOpenHelper {

    public static final String DATABASE_NAME="kamidatabase";
    public static final String TABLE_NAME="kamitable";
    public static final int DATABASE_VERSION=1; 
    private static final String id="_id";
    private static final String names="Name";
    private static final String contact="PhoneNo";
    private static final String CREATE_TABlE = "create table "+TABLE_NAME+"("+id+" integer primary key autoincrement, "+names+" varchar(255), "+contact+" integer);"; 
    private static final String droptable= "drop table "+TABLE_NAME+" if exists";
    private Context context;

    public Kamisqlhelper(Context context){
        super(context, DATABASE_NAME, null, DATABASE_VERSION);
        this.context=context;
        toastmessage.showtoast(context, "constructor called");

    }

    @Override
    public void onCreate(SQLiteDatabase db) {
        // TODO Auto-generated method stub
        try {
            db.execSQL(CREATE_TABlE);
        } catch (SQLException e) {
            // TODO Auto-generated catch block
            toastmessage.showtoast(context, ""+e);
            toastmessage.showtoast(context, "oncreate called");
        }

    }

    @Override
    public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
        // TODO Auto-generated method stub
        try {
            db.execSQL(droptable);
            onCreate(db);
        } catch (SQLException e) {
            // TODO Auto-generated catch block
            toastmessage.showtoast(context, ""+e);
            toastmessage.showtoast(context, "onupgradecalled");
        }

    }

}

主要活动代码

import android.os.Bundle;
import android.app.Activity;
import android.database.sqlite.SQLiteDatabase;
import android.view.Menu;


public class MainActivity extends Activity {
    Kamisqlhelper kamihelper;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    kamihelper = new Kamisqlhelper(this);
    SQLiteDatabase sqLiteDatabase = kamihelper.getWritableDatabase();
}


}

还请建议更好的sqlite最新教程。

1 个答案:

答案 0 :(得分:1)

第一次创建数据库时会调用

onCreate,这意味着当您第一次使用SQLiteOpenHelper时,它将被调用,否则,它永远不会被调用SQLiteOpenHelper.html#onCreate