Android将数据从SQLite加载到TableLayout中

时间:2014-07-30 04:17:55

标签: android sqlite

我正在尝试将SQLite数据库中的数据加载到Android TableLayout中。我已经设置并连接了数据库,但tableLayout没有从SQLite加载数据。

 private void BuildTable() {
    try {
        String sql = "SELECT * FROM exercise";
        Cursor mCur = mDb.rawQuery(sql, null);
        if (mCur.getCount() != 0) {
            if (mCur.moveToFirst()) {
                do {
                    int rows = mCur.getCount();
                    int cols = mCur.getColumnCount();
                    // outer for loop
                    for (int i = 0; i < rows; i++) {

                        TableRow row = new TableRow(this);
                        row.setLayoutParams(new LayoutParams(
                                LayoutParams.MATCH_PARENT,
                                LayoutParams.WRAP_CONTENT));

                        // inner for loop
                        for (int j = 0; j < cols; j++) {

                            TextView tv = new TextView(this);
                            tv.setLayoutParams(new LayoutParams(
                                    LayoutParams.WRAP_CONTENT,
                                    LayoutParams.WRAP_CONTENT));
                            tv.setGravity(Gravity.CENTER);
                            tv.setTextSize(18);
                            tv.setPadding(0, 5, 0, 5);

                            tv.setText(mCur.getString(j));
                            row.addView(tv);

                        }
                        table_layout.addView(row);
                    }
                } while (mCur.moveToNext());
            }
        }
    } catch (SQLException mSQLException) {
        throw mSQLException;
    }

我在onCreate()时调用了BuildTable():

TableLayout table_layout;

private SQLiteDatabase mDb;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.tabhost);

    DatabaseAdapter dbAdapter = new DatabaseAdapter(this); dbAdapter.createDatabase();
    this.mDb =  new DataBaseHelper(this).getReadableDatabase();  
    table_layout = (TableLayout) findViewById(R.id.TableLayout);
    BuildTable();
}

LogCat显示数据库已创建,但不知何故它不会将数据提取到tableLayout中。任何指南?

提前致谢。

DataBaseAdapter.java

protected static final String TAG = "DatabaseAdapter";
private final Context mContext;
private SQLiteDatabase mDb;
private DataBaseHelper mDbHelper;

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

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

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

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

DatabaseHelper.java

private static String TAG = "DataBaseHelper"; // Tag just for the LogCat
                                                // window
// destination path (location) of our database on device
private static String DB_PATH = "";
private static String DB_NAME = "schoolAssignment";// Database name
private SQLiteDatabase mDataBase;
private final Context mContext;

public DataBaseHelper(Context context) {
    super(context, DB_NAME, null, 1);// 1? its Database Version
    DB_PATH = "/data/data/" + context.getPackageName() + "/databases/";
    this.mContext = context;
    try
    {   
        createDataBase();
    }
    catch (Exception e)
    {   
        Log.e(TAG,"DatabaseHelper_constuctor createDataBase :" + e.fillInStackTrace());   
    }
}

public void createDataBase() throws IOException {
    // If database not exists copy it from the assets
    Log.e(TAG, "CreateDataBase()");
    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/Database
// Name
private boolean checkDataBase() {
    File dbFile = new File(DB_PATH + DB_NAME);
    Log.e("dbFile", dbFile + "   "+ dbFile.exists());
    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();
}

@Override
public void onCreate(SQLiteDatabase arg0) {
    // TODO Auto-generated method stub

}

@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
    // TODO Auto-generated method stub

}

2 个答案:

答案 0 :(得分:0)

@ 20美分数据库操作通常需要很长时间,因此建议在另一个线程中执行它们或执行AsyncTask。我建议你使用CursorLoader这一继承自AsyncTaskLoader的类。如何管理它们,您可以看到here以及更实用的示例,其中包含ProvidersSqliteHelperhere

更重要的是,您要学会管理覆盖onCreateLoaderonLoadFinishedonLoaderReset的方法。

亲切的问候

Pd积。我有另一个例子here

答案 1 :(得分:0)

这是tv.setText(mCur.getString(j))可以抛出异常的可能性。

请确保您的数据库中的所有数据类型都是STRING Type。如果任何一个是不同的类型,那么使用适当的方法。

Cursor getString Definitation: 以String形式返回所请求列的值。

结果以及当列值为null或列类型不是字符串类型时此方法是否抛出异常是实现定义的。