Breaking News
Loading...
June 3, 2016

Android Loading SQLite Data Into TableLayout

10:23 AM
In the previous few tutorials we have seen an example relating to TableLayout they are Basic Android Table Layout and Buidling Dynamic TableLayout At Runtime , In this tutorial we are making use of those tutorial concept and extending it to Database , how to fetch or load data from SQLite database into TableLayout .

Download source
Project Detail
Project NameSQLiteTableDemo
Packagecom.pavan.sqlitetabledemo
Minimum SDKAPI 8
Target SDKAPI 17
ThemeHolo Light with Dark Action Bar

1. Database Setup

file :MyDbHelper.java
package com.pavan.sqlitetabledemo;

import android.content.Context;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;

public class MyDbHelper extends SQLiteOpenHelper {
 // TABLE INFORMATTION
 public static final String TABLE_MEMBER = "member";
 public static final String MEMBER_ID = "_id";
 public static final String MEMBER_FIRSTNAME = "firstname";
 public static final String MEMBER_LASTNAME = "lastname";

 // DATABASE INFORMATION
 static final String DB_NAME = "MEMBER.DB";
 static final int DB_VERSION = 1;

 // TABLE CREATION STATEMENT

 private static final String CREATE_TABLE = "create table " + TABLE_MEMBER
 + "(" + MEMBER_ID + " INTEGER PRIMARY KEY AUTOINCREMENT, "
 + MEMBER_FIRSTNAME + " TEXT NOT NULL ," + MEMBER_LASTNAME
 + " TEXT NOT NULL);";

 public MyDbHelper(Context context) {
  super(context, DB_NAME, null, DB_VERSION);
 }

 @Override
 public void onCreate(SQLiteDatabase db) {
  db.execSQL(CREATE_TABLE);
 }

 @Override
 public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
  db.execSQL("DROP TABLE IF EXISTS " + TABLE_MEMBER);
  onCreate(db);
 }
}
file :SQLController.java
package com.pavan.sqlitetabledemo;

 import android.content.ContentValues;
 import android.content.Context;
 import android.database.Cursor;
 import android.database.SQLException;
 import android.database.sqlite.SQLiteDatabase;

 public class SQLController {

 private MyDbHelper dbhelper;
 private Context ourcontext;
 private SQLiteDatabase database;

 public SQLController(Context c) {
  ourcontext = c;
 }

 public SQLController open() throws SQLException {
  dbhelper = new MyDbHelper(ourcontext);
  database = dbhelper.getWritableDatabase();
  return this;
 }

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

 public void insertData(String name, String lname) {
  ContentValues cv = new ContentValues();
  cv.put(MyDbHelper.MEMBER_FIRSTNAME, name);
  cv.put(MyDbHelper.MEMBER_LASTNAME, lname);
  database.insert(MyDbHelper.TABLE_MEMBER, null, cv);
 }

 public Cursor readEntry() {
  String[] allColumns = new String[] { MyDbHelper.MEMBER_ID, MyDbHelper.MEMBER_FIRSTNAME, MyDbHelper.MEMBER_LASTNAME };
  Cursor c = database.query(MyDbHelper.TABLE_MEMBER, allColumns, null, null, null, null, null);
  if (c != null) {
   c.moveToFirst();
  }
  return c;
 }
}

2. XML Layout

file : activity_main.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical" >

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:orientation="horizontal" >

        <EditText
            android:id="@+id/fistname_et_id"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:hint="firstName" />

        <EditText
            android:id="@+id/lastname_et_id"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:hint="lastname" />

        <Button
            android:id="@+id/addmem_btn_id"
            android:layout_width="fill_parent"
            android:layout_height="wrap_content"
            android:text="Add" />
    </LinearLayout>

    <ScrollView
        android:layout_width="match_parent"
        android:layout_height="match_parent" >

        <TableLayout
            android:id="@+id/tableLayout1"
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            android:padding="10dp"
            android:shrinkColumns="*"
            android:stretchColumns="*" >
        </TableLayout>
    </ScrollView>

</LinearLayout>

3. Activity

file :MainActivity.java
package com.pavan.sqlitetabledemo;

import android.app.Activity;
import android.app.ProgressDialog;
import android.database.Cursor;
import android.os.AsyncTask;
import android.os.Bundle;
import android.view.Gravity;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TableLayout;
import android.widget.TableRow;
import android.widget.TableRow.LayoutParams;
import android.widget.TextView;

public class MainActivity extends Activity {

 TableLayout table_layout;
 EditText firstname_et, lastname_et;
 Button addmem_btn;

 SQLController sqlcon;

 ProgressDialog PD;

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

  sqlcon = new SQLController(this);

  firstname_et = (EditText) findViewById(R.id.fistname_et_id);
  lastname_et = (EditText) findViewById(R.id.lastname_et_id);
  addmem_btn = (Button) findViewById(R.id.addmem_btn_id);
  table_layout = (TableLayout) findViewById(R.id.tableLayout1);

  BuildTable();

  addmem_btn.setOnClickListener(new OnClickListener() {

   @Override
   public void onClick(View v) {
    new MyAsync().execute();

   }
  });

 }

 private void BuildTable() {

  sqlcon.open();
  Cursor c = sqlcon.readEntry();

  int rows = c.getCount();
  int cols = c.getColumnCount();

  c.moveToFirst();

  // 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.setBackgroundResource(R.drawable.cell_shape);
    tv.setGravity(Gravity.CENTER);
    tv.setTextSize(18);
    tv.setPadding(0, 5, 0, 5);

    tv.setText(c.getString(j));

    row.addView(tv);

   }

   c.moveToNext();

   table_layout.addView(row);

  }
  sqlcon.close();
 }

 private class MyAsync extends AsyncTask {

  @Override
  protected void onPreExecute() {

   super.onPreExecute();

   table_layout.removeAllViews();

   PD = new ProgressDialog(MainActivity.this);
   PD.setTitle("Please Wait..");
   PD.setMessage("Loading...");
   PD.setCancelable(false);
   PD.show();
  }

  @Override
  protected Void doInBackground(Void... params) {

   String firstname = firstname_et.getText().toString();
   String lastname = lastname_et.getText().toString();

   // inserting data
   sqlcon.open();
   sqlcon.insertData(firstname, lastname);
   // BuildTable();
   return null;
  }

  @Override
  protected void onPostExecute(Void result) {
   super.onPostExecute(result);
   BuildTable();
   PD.dismiss();
  }
 }

}
Source URL: http://www.tutorialsbuzz.com/2014/01/android-loading-sqlite-data-tablelayout.html

0 comments:

Post a Comment

 
Toggle Footer