如何在Android中保存数据库?

时间:2013-01-08 09:19:42

标签: java android database sqlite

我是Android开发的新手,我正在尝试创建一个简单的应用程序,我可以添加和查看我的记录。我可以成功地添加数据并在表格中查看它,它可以在我运行程序时运行。 (我正在关注this tutorial)但是每次我关闭Eclipse并尝试添加新数据并查看它们时,我输入的先前信息就消失了。好像当我关闭eclipse时,它不会保存我的数据库。这是我正在关注的示例代码。

package com.example.hotornot;

import java.sql.Statement;

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;

public class Example {


public static final String KEY_ROWID = "id";
public static final String KEY_NAME = "name";
public static final String KEY_NUM = "number";

public static final String DATABASE_NAME = "dbTry";
public static final String DATABASE_TABLE = "tblSamp";
public static final int DATABASE_VERSION = 1;

public DbHelper ourhelper;
public final Context ourcontext;
public SQLiteDatabase ourdatabase;


 class DbHelper extends SQLiteOpenHelper{

    public DbHelper(Context context) {
        super(context, DATABASE_NAME, null, DATABASE_VERSION);
        // TODO Auto-generated constructor stub
    }

    @Override
    public void onCreate(SQLiteDatabase arg0) {
        // TODO Auto-generated method stub
        arg0.execSQL("CREATE TABLE " + DATABASE_TABLE + " (" + KEY_ROWID + " INTEGER, " + KEY_NAME + " NULL, " + KEY_NUM + " NULL);");
    }

    @Override
    public void onUpgrade(SQLiteDatabase arg0, int arg1, int arg2) {
        // TODO Auto-generated method stub
        arg0.execSQL("DROP TABLE IF EXIST " + DATABASE_TABLE);
        onCreate(arg0);

    }

}

public Example(Context c)
{
    ourcontext = c;     
}

public Example open() throws SQLException
{
    ourhelper = new DbHelper(ourcontext);
    ourdatabase = ourhelper.getWritableDatabase();
    return this;
}

public void close()
    {
        ourhelper.close();
    }

public long createEntry(String name, String num)
{
    // TODO Auto-generated method stub

    ContentValues cv = new ContentValues();
    cv.put(KEY_NAME, name);
    cv.put(KEY_NUM, num);
    return ourdatabase.insert(DATABASE_TABLE, null, cv);        
}

public  String getData() 
{
    // TODO Auto-generated method stub

    String[] columns = new String[]{ KEY_ROWID,KEY_NAME, KEY_NUM};
    Cursor c = ourdatabase.query(DATABASE_TABLE, columns, null, null, null, null, null);
    String result = "";

    int iRow = c.getColumnIndex(KEY_ROWID);
    int iName = c.getColumnIndex(KEY_NAME);
    int iNum = c.getColumnIndex(KEY_NUM);


    for (c.moveToFirst(); ! c.isAfterLast(); c.moveToNext()){
    result = result + c.getString(iRow) + " " +c.getString(iName) + " " + c.getString(iNum) + "\n";

    }
    return result;
}
}

1 个答案:

答案 0 :(得分:0)

您必须覆盖现有数据库或卸载应用

请检查您的代码

on Activity onCreate事件检查是否存在db文件如果存在不覆盖并跳过该过程肯定会得到旧记录