Android sqlite table layout example

In this Android tip, I am going to show you how to populate data stored in a SQLite data into a TableLayout programmatically.
The TableLayout is a view group to display data in a table format. A table might have many rows and columns. The TableRow class is used to define a row of the table. In the row, you can have multiple columns. When you add views (e.g. TextView) to the row, by default, the first view is in the first column (column index 0); the second view is in the second column. For more information about TableLayout, you read the page: TableLayout.



Now to have an example application on populating SQLite data into TableLayout, you create a new project. Then an empty TableLayout to the activity_main.xml file. Its data rows will be added later in code.

<TableLayout xmlns:android=" http://schemas.android.com/apk/res/android"
   xmlns:tools= "http://schemas.android.com/tools"
   android:id= "@+id/tablelayout"
   android:layout_width= "match_parent"
   android:layout_height= "match_parent"
   android:stretchColumns="*"

   >
</TableLayout>


You create a class called DatabaseHelper that is used to create a database (outletdb), a table (tbloutletdata), and insert data to the table. The tbloutletdata table has three columns: outlet_id, outlet_name, and outlet_type.

public class DatabaseHelper extends SQLiteOpenHelper {
   public static final String DATABASE_NAME = "outletdb";
   public static final int DATABASE_VERSION = 1;
   public static final String TABLE_OUTLET = "tbloutletdata";
   public static final String CREATE_TABLE_OUTLET= "CREATE TABLE IF NOT EXISTS "+ TABLE_OUTLET+ "(outlet_id INTEGER PRIMARY KEY AUTOINCREMENT, outlet_name TEXT NULL, outlet_type TEXT NULL)";
   public static final String DELETE_TABLE_OUTLET="DROP TABLE IF EXISTS " + TABLE_OUTLET;

   public DatabaseHelper(Context context) {
     super(context, DATABASE_NAME, null, DATABASE_VERSION);

   }
   public void onCreate(SQLiteDatabase db) {

     db.execSQL(CREATE_TABLE_OUTLET);

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

     db.execSQL(DELETE_TABLE_OUTLET);
     //Create tables again
     onCreate(db);
   }

   public void insertData(String outlet_name,String outlet_type ){

     // Open the database for writing
     SQLiteDatabase db = this.getWritableDatabase();
     // Start the transaction.
     db.beginTransaction();
     ContentValues values;

     try
     {
        values = new ContentValues();
        values.put("outlet_name",outlet_name);
        values.put("outlet_type",outlet_type);
        // Insert Row
        long i = db.insert(TABLE_OUTLET, null, values);
        Log.i("Insert", i + "");
        // Insert into database successfully.
        db.setTransactionSuccessful();

     }
     catch (SQLiteException e)
     {
        e.printStackTrace();

     }
     finally
     {
        db.endTransaction();
        // End the transaction.
        db.close();
        // Close database
     }

   }


}


In the MainActivity class that hosts the TableLayout, you create an instance of DatabaseHelper, insert sample data to the database, add header row to the table, and add data rows to the table.

public class MainActivity extends Activity {
   private Context context;
   @Override
   protected void onCreate(Bundle savedInstanceState) {
     super.onCreate(savedInstanceState);
     setContentView(R.layout.activity_main);
     context=this;
     // Create DatabaseHelper instance
     DatabaseHelper dataHelper=new DatabaseHelper(context);
   // Insert sample data
     dataHelper.insertData("Kent","HoReCa");
     dataHelper.insertData("FineE","HoReCa");
     dataHelper.insertData("MKent","GTrade");
     dataHelper.insertData("MeviusLove","MTrade");
     dataHelper.insertData("XEMo","HoReCa");
     // Reference to TableLayout
     TableLayout tableLayout=(TableLayout)findViewById(R.id.tablelayout);
     // Add header row
     TableRow rowHeader = new TableRow(context);
     rowHeader.setBackgroundColor(Color.parseColor("#c0c0c0"));
     rowHeader.setLayoutParams(new TableLayout.LayoutParams(TableLayout.LayoutParams.MATCH_PARENT,
           TableLayout.LayoutParams.WRAP_CONTENT));
     String[] headerText={"ID","NAME","TYPE"};
     for(String c:headerText) {
        TextView tv = new TextView(this);
        tv.setLayoutParams(new TableRow.LayoutParams(TableRow.LayoutParams.WRAP_CONTENT,
             TableRow.LayoutParams.WRAP_CONTENT));
        tv.setGravity(Gravity.CENTER);
        tv.setTextSize(18);
        tv.setPadding(5, 5, 5, 5);
        tv.setText(c);
        rowHeader.addView(tv);
     }
     tableLayout.addView(rowHeader);

     // Get data from sqlite database and add them to the table
     // Open the database for reading
     SQLiteDatabase db = dataHelper.getReadableDatabase();
     // Start the transaction.
     db.beginTransaction();

     try
     {
        String selectQuery = "SELECT * FROM "+ DatabaseHelper.TABLE_OUTLET;
        Cursor cursor = db.rawQuery(selectQuery,null);
        if(cursor.getCount() >0)
        {
           while (cursor.moveToNext()) {
             // Read columns data
             int outlet_id= cursor.getInt(cursor.getColumnIndex("outlet_id"));
             String outlet_name= cursor.getString(cursor.getColumnIndex("outlet_name"));
             String outlet_type= cursor.getString(cursor.getColumnIndex("outlet_type"));

             // dara rows
             TableRow row = new TableRow(context);
             row.setLayoutParams(new TableLayout.LayoutParams(TableLayout.LayoutParams.MATCH_PARENT,
                   TableLayout.LayoutParams.WRAP_CONTENT));
             String[] colText={outlet_id+"",outlet_name,outlet_type};
             for(String text:colText) {
                TextView tv = new TextView(this);
                tv.setLayoutParams(new TableRow.LayoutParams(TableRow.LayoutParams.WRAP_CONTENT,
                     TableRow.LayoutParams.WRAP_CONTENT));
                tv.setGravity(Gravity.CENTER);
                tv.setTextSize(16);
                tv.setPadding(5, 5, 5, 5);
                tv.setText(text);
                row.addView(tv);
             }
             tableLayout.addView(row);

           }

        }
        db.setTransactionSuccessful();

     }
     catch (SQLiteException e)
     {
        e.printStackTrace();

     }
     finally
     {
        db.endTransaction();
        // End the transaction.
        db.close();
        // Close database
     }
}



Android-sqlite-table-layout-example

Posted by: Dara | post date: 02-23-2015 | Subject: Android Apps Development

write programming tip




This website intents to provide free and high quality tutorials, examples, exercises and solutions, questions and answers of programming and scripting languages:
C, C++, C#, Java, VB.NET, Python, VBA,PHP & Mysql, SQL, JSP, ASP.NET,HTML, CSS, JQuery, JavaScript and other applications such as MS Excel, MS Access, and MS Word. However, we don't guarantee all things of the web are accurate. If you find any error, please report it then we will take actions to correct it as soon as possible.