2011-11-25 122 views
5

我想从SQLITE数据库中获取数据并将其显示在LIST中。无法从Sqlite数据库获取数据

我的数据库名称是AppDB.db,表名是Scrip,它包含3列_id(主键)和符号& company_name,它们是文本。

我只想抓取第二列和第三列。我已将数据库复制到“资产”文件夹中。

当我执行下面的代码时,我得到强制关闭,但我不知道可能是什么原因。请帮助..

我绝对初学者到Android,所以任何帮助赞赏...

内容:

1)DataAttach.java

2)DbManager。在简要

的java

3.)的logcat

4.).XML

5.)AVD问题

6.)数据库的快照


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中

它包含具有内的RelativeLayout 3个TextViews RelativeLayout的。


5)我总是得到这个错误

即使重开食,重新启动系统,重新创建AVD,努力,kill_server和START_SERVER后,我得到这个消息。

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

6。DB)的截图:

Screenshot

全DOC编辑,以最新的代码和ACC。对于您的建议,但仍然无法使用应用程序。

+1

SimpleCursorAdapter总是需要_id.so尝试在您的光标中提取_id。 – Hiral

+0

@Hiral - 尝试过,但同样的概率:( – GAMA

+0

但是然后问题可能还包括这个..bcz其他问题,你总是需要_id传递给SimpleCursorAdapter。 – Hiral

回答

3

我不知道你在用这个功能做什么。您正在尝试读取.db文件并说数据库已创建。第一次尝试运行时,数据库路径中不会有.db文件。这就是为什么'没有这样的文件或目录'错误被抛出。

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

在DBManager构造函数调用SQLiteOpenHelper的getReadableDatabase()如果没有一个,这将创建一个数据库。 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。尝试在构造函数中调用getReadableDatabase()方法。你有工作 – SurRam

+0

它在构造函数中。反正你的开放方法是非静态的方法。所以你肯定会创建一个对象来调用它。在构造函数中声明将是好的 – SurRam

+0

我应该在前面的评论中提到这一点。你根本不需要打开方法。只要在构造函数中有getReadableDatabase(),它将创建一个数据库,如果它不是thre。如果已经存在,请打开它。使用该实例来完成所有与数据库相关的功能 – SurRam

2

SimpleCursorAdapter需要在Cursor您传递给它_id领域。因此,尝试改变你的查询是这样的:

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

您也越来越:

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

确保你,当你与他们做了你使用的所有Cursor对象调用close()

+0

关闭游标和传递ID后,它仍然给出相同的概率 由于反正! – GAMA

+0

整个DOC编辑为最新的代码和ACC。您的建议,但仍然应用程序不起作用。 – GAMA

+0

代码已更新,请看看... – GAMA

2

我想,你需要设置布局文件为:

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

由于您所传递R.layout.main这是给你重新加载相同的布局文件错误。

我不确定,但这可能是问题所在。 还要在传递给适配器的光标中加上_id。

+0

将做到这一点。日Thnx。 – GAMA

+0

整个DOC编辑到最新的代码和ACC。对于您的建议,但仍然无法使用应用程序。 – GAMA

+0

任何帮助表示赞赏! – GAMA