2014-02-13 98 views
1

嗨,我無法讀取我的項目中的嵌入式SQLite數據庫。無法從Android中的本地SQLite數據庫讀取?

我想從一個活動獲取數據到另一個活動並在TextView中顯示它。

這裏是我的數據庫工具類:

public class myDBTools extends SQLiteOpenHelper { 

private static String DB_PATH = "/data/data/com.example.appscan5/databases/"; 

private static String DB_NAME = "productlist"; 

private static SQLiteDatabase myDatabase; 

public myDBTools(Context applicationContext) { 
    super(applicationContext, DB_NAME, null, 1); 

} 

@Override 
public void onCreate(SQLiteDatabase db) { 
    myDatabase= SQLiteDatabase.openDatabase(DB_PATH + DB_NAME,null, SQLiteDatabase.CREATE_IF_NECESSARY); 

} 

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

} 

public static HashMap<String, String> getProductInfo(String id) { 

    HashMap<String, String> productMap = new HashMap<String, String>(); 

    String selectQuery = "SELECT * FROM products WHERE _id='" + id + "'"; 

    Cursor cursor = myDatabase.rawQuery(selectQuery, null); 

    // move to the first row of dataBase 
    if (cursor.moveToFirst()) { 

     do { 

      productMap.put("NumberId", cursor.getString(0)); 
      productMap.put("BarcodeId", cursor.getString(1)); 
      productMap.put("ProductName", cursor.getString(2)); 
      productMap.put("Calories", cursor.getString(3)); 
      productMap.put("Protein", cursor.getString(4)); 
      productMap.put("Carbohydrates", cursor.getString(5)); 
      productMap.put("Fats", cursor.getString(6)); 
      productMap.put("Grams", cursor.getString(7)); 

     } while (cursor.moveToNext()); 

    } 
    return productMap; 
} 
} 

這是我如何使用它的另一項活動:

myDBTools mydbTools = new myDBTools(this); 
HashMap<String, String> productMap = mydbTools.getProductInfo(id); 
+0

只是額外的一點,你可能不想使用'SELECT *',如果你的結構稍後有任何改變,它可能會讓你從這些位置獲取信息。最好使用'SELECT numberId,barcodeId,productName'等 – Nicholas

回答

1

您需要先打開數據庫。

mydbTools.open(); 

把上面一行到您的OnCreate,它會工作

1

您必須執行任何操作之前Open數據庫:打造開放式方法

// ---opens the database--- 
public myDBTools open() throws SQLException { 
    db = DBHelper.getWritableDatabase(); 
    return this; 
} 

而且必須Close數據庫操作後完成。創建close方法

// ---closes the database--- 
public void close() { 
    DBHelper.close(); 
} 

現在,創造一個像

myDBTools mydbTools = new myDBTools(this); 
mydbTools.open(); 

//All the operations related to database 
mydbTools.close(); 
0

myDBTools object叫這個OpenClose方法後使用的SQLite數據庫有很多的麻煩。看來我一直在創建一個數據庫,但沒有複製我的數據庫文件的內容到新創建的數據庫使用SQLiteOpenHelper。

到底我有沒有表的一個數據庫,它和DUS我不能執行選擇查詢和這裏就是我得到了一個錯誤:

String selectQuery = "SELECT * FROM products WHERE _id='" + id + "'"; 
Cursor cursor = myDatabase.rawQuery(selectQuery, null); 

這是我的全部工作的代碼到目前爲止的數據庫類:

public class MyDatabase extends SQLiteOpenHelper { 

private static String TAG = MyDatabase.class.getName(); 

private String DB_PATH = "/data/data/com.example.appscan5/databases/"; 
private static String DB_NAME = "productlist.db"; 

private SQLiteDatabase myDataBase = null; 
private final Context myContext; 

public MyDatabase(Context context) { 
    super(context, DB_NAME, null, 1); 

    this.myContext = context; 
    Log.v("log_tag", "DBPath: " + DB_PATH); 
    // File f=getDatabasePath(DB_NAME); 
} 

public void createDataBase() throws IOException { 
    boolean dbExist = checkDataBase(); 
    SQLiteDatabase db_Read = null; 
    if (dbExist) { 
     Log.v("log_tag", "database does exist"); 
    } else { 
     Log.v("log_tag", "database does not exist"); 

     //By calling this method and empty database will be created into the default system path 
     //of your application so we are gonna be able to overwrite that database with our database. 
     db_Read = this.getReadableDatabase();   
     db_Read.close(); 

     try { 
      copyDataBase(); 
     } catch (IOException e) { 
      throw new Error("Error copying database"); 
     } 
    } 
} 

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

private boolean checkDataBase() { 

    File dbFile = new File(DB_PATH + DB_NAME); 
    Log.v("dbFile", dbFile + " " + dbFile.exists()); 

    return dbFile.exists(); 
} 

public boolean openDataBase() throws SQLException { 

    String mPath = DB_PATH + DB_NAME; 
    myDataBase = SQLiteDatabase.openDatabase(mPath, null, SQLiteDatabase.CREATE_IF_NECESSARY); 

    return myDataBase != null; 
} 


@Override 
public synchronized void close() { 
    if (myDataBase != null) myDataBase.close(); 

    super.close(); 
} 

@Override 
public void onCreate(SQLiteDatabase db) { 

    //When i use this createQuery i create a database and don't get an error but the database is empty. 

    // String createQuery = 
    // "CREATE TABLE products (numberId INTEGER NOT NULL, barcodeID TEXT PRIMARY KEY NOT NULL, name TEXT NOT NULL, calories INTEGER NOT NULL, protein INTEGER,carbohydrates INTEGER, fats INTEGER, grams INTEGER, sodium INTEGER, fibre INTEGER)"; 
    // db.execSQL(createQuery); 
} 

@Override 
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) { 
    Log.v(TAG, "Upgrading database, this will drop database and recreate."); 
} 

public HashMap<String, String> getProductInfo(String id) { 

    HashMap<String, String> productMap = new HashMap<String, String>(); 

    SQLiteDatabase db = this.getReadableDatabase(); 
    openDataBase(); 


    // HERE I GET AN EROR (NO SUCH TABLE) 
    String selectQuery = "SELECT * FROM products WHERE barcodeId='" + id + "'"; 

    //String selectQuery = "SELECT * FROM products"; 


    Cursor myCursor = db.rawQuery(selectQuery, null); 
    if (!myCursor.moveToFirst()) { 
     Log.w("debug", "No tables!"); 
    } else 
     Log.w("Done", "Table is here"); 


    do { 

     productMap.put("NumberId", myCursor.getString(0)); 
     productMap.put("BarcodeId", myCursor.getString(1)); 
     productMap.put("ProductName", myCursor.getString(2)); 
     productMap.put("Calories", myCursor.getString(3)); 
     productMap.put("Protein", myCursor.getString(4)); 
     productMap.put("Carbohydrates", myCursor.getString(5)); 
     productMap.put("Fats", myCursor.getString(6)); 
     productMap.put("Grams", myCursor.getString(7)); 
     productMap.put("Sodium", myCursor.getString(8)); 
     productMap.put("Fibre", myCursor.getString(9)); 


    } while (myCursor.moveToNext()); 



    close(); 
    return productMap; 


    // My second query here fails, since the database contains no tables. 
} 

} 

這是我如何使用它的代碼:

//-------------------------------------------------------------------------------- 
MyDatabase myDB = new MyDatabase(this); 
try { 
    myDB.createDataBase(); 
    } catch (IOException e) { 
     e.printStackTrace(); 
    } 

HashMap<String, String> productMap =myDB.getProductInfo(id); 
//--------------------------------------------------------------------------------    

我不是相當舒服是這是使用MyDatabase類的最好方法。如果有人更好地使用它,請分享一個解釋原因。

乾杯!