0

I am trying to load data from SQLite database into Android TableLayout. I set up and connected the database already but the tableLayout is not loading the data from 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;
    }

I called the BuildTable() when onCreate():

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();
}

The LogCat shows that the database is created but somehow it does not fetch data into the tableLayout. Any guides?

Thanks in advance.

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

}
  • Make sure your database has some records, put a break point and debug to see how many rows in your cursor. – ductran Jul 30 '14 at 04:23
  • @R4j It is returning me 4 records. But it does not add it into the table –  Jul 30 '14 at 04:32

2 Answers2

0

@20 Cents DB Operations usually take long, therefore is advisable to perform them in another Thread or doing as AsyncTask. I recommend you do it with CursorLoader, a class which inherits from AsyncTaskLoader. How you can manage them, you can see here and a more practical Example which works in addition with Providers, SqliteHelper, etc is here.

What is more important is you learn to manage the methods to override onCreateLoader, onLoadFinished, onLoaderReset.

Kind Regards

p.d. I have another example here

Community
  • 1
  • 1
Gödel77
  • 839
  • 3
  • 15
  • 27
  • Would you mind to provide me an example to fit into my situation? –  Jul 30 '14 at 05:51
  • If you want to fit into your situacion then you should perform your DB Load Initialization in another Thread, so you should write something like `new Handler().post(new Runnable() { @Override public void run() { // Your DB Stuff here } });` another alternative would be to manage as `AsyncTask`, you find an example here http://stackoverflow.com/questions/9671546/asynctask-android-example – Gödel77 Jul 30 '14 at 06:10
  • Try to include ` DatabaseAdapter dbAdapter = new DatabaseAdapter(this); dbAdapter.createDatabase(); this.mDb = new DataBaseHelper(this).getReadableDatabase();` inside the above code, you know `new Handler().post...` – Gödel77 Jul 30 '14 at 06:13
  • Sorry, I don't quite get it. Do you mean by wrapping the whole DBAdapter class in the new Handler() part? –  Jul 30 '14 at 06:14
  • No, I meant, write the two lines, which I said, inside `run` Method, where `Your DB Stuff` is. – Gödel77 Jul 30 '14 at 06:23
  • I've put in my codes already. Would you mind to guide me on how to implement your solution in mine? –  Jul 30 '14 at 06:27
  • Let us [continue this discussion in chat](http://chat.stackoverflow.com/rooms/58315/discussion-between-godel77-and-20-cents). – Gödel77 Jul 30 '14 at 06:29
0

here is a possiblity that tv.setText(mCur.getString(j)) can throw an exception.

Please Ensure that your all data type in database are STRING Type. If any one is different type then use appropiate method.

Cursor getString Definitation : Returns the value of the requested column as a String.

The result and whether this method throws an exception when the column value is null or the column type is not a string type is implementation-defined.

Hradesh Kumar
  • 1,765
  • 15
  • 20
  • I print out the mCur.getString(j) and it returned me the string that I wanted. So can I assume that it's the loading data into tableLayout went wrong? –  Jul 30 '14 at 06:23