Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/java/352.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Java 数据插入外部sqlite数据库,但未保存在android studio中_Java_Android_Sqlite - Fatal编程技术网

Java 数据插入外部sqlite数据库,但未保存在android studio中

Java 数据插入外部sqlite数据库,但未保存在android studio中,java,android,sqlite,Java,Android,Sqlite,我正在使用一个外部sqlite数据库,而不是在我的android studio项目中创建一个,因为数据库中将包含一些已填充的数据。但是我还需要插入更多的数据。 当我插入任何新数据时,它会显示新数据,但当我关闭android应用程序并再次打开以查看数据时,通过应用程序插入的新数据会被删除,只显示预填充的数据 我正在使用DB browser for sqlite创建外部sqlite数据库,并在其中预先填充一些数据。在我的androidstudio项目中,我将这个数据库添加到我的资产文件夹中,并实现了

我正在使用一个外部sqlite数据库,而不是在我的android studio项目中创建一个,因为数据库中将包含一些已填充的数据。但是我还需要插入更多的数据。 当我插入任何新数据时,它会显示新数据,但当我关闭android应用程序并再次打开以查看数据时,通过应用程序插入的新数据会被删除,只显示预填充的数据

我正在使用DB browser for sqlite创建外部sqlite数据库,并在其中预先填充一些数据。在我的androidstudio项目中,我将这个数据库添加到我的资产文件夹中,并实现了SQLiteOpenHelper类来访问这个数据库。从数据库表读取数据是成功的。现在,当我插入新数据时,我也可以临时读取新数据。暂时的意思是,在我关闭应用程序后,新数据会丢失

我的外部sqlite数据库的表:

CREATE TABLE `table_name` (
`Id`    INTEGER NOT NULL PRIMARY KEY AUTOINCREMENT,
`Content`   TEXT NOT NULL
);
SQLiteOpenHelper类:

public class ProcessExternalDBHelper {
private static final String DATABASE_NAME = "database_name.db";
private static final int DATABASE_VERSION = 1;
private static String DATABASE_PATH = "";

private static final String DATABASE_TABLE = "table_name";
private static final String KEY_ROWID = "Id";
private static final String KEY_CONTENT = "Content";

private ExternalDbHelper ourHelper;
private final Context ourContext;
private SQLiteDatabase ourDatabase;

private static class ExternalDbHelper extends SQLiteOpenHelper {

    public ExternalDbHelper(Context context) {
        super(context, DATABASE_NAME, null, DATABASE_VERSION);
        if (Build.VERSION.SDK_INT >= 17) {
            DATABASE_PATH = context.getApplicationInfo().dataDir + 
"/databases/";
        } else {
            DATABASE_PATH = "/data/data/" + context.getPackageName() + 
"/databases/";
        }
    }

    @Override
    public void onCreate(SQLiteDatabase db) {

    }

    @Override
    public void onUpgrade(SQLiteDatabase db, int oldVersion, int 
newVersion) {

    }
}

public ProcessExternalDBHelper(Context context) {
    ourContext = context;
}
//for reading
public ProcessExternalDBHelper openRead() throws SQLException {
    ourHelper = new ExternalDbHelper(ourContext);
    ourDatabase = ourHelper.getReadableDatabase();
    return this;
}
//for writing
public ProcessExternalDBHelper openWrite() throws SQLException{
    ourHelper = new ExternalDbHelper(ourContext);
    ourDatabase = ourHelper.getWritableDatabase();
    return this;
}

public void close() {
    if (ourHelper != null) {
        ourHelper.close();
    }
}

//Create database in activity
public void createDatabase() throws IOException {
    createDB();
}
//Create db if not exists
private void createDB() {
    boolean dbExists = checkDatabase();
    if (!dbExists) {
        openRead();             
        try {
            this.close();
            copyDatabase();
        } catch (IOException ie) {
            throw new Error("Error copying database");
        }
    }
}

private boolean checkDatabase() {
    boolean checkDB = false;
    try {
        String myPath = DATABASE_PATH + DATABASE_NAME;
        File dbfile = new File(myPath);
        checkDB = dbfile.exists();
    } catch (SQLiteException e) {

    }
    return checkDB;
}

private void copyDatabase() throws IOException {
    InputStream myInput = null;
    OutputStream myOutput = null;
    String outFileName = DATABASE_PATH + DATABASE_NAME;

    try {
        myInput = ourContext.getAssets().open(DATABASE_NAME);
        myOutput = new FileOutputStream(outFileName);

        byte[] buffer = new byte[1024];
        int length;
        while ((length = myInput.read(buffer)) > 0) {
            myOutput.write(buffer, 0, length);
        }
        myOutput.flush();
        myOutput.close();
        myInput.close();
    } catch (IOException ie) {
        throw new Error("Copydatabase() error");
    }
}
//To show all available contents in my database
public List<Model> findallContents() {
    List<Model> mContents = new ArrayList<>();

    String[] columns = new String[]{KEY_CONTENT};
    Cursor cursor = ourDatabase.query(DATABASE_TABLE, columns, null, null, 
null, null, null);
    int iContent = cursor.getColumnIndex(KEY_CONTENT);

    for (cursor.moveToFirst(); !cursor.isAfterLast(); cursor.moveToNext()) 
    {
        Model model= new Model();
        model.setContent(cursor.getString(iContent));

        mContents.add(model);
    }

    cursor.close();
    return mContents;
}

public void addContent(String content) {
    ContentValues contentValues = new ContentValues();
    contentValues.put(KEY_CONTENT, content);

    ourDatabase.insert(DATABASE_TABLE, null, contentValues);
    ourDatabase.close();
}

}
最后是我的活动类,我在其中读写数据:

public class MainActivity extends AppCompatActivity {

private EditText editText_Content;
private ImageButton imageButton_Save;
private List<Model> mContentsArrayList;

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

    ProcessExternalDBHelper myDbHelper = new ProcessExternalDBHelper(this);
    try {
        myDbHelper.createDatabase();
    } catch (IOException ioe) {
        throw new Error("Unable to CREATE DATABASE");
    } finally {
        myDbHelper.close();
    }

    initialize();

    GetContents();

    imageButton_Save.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            if (!(editText_Content.getText().toString().trim().isEmpty())) 
            {
                SaveContents();
            } 
        }
    });
}

private void initialize() {
    editText_Content = findViewById(R.id.editText_contents);
    imageButton_Save = findViewById(R.id.imageButton_save);

    mContentsArrayList = new ArrayList<>();
}
//GetContents and show them later in my RecyclerView
private void GetContents() {
    try {
        mContentsArrayList.clear();
        ProcessExternalDBHelper autoProcess = new 
    ProcessExternalDBHelper(this);
        autoProcess.openRead();
        mContentsArrayList.addAll(autoProcess.findallContents();
        autoProcess.close();
    } catch (Exception e) {

    }
}
//For saving content into database    
private void SaveContents() {
    String content = editText_Content.getText().toString();

    try {
        ProcessExternalDBHelper autoProcess = new 
ProcessExternalDBHelper(this);
        autoProcess.openWrite();   //for writing into database
        autoProcess.addContent(content);
        autoProcess.close();
        editText_Content.getText().clear();
    } catch (Exception e) {

    }
}

}
public类MainActivity扩展了AppCompatActivity{
私有编辑文本编辑文本内容;
私有图像按钮图像按钮保存;
私有列表mContentsArrayList;
@凌驾
创建时受保护的void(Bundle savedInstanceState){
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
ProcessExternalDBHelper myDbHelper=新ProcessExternalDBHelper(此);
试一试{
myDbHelper.createDatabase();
}捕获(ioe异常ioe){
抛出新错误(“无法创建数据库”);
}最后{
myDbHelper.close();
}
初始化();
GetContents();
imageButton_Save.setOnClickListener(新视图.OnClickListener(){
@凌驾
公共void onClick(视图v){
if(!(editText\u Content.getText().toString().trim().isEmpty())
{
SaveContents();
} 
}
});
}
私有void初始化(){
editText\u内容=findViewById(R.id.editText\u内容);
imageButton_Save=findViewById(R.id.imageButton_Save);
mContentsArrayList=newarraylist();
}
//获取内容并稍后在我的RecyclerView中显示
私有void GetContents(){
试一试{
mContentsArrayList.clear();
ProcessExternalDBHelper自动处理=新建
ProcessExternalDBHelper(此);
autoProcess.openRead();
mContentsArrayList.addAll(autoProcess.findallContents();
autoProcess.close();
}捕获(例外e){
}
}
//用于将内容保存到数据库中
私有void SaveContents(){
String content=editText_content.getText().toString();
试一试{
ProcessExternalDBHelper自动处理=新建
ProcessExternalDBHelper(此);
autoProcess.openWrite();//用于写入数据库
autoProcess.addContent(content);
autoProcess.close();
editText_Content.getText().clear();
}捕获(例外e){
}
}
}
最后,我正在使用Sqlite(3.10.1版)、android studio(3.0.1版)和MinsdkVersion19的DB浏览器


我希望新插入到数据库中的数据能够被保存并在以后看到,即使我关闭我的应用程序并稍后重新启动应用程序。谢谢!

您的问题是数据库路径没有被重置,因此在调用createDatabase时是空的

因此,查看数据库是否存在的检查无法找到数据库(它只查找文件系统最高级别的文件database_db.db,因此该文件将不存在),并且复制数据库时会覆盖保存有数据的数据库

我建议进行以下修改:-

private boolean checkDatabase() {
    File dbfile = new File(ourContext.getDatabasePath(DATABASE_NAME).getPath());
    if ( dbfile.exists()) return true;
    File dbdir = dbfile.getParentFile();
    if (!dbdir.exists()) {
        dbdir.mkdirs();
    }
    return false;
}
  • 这样做的好处是,如果数据库目录不存在,则将创建该目录,并且该目录仅依赖于路径的数据库名称
  • 也不需要try/catch构造
或者:-

private void copyDatabase() throws IOException {
    InputStream myInput = null;
    OutputStream myOutput = null;
    String outFileName = ourContext.getDatabasePath(DATABASE_NAME).getPath(); //<<<<<<<<<< CHANGED

    try {
        myInput = ourContext.getAssets().open(DATABASE_NAME);
        myOutput = new FileOutputStream(outFileName);

        byte[] buffer = new byte[1024];
        int length;
        while ((length = myInput.read(buffer)) > 0) {
            myOutput.write(buffer, 0, length);
        }
        myOutput.flush();
        myOutput.close();
        myInput.close();
    } catch (IOException ie) {
        throw new Error("Copydatabase() error");
    }
}
private void copyDatabase()引发IOException{
InputStream myInput=null;
OutputStream myOutput=null;

String OutfielName=ourContext.getDatabasePath(DATABASE_NAME).getPath();//是的,我也通过在createDatabase()中初始化我的DATABASE_路径进行了检查。我真的要感谢你帮助我理解我的错误并展示了更有效的方法。它很有效!!!
private void copyDatabase() throws IOException {
    InputStream myInput = null;
    OutputStream myOutput = null;
    String outFileName = ourContext.getDatabasePath(DATABASE_NAME).getPath(); //<<<<<<<<<< CHANGED

    try {
        myInput = ourContext.getAssets().open(DATABASE_NAME);
        myOutput = new FileOutputStream(outFileName);

        byte[] buffer = new byte[1024];
        int length;
        while ((length = myInput.read(buffer)) > 0) {
            myOutput.write(buffer, 0, length);
        }
        myOutput.flush();
        myOutput.close();
        myInput.close();
    } catch (IOException ie) {
        throw new Error("Copydatabase() error");
    }
}