2011-11-25 6 views
5

Desidero recuperare i dati dal database SQLITE e visualizzarli in un ELENCO.Non è possibile recuperare i dati dal database Sqlite

Il nome del mio database è AppDB.db e il nome della tabella è Scrip che contiene 3 colonne _id (chiave primaria) e il simbolo & company_name che sono testo.

Voglio recuperare solo 2a e 3a colonna. Ho copiato il database nella cartella Risorse.

Ho la forza chiusa quando eseguo il seguente codice ma non so quale possa essere il motivo. Si prega di aiutare ..

Sono principiante assoluto ad Android, in modo che qualsiasi aiuto apprezzato ...

Contenuto:

1.) DataAttach.java

2.) DBManager. java

3.) LogCat

4.) .xml in breve

5.) AVD Problema

6.) Snapshot di database di


1.) DataAttach.java

public class DataAttach extends Activity { 
    private DbManager dbM; 
    private Cursor c; 

    @Override 
    public void onCreate(Bundle savedInstanceState) { 
     super.onCreate(savedInstanceState); 
     try { 
      dbM = new DbManager(this); 
      dbM.createDataBase(); 
      dbM.openDB(); 

      try { 
       c = dbM.fetchAllData(); 
      } catch (Exception e) { 
       throw new Error("\n\nERROR Fetchin data\n\n"); 
      } 

      if (c != null) { 
       SimpleCursorAdapter adapter = new SimpleCursorAdapter(
         this, 
         android.R.layout.simple_list_item_1, 
         c, 
         new String[] { c.getString(c.getColumnIndex("_id")), 
           c.getString(c.getColumnIndex("symbol")), 
           c.getString(c.getColumnIndex("company_name")) }, 
         new int[] { R.id._id, R.id.symbol, R.id.company_name }); 
       ListView list = (ListView) findViewById(R.id.MainLayout); 
       list.setAdapter(adapter); 
      } 
     } 

     catch (Exception e) { 
      throw new Error("\n\nERROR DB failure\n\n"); 
     } 

     finally { 
      c.close(); 
      dbM.close(); 
     } 
    } 
}  

2.) DbManager.java

public class DbManager extends SQLiteOpenHelper { 

    private static final String KEY_ROWID = "_id"; 
    private static final String KEY_SYMBOL = "symbol"; 
    private static final String KEY_COMPANY_NAME = "company_name"; 

    private static final String DATABASE_NAME = "AppDB"; 
    private static final String DATABASE_PATH = "/data/data/com.dbexample/databases/"; 
    private static final Integer DATABASE_VERSION = 3; 
    private static final String DATABASE_TABLE = "Scrip"; 
    // private static final String TAG = "DbManager"; 
    private final Context ctx; 
    private SQLiteDatabase mDb; 

    public DbManager(Context context) { 

     super(context, DATABASE_NAME, null, DATABASE_VERSION); 
     this.ctx = context; 
    } 

    /* 
    * Creates a empty database on the system and rewrites it with your own 
    * database. 
    */ 
    public void createDataBase() { 

     if (checkDataBase()) { 
      // do nothing - database already exist 
     } else { 
      /* 
      * By calling this method and empty database will be created into 
      * the default system path of your application so we can overwrite 
      * that database with our database. 
      */ 
      this.getReadableDatabase(); 

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

    /* 
    * Check if the database already exist to avoid re-copying the file each 
    * time you open the application. 
    */ 
    private boolean checkDataBase() { 
     SQLiteDatabase checkDB = null; 
     try { 
      String myPath = DATABASE_PATH + DATABASE_NAME; 
      checkDB = SQLiteDatabase.openDatabase(myPath, null, 
        SQLiteDatabase.OPEN_READONLY); 

     } catch (SQLiteException e) { 
      throw new Error("\n\nERROR database does't exist yet\n\n"); 
     } 

     if (checkDB != null) { 
      checkDB.close(); 
     } 
     return checkDB != null ? true : false; 
    } 

    /* 
    * Copies your DB from your local assets-folder to the just created empty DB 
    * in the system folder, from where it can be accessed and handled. 
    */ 
    private void copyDataBase() throws IOException { 
     /* Open your local db as the input stream */ 
     InputStream myInput = ctx.getAssets().open(DATABASE_NAME); 

     /* Path to the just created empty db */ 
     String outFileName = DATABASE_PATH + DATABASE_NAME; 

     /* Open the empty db as the output stream */ 
     OutputStream myOutput = new FileOutputStream(outFileName); 

     /* transfer bytes from the inputfile to the outputfile */ 
     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 void openDB() throws SQLException { 
     String myPath = DATABASE_PATH + DATABASE_NAME; 
     mDb = SQLiteDatabase.openDatabase(myPath, null, 
       SQLiteDatabase.OPEN_READONLY); 
    } 

    @Override 
    public void close() { 
     mDb.close(); 
    } 

    @Override 
    public void onCreate(SQLiteDatabase db) { 
    } 

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

    public Cursor fetchAllData() { 
     return mDb.query(DATABASE_TABLE, new String[] { KEY_ROWID, KEY_SYMBOL, 
       KEY_COMPANY_NAME }, null, null, null, null, null); 

     // return mDb.rawQuery("select _id,symbol,company_name from Scrip", 
     // new String[] { KEY_ROWID,KEY_SYMBOL, KEY_COMPANY_NAME }); 
    } 
}         

3.) LOG CAT

sqlite3_open_v2("/data/data/com.dbexample/databases/AppDB", &handle, 1, NULL) failed 

Failed to open the database. closing it. 

android.database.sqlite.SQLiteCantOpenDatabaseException: unable to open database file 

at android.database.sqlite.SQLiteDatabase.dbopen(Native Method) 

at android.database.sqlite.SQLiteDatabase.openDatabase(SQLiteDatabase.java:1017)    

4.) main.xml

Contiene RelativeLayout avente 3 TextViews all'interno RelativeLayout.


5.) ho SEMPRE ottenere questo errore

Anche dopo la riapertura l'eclissi, il riavvio del sistema, ricreando l'AVD, cercando, kill_server e START_SERVER, ricevo questo messaggio.

Failed to install DataAttach.apk on device 'emulator-5554': device not found 
com.android.ddmlib.InstallException: device not found 
Launch canceled!    

6.) Schermata di DB:

Screenshot

TUTTO DOC A CURA PER ULTIMO CODICE E ACC. ALLE SUGGERIMENTI, ma l'app non funziona.

+1

SimpleCursorAdapter ha sempre bisogno di _id.so provare a recuperare _id anche nel cursore. – Hiral

+0

@Hiral - provato, ma stesso prob :( – GAMA

+0

Ma poi il problema potrebbe anche qualcos'altro, incluso questo..bcz avrai sempre bisogno di _id per passare a SimpleCursorAdapter. – Hiral

risposta

3

Non so cosa si sta tentando di fare con questa funzione. Stai provando a leggere un file .db e dici che il DB è stato creato. La prima volta che si tenta di eseguire non ci sarà un file .db nel percorso del database. Ecco perché viene generato l'errore "Nessun file o directory".

11-25 12:06:13.398: E/Netd(31): Unable to bind netlink socket: No such file or directory 

Nel DBManager Constructor chiamata del SQLiteOpenHelper getReadableDatabase() che creerà un db, se non ce n'è uno. SQLiteOpenHelper

public void createNewDatabase() { 
       InputStream assetsDB = null; 
       try { 
        assetsDB = context.getAssets().open(DATABASE_NAME); 
        OutputStream dbOut = new FileOutputStream(DATABASE_PATH 
          + DATABASE_NAME); 

        byte[] buffer = new byte[1024]; 
        int length; 
        while ((length = assetsDB.read(buffer)) > 0) { 
         dbOut.write(buffer, 0, length); 
        } 

        dbOut.flush(); 
        dbOut.close(); 
        assetsDB.close(); 
        Log.i(TAG, "New database created..."); 
       } catch (IOException e) { 

        Log.e(TAG, "Could not create new database..."); 
       } 
      } 
+0

ya Prova a chiamare il metodo getReadableDatabase() nel costruttore. lavoro – SurRam

+0

avete nel costruttore. comunque il tuo metodo aperto è un metodo non statico. Quindi sicuramente creerai un oggetto per chiamarlo. Avere la dichiarazione nel costruttore sarà buona – SurRam

+0

avrei dovuto menzionarlo nel commento precedente stesso. Non hai affatto bisogno del metodo aperto. Basta avere getReadableDatabase() nel costruttore che creerà un db se non è thre. aprilo se già lì. Usa quell'istanza per fare tutte le tue funzioni relative a db – SurRam

2

SimpleCursorAdapter bisogno _id campo nella Cursor si passa ad esso. Quindi, cercare di modificare la tua ricerca in questo modo:

return mDb.query(DATABASE_TABLE, new String[] { KEY_ROWID, KEY_SYMBOL, KEY_COMPANY_NAME }, null, null, null, null, null); 

Inoltre si stanno ottenendo:

android.database.sqlite.DatabaseObjectNotClosedException: Application did not close the cursor or database object that was opened here

assicuratevi di chiamare close() su tutti Cursor oggetti che si utilizzano quando si è fatto con loro.

+0

dopo aver chiuso il cursore e passando l'ID, dà comunque lo stesso prob. Grazie comunque ! – GAMA

+0

INTERO DOC EDITATO AL PIÙ RECENTE CODICE E ACC. ALLE SUGGERIMENTI, ma l'app non funziona. – GAMA

+0

CODICE AGGIORNATO, PER FAVORE GUARDA ... – GAMA

2

credo, è necessario impostare il file di layout come:

SimpleCursorAdapter sca=new SimpleCursorAdapter(context, android.R.layout.simple_list_item_1, c, from, to); 

Perché si sta passando R.layout.main cui si sta dando errore nel ricaricare stesso file di layout.

Non sono sicuro, ma questo potrebbe essere il problema. Aggiungete anche _id nel cursore passato alla scheda.

+0

lo farà. thnx. – GAMA

+0

INTERO DOC MODIFICATO PER ULTIMO CODICE E ACC. ALLE SUGGERIMENTI, ma l'app non funziona. – GAMA

+0

Qualsiasi aiuto apprezzato! – GAMA