2014-02-13 3 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에 선 위에 놓고, 당신이 Open 데이터베이스에 어떤 작업하기 전에해야한다

1

작동합니다 : 열려있는 방법

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

을 만들고 Close 데이터베이스 작업 후 완료해야합니다.

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

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

처럼 myDBTools object이라는 OpenClose 방법을 생성 한 후, 이제 close 메소드

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

을 만들 SQLite는 함께 데이터베이스를 사용하여 문제를 많이했다. 그것은 내가 데이터베이스를 만들었지 만 havent SQLiteOpenHelper를 사용하여 새로 만든 데이터베이스에 내 데이터베이스 파일의 내용을 복사하는 것 같습니다. 결국

내가 그 안에 어떤 테이블이있는 데이터베이스를했고 DUS 내가 선택 쿼리를 실행을 couldnt 그리고 여기에 오류가 가지고있는 곳입니다 : 이것은 내 전체 작업 코드는 지금까지의

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 클래스를 사용하는 가장 좋은 방법입니다. 어떤 사람이 그것을 사용하는 것이 더 좋은 생각이라면 이유를 설명해주십시오.

건배!

관련 문제