0

我是 android 开发的新手,我正在尝试制作一个简单的应用程序,我可以在其中添加和查看我的记录。我可以成功添加数据并在表格中查看它们,每当我运行程序时它都会起作用。(我正在关注本教程)但是每次我关闭 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;
}
}
4

1 回答 1

0

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

请检查您的代码

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

于 2013-01-08T09:24:37.770 回答