Android数据库从现有的.sqlite文件中读取

时间:2015-02-18 14:34:44

标签: android database

我想从现有文件中读取数据库。

我已将.sqlite数据库复制到资产文件夹。 我可以在/ data / data // databases /

中的DDMS资源管理器下看到.sqlite文件

然而,当我运行" c = db.rawQuery(" SELECT count(*)FROM sqlite_master WHERE type =' table'",null);&# 34;

它只返回android_metadata表,而不是我在Firefox SQLite Manager中创建的数据库中的其他表。

*注意,我将发布我的DatabaseHandler和数据库活动文件,对于任何修改,请提供完整代码(修改我现有的文件),原因是我是Android的新手,而且代码段混淆了我到我需要粘贴,替换或追加等级的地方,因此我会很感激完整的代码。

数据库处理程序:

    package com.mypackage.lm;

import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.ArrayList;
import java.util.List;

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

public class DatabaseHelper extends SQLiteOpenHelper {

    private static final String DB_NAME  = "lm.sqlite";
    private static final int DB_VERSION  = 1;
    private static final String TABLE_LM = "lmtable";
    private static final String LOG_TAG = "debugger";
    private static final String DB_PATH = "context.getDatabasePath(DatabaseHelper.DB_NAME).getParentFile()";

    private SQLiteDatabase myDB; 
    private Context context;

    public DatabaseHelper(Context context) {
    super(context, DB_NAME, null, DB_VERSION);
    this.context = context;
    }

    @Override
    public void onCreate(SQLiteDatabase db) {
    // TODO Auto-generated method stub

    }

    @Override
    public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
    // TODO Auto-generated method stub

    }

    @Override
    public synchronized void close(){
    if(myDB!=null){
        myDB.close();
    }
    super.close();
    }

    /***
     * Check if the database is exist on device or not
     * @return
     */
    private boolean checkDataBase() {
    SQLiteDatabase tempDB = null;
    try {
        String myPath = DB_PATH + DB_NAME;
        tempDB = SQLiteDatabase.openDatabase(myPath, null,
            SQLiteDatabase.OPEN_READWRITE);
    } catch (SQLiteException e) {
        Log.e("ts01 - check", e.getMessage());
    }
    if (tempDB != null)
        tempDB.close();
    return tempDB != null ? true : false;
    }

/***
 * Copy database from source code assets to device
 * @throws IOException
 */
public void copyDataBase() throws IOException{
    try {
    InputStream myInput = context.getAssets().open(DB_NAME);
    String outputFileName = DB_PATH + DB_NAME;
    OutputStream myOutput = new FileOutputStream(outputFileName);

    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 (Exception e) {
    Log.e("ts02 - copyDatabase", e.getMessage());
    }

    }

/***
 * Open database
 * @throws SQLException
 */
    public void openDataBase() throws SQLException{
        String myPath = DB_PATH + DB_NAME;
        myDB = SQLiteDatabase.openDatabase(myPath, null, SQLiteDatabase.OPEN_READWRITE);
}

    /***
     * Check if the database doesn't exist on device, create new one
     * @throws IOException
     */
    public void createDataBase() throws IOException {
        boolean dbExist = checkDataBase();        

        if (dbExist) {
            System.out.println("Database DOES exist");

        } else {
        System.out.println("Database DOESN'T exist");
        this.getReadableDatabase();
        try {
            copyDataBase();
        } catch (IOException e) {
            Log.e("ts03 - create", e.getMessage());
        }
        }
    }


    public List<String> getAllUsers(){
        List<String> listUsers = new ArrayList<String>();
        SQLiteDatabase db = this.getWritableDatabase();

        Cursor c;

        try {
        //c = db.rawQuery("SELECT * FROM " + TABLE_LM , null);
        //c = db.rawQuery("SELECT name FROM sqlite_master WHERE type = 'table'" , null);
        //c = db.rawQuery("SELECT count(*) FROM sqlite_master WHERE type = 'table' AND name != 'android_metadata' AND name != 'sqlite_sequence'", null);
        c = db.rawQuery("SELECT count(*) FROM sqlite_master WHERE type = 'table'", null);
        if(c == null) return null;

        String name;
        c.moveToFirst();
        do {            
            name = c.getString(0);            
            listUsers.add(name);
        } while (c.moveToNext()); 
        c.close();
        } catch (Exception e) {
        Log.e("ts04", e.getMessage());
        }

        db.close();        

        return listUsers;
    }

}

数据库活动:

    package com.mypackage.lm;

import java.io.IOException;
import java.util.List;

import com.mypackage.lm.R.id;

import android.app.Activity;
import android.graphics.Color;
import android.os.Bundle;
import android.util.Log;
import android.view.Menu;
import android.widget.ArrayAdapter;
import android.widget.ListAdapter;
import android.widget.ListView;
import android.widget.TextView;

public class DatabaseActivity extends MainActivity {

        DatabaseHelper dbHeplper;
        ListView lvUsers;
        ListAdapter adapter;

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



        dbHeplper = new DatabaseHelper(getApplicationContext());


        try {
            dbHeplper.createDataBase();
        } catch (IOException e) {
            e.printStackTrace();
        }

        lvUsers = (ListView)findViewById(id.listViewDB);
         List<String> listUsers = dbHeplper.getAllUsers();

        if(listUsers != null){
            adapter = new ArrayAdapter<String>(getApplicationContext(),
                android.R.layout.simple_list_item_1, android.R.id.text1,
                listUsers);
            lvUsers.setAdapter(adapter);
        }

        }

        @Override
        public boolean onCreateOptionsMenu(Menu menu) {
        // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(R.menu.main, menu);
        return true;
        }


    }

2 个答案:

答案 0 :(得分:0)

也许我错了,这不是答案,但如果这应该是你的道路:

   private static final String DB_PATH = "context.getDatabasePath(DatabaseHelper.DB_NAME).getParentFile()";

然后你将没有文件路径。您在引号内设置了一个方法,因此路径将是:

    context.getDatabasePath(DatabaseHelper.DB_NAME).getParentFile()lm.sqlite

我认为你想要做的是:

        private static final String DB_PATH = context.getDatabasePath(DatabaseHelper.DB_NAME).getParentFile();

答案 1 :(得分:0)

好的,由于一些奇怪的原因它起作用,我从虚拟设备卸载了APP然后重新运行它,在重新安装apk后我能够看到数据库表(android_metadata和lmtable)。

现在我的下一阶段是确定我的android如何知道对数据库进行了更改并且需要重新复制,尽管“如果存在DB”语句,我读到了关于增加数据库版本号的问题,所以可能这是问题但是至于现在,从虚拟设备卸载应用程序就可以了。