2015-10-20 63 views
0

我需要幫助以通過使用getter和setter從資產文件夾中的數據庫檢索數據。我沒有任何想法如何檢索數據,因爲即時通訊新的android。將要添加的代碼將檢索數據庫中的數據。通過訪問SQLite在資產文件夾中顯示數據

public class DatabaseHelper extends SQLiteOpenHelper { 

    private static String DB_PATH = "/data/data/com.example.user.displayname/databases/"; 
    private static String DB_NAME = "displayname"; 
    private SQLiteDatabase myDataBase; 
    private Context myContext = null; 


    public DatabaseHelper(Context context) { 
     super(context, DB_NAME, (SQLiteDatabase.CursorFactory) null, 1); 
     this.myContext = context; 
    } 

    public void createDataBase() throws IOException { 
     boolean dbExist = this.checkDataBase(); 
     if(!dbExist) { 
      this.getReadableDatabase(); 

      try { 
       this.copyDataBase(); 
      } catch (IOException e) { 
       throw new Error("Error"); 
      } 
     } 
    } 

    public void copyDataBase() throws IOException { 
     InputStream myInput = this.myContext.getAssets().open(DB_NAME); 
     String outFileName = DB_PATH + DB_NAME; 
     FileOutputStream 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(); 
    } 

    public boolean checkDataBase() { 
     SQLiteDatabase checkDB = null; 

     try { 
      String e = DB_PATH + DB_NAME; 
      checkDB = SQLiteDatabase.openDatabase(e, (SQLiteDatabase.CursorFactory)null, 0); 
     } catch (SQLiteException e) { 
      ; 
     } 

     if(checkDB != null) { 
      checkDB.close(); 
     } 

     return checkDB != null; 
    } 

    public void openDataBase() throws SQLException { 
     String myPath = DB_PATH + DB_NAME; 
     this.myDataBase = SQLiteDatabase.openDatabase(myPath, (SQLiteDatabase.CursorFactory)null, 0); 
    } 

    public synchronized void close() { 
     if(this.myDataBase != null) { 
      this.myDataBase.close(); 
     } 

     super.close(); 
    } 

    @Override 
    public void onCreate(SQLiteDatabase db) { 

    } 

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

    public void createDatabase() { 
    } 
} 
+0

這個問題有什麼進展? – Majkl

回答

1

請檢查下面的代碼這是我的工作:

私人靜態字符串DB_NAME = 「Your_Db_Name」; //數據庫名稱

DB_NAME這裏是你的數據庫的名稱。並且您在資產文件夾中有一個數據庫副本,例如,如果您的數據庫名稱是todoExample,那麼DB_NAME的值將是todoExample,

private static String DB_NAME =「todoExample」;

DataHelper.java

import java.io.File; 
import java.io.FileOutputStream; 
import java.io.IOException; 
import java.io.InputStream; 
import java.io.OutputStream; 

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

public class DataBaseHelper extends SQLiteOpenHelper 
{ 
private static String TAG = "DataBaseHelper"; 
private static String DB_PATH = ""; 
private static String DB_NAME ="todoExample";// Database name 
private SQLiteDatabase mDataBase; 
private final Context mContext; 

public DataBaseHelper(Context context) 
{ 
    super(context, DB_NAME, null, 1); 
    if(android.os.Build.VERSION.SDK_INT >= 17){ 
     DB_PATH = context.getApplicationInfo().dataDir + "/databases/";   
    } 
    else 
    { 
     DB_PATH = "/data/data/" + context.getPackageName() + "/databases/"; 
    } 
    this.mContext = context; 
} 

public void createDataBase() throws IOException 
{ 
    boolean mDataBaseExist = checkDataBase(); 
    if(!mDataBaseExist) 
    { 
     this.getReadableDatabase(); 
     this.close(); 
     try 
     { 
      //Copy the database from assests 
      copyDataBase(); 
      Log.e(TAG, "createDatabase database created"); 
     } 
     catch (IOException mIOException) 
     { 
      throw new Error("ErrorCopyingDataBase"); 
     } 
    } 
} 
    //Check that the database exists here: /data/data/your package/databases/Da Name 
    private boolean checkDataBase() 
    { 
     File dbFile = new File(DB_PATH + DB_NAME); 
     return dbFile.exists(); 
    } 

    //Copy the database from assets 
    private void copyDataBase() throws IOException 
    { 
     InputStream mInput = mContext.getAssets().open(DB_NAME); 
     String outFileName = DB_PATH + DB_NAME; 
     OutputStream mOutput = new FileOutputStream(outFileName); 
     byte[] mBuffer = new byte[1024]; 
     int mLength; 
     while ((mLength = mInput.read(mBuffer))>0) 
     { 
      mOutput.write(mBuffer, 0, mLength); 
     } 
     mOutput.flush(); 
     mOutput.close(); 
     mInput.close(); 
    } 

    //Open the database, so we can query it 
    public boolean openDataBase() throws SQLException 
    { 
     String mPath = DB_PATH + DB_NAME; 
     //Log.v("mPath", mPath); 
     mDataBase = SQLiteDatabase.openDatabase(mPath, null, SQLiteDatabase.CREATE_IF_NECESSARY); 
     //mDataBase = SQLiteDatabase.openDatabase(mPath, null, SQLiteDatabase.NO_LOCALIZED_COLLATORS); 
     return mDataBase != null; 
    } 

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

DataAdapter.java

import java.io.IOException; 
import android.content.Context; 
import android.database.Cursor; 
import android.database.SQLException; 
import android.database.sqlite.SQLiteDatabase; 
import android.util.Log; 

public class DataAdapter 
{ 
    protected static final String TAG = "DataAdapter"; 

    private final Context mContext; 
    private SQLiteDatabase mDb; 
    private DataBaseHelper mDbHelper; 

    public DataAdapter(Context context) 
    { 
     this.mContext = context; 
     mDbHelper = new DataBaseHelper(mContext); 
    } 

    public DataAdapter createDatabase() throws SQLException 
    { 
     try 
     { 
      mDbHelper.createDataBase(); 
     } 
     catch (IOException mIOException) 
     { 
      Log.e(TAG, mIOException.toString() + " UnableToCreateDatabase"); 
      throw new Error("UnableToCreateDatabase"); 
     } 
     return this; 
    } 

    public DataAdapter open() throws SQLException 
    { 
     try 
     { 
      mDbHelper.openDataBase(); 
      mDbHelper.close(); 
      mDb = mDbHelper.getReadableDatabase(); 
     } 
     catch (SQLException mSQLException) 
     { 
      Log.e(TAG, "open >>"+ mSQLException.toString()); 
      throw mSQLException; 
     } 
     return this; 
    } 

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

    public Cursor getTodoData() 
    { 
     try 
     { 
      String sql ="SELECT * FROM list"; 

      Cursor mCur = mDb.rawQuery(sql, null); 
      if (mCur!=null) 
      { 
       mCur.moveToNext(); 
      } 
      return mCur; 
     } 
     catch (SQLException mSQLException) 
     { 
      Log.e(TAG, "getTestData >>"+ mSQLException.toString()); 
      throw mSQLException; 
     } 
    } 
} 

Todo.java

package com.example.todo; 

public class Todo { 

    private String name; 
    private String note; 

    public Todo() { 
    } 

    public Todo(String name, String note) { 
     this.name = name; 
     this.note = note; 
    } 

    public String getName() { 
     return name; 
    } 

    public void setName(String name) { 
     this.name = name; 
    } 

    public String getNote() { 
     return note; 
    } 

    public void setNote(String note) { 
     this.note = note; 
    } 

} 

現在你Ç使用它:

List<Todo> todoItem = new ArrayList<Todo>(); 
DataAdapter mDbHelper = new DataAdapter(urContext);   
mDbHelper.createDatabase();  
mDbHelper.open(); 

Cursor cursor = mDbHelper.getTodoData(); 
if (cursor.moveToFirst()) { 
      do { 
       Todo todo = new Todo(); 
       todo.setName(cursor.getString(1)); 
       todo.setNote(cursor.getString(2)); 

       todoItem.add(todo); 

      } while (cursor.moveToNext()); 
} 

mDbHelper.close(); 
+0

但我已經有我的數據庫在資產文件夾。但我不知道要調用這些數據並使用它來顯示使用getter和setter。你向我展示創建一個新表並添加值並顯示它。 –

+0

@GemUbaldo請檢查我編輯的答案。 – Lawrance

+0

我在公共光標getTodoData() –

0

您無法寫入資產目錄中的文件。該數據庫是經常保存在這裏:

string dbPath = Path.Combine (System.Environment.GetFolderPath (System.Environment.SpecialFolder.Personal), "Database.db3"); 

和裝載例如可以做(C#xamarin)

public static List<Cars> GetCars(int id, ref string logText) 
{ 
    List<Cars> ret = null; 
    string dbPath = EVODatabase.GetDBPath(); 
    try 
    { 
    using (SQLiteConnection conn = new SQLiteConnection(dbPath)) 
    { 
     object[] param = new object[0]; 
     SQLiteCommand cmd = conn.CreateCommand("select * from Cars where id = " + id, param); 
     ret = cmd.ExecuteQuery<Cars>(); 
    } 
    } 
    catch (Exception ex) 
    { 
    logText += "\n" + ex.Message + "\n" + ex.StackTrace + "\n" + ex.InnerException; 
    } 
    return ret; 
} 
0

你可以這樣說:

DBAdapter.java

在這裏你必須改變兩行:

public static final String DATABASE_NAME = "my_db_title"; 
public final static String DATABASE_PATH = "/data/data/my_package_name_here/databases/"; 

將對DBAdapter

public class DBAdapter extends SQLiteOpenHelper { 
    private SQLiteDatabase myDataBase; 
    private final Context myContext; 
    public static final String DATABASE_NAME = "my_db_title"; 
    public final static String DATABASE_PATH = "/data/data/my_package_name_here/databases/"; 
    public static final int DATABASE_VERSION = 1; 

    // public static final int DATABASE_VERSION_old = 1; 

    // Constructor 
    public DBAdapter(Context context) { 
     super(context, DATABASE_NAME, null, DATABASE_VERSION); 
     this.myContext = context; 
    } 

    // Create a empty database on the system 
    public void createDatabase(Context ctx) throws IOException { 
     boolean dbExist1 = checkDataBase(); 
     if (!dbExist1) { 
      this.getReadableDatabase(); 
      try { 
       this.close(); 
       copyDataBase(); 
      } catch (IOException e) { 
       throw new Error("Error copying database"); 
      } 
     } 
    } 

    // Check database already exist or not 
    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; 
    } 

    // Copies your database from your local assets-folder to the just created 
    // empty database in the system folder 
    private void copyDataBase() throws IOException { 
     String outFileName = DATABASE_PATH + DATABASE_NAME; 
     OutputStream myOutput = new FileOutputStream(outFileName); 
     InputStream myInput = myContext.getAssets().open(DATABASE_NAME); 

     byte[] buffer = new byte[1024]; 
     int length; 
     while ((length = myInput.read(buffer)) > 0) { 
      myOutput.write(buffer, 0, length); 
     } 
     myInput.close(); 
     myOutput.flush(); 
     myOutput.close(); 
    } 

    // delete database 
    public void db_delete() { 
     File file = new File(DATABASE_PATH + DATABASE_NAME); 
     if (file.exists()) { 
      file.delete(); 
      System.out.println("delete database file."); 
     } 
    } 

    // Open database 
    public void o() throws SQLException { 
     String myPath = DATABASE_PATH + DATABASE_NAME; 
     myDataBase = SQLiteDatabase.openDatabase(myPath, null, 
       SQLiteDatabase.OPEN_READWRITE); 
    } 

    public synchronized void c() throws SQLException { 
     if (myDataBase != null) 
      myDataBase.close(); 
     super.close(); 
    } 

    public void onCreate(SQLiteDatabase db) { 
    } 

    public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) { 
     if (newVersion > oldVersion) { 
      Log.v("Database Upgrade", "Database version higher than old."); 
      db_delete(); 
     } 
    } 

    // Other stuff 
} 

活動片段

private DBAdapter mDbAdapter; 

的onCreate()

mDbAdapter = new DBAdapter(mContext); 
    try { 
     mDbAdapter.createDatabase(mContext); 
    } catch (IOException e) { 
     e.printStackTrace(); 
    } 

完成

相關問題