Android GridView Binding from SQLite Database

  • by
Android GridView Binding from SQLite Database 02

Let’s see how we can bind Android GridView from SQLite Database. This example will be creating a simple SQLite Database named “Companies.db” and allowing users to add a new company name into Android database. Data will be shown on an Android GridView control below the edit text box.  Android GridView Binding from SQLite Database

Android GridView Binding from SQLite Database 01

Create two layout files in your android project with name gridlayout.xml and list_template.xml, edit them as shown below.

res > layout > gridlayout.xml:

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

<EditText
android:id="@+id/txtCompanyName"
android:layout_alignParentTop="true"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginTop="5dp"
android:layout_margin="5dp"
android:hint="Company Name"
android:padding="5dp"
android:textSize="20sp"/>

<LinearLayout
android:layout_margin="5dp"
android:id="@+id/lv1"
android:layout_below="@+id/txtCompanyName"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="horizontal"
android:weightSum="2">

<Button
android:id="@+id/btnAdd"
android:onClick="AddData"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_margin="5dp"
android:layout_weight="1"
android:background="@color/colorPrimaryDark"
android:textColor="#fff"
android:text="ADD" />

<Button
android:id="@+id/btnClear"
android:onClick="ClearData"
android:layout_width="0dp"
android:background="@color/colorAccent"
android:textColor="#fff"
android:layout_height="wrap_content"
android:layout_margin="5dp"
android:layout_weight="1"
android:text="CLEAR" />
</LinearLayout>

<GridView
android:id="@+id/lstView"
android:layout_below="@+id/lv1"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_margin="0dp"
android:numColumns="2"
/>

</RelativeLayout>

res > layout > list_template.xml:

<?xml version="1.0" encoding="utf-8"?>
<TextView xmlns:android="http://schemas.android.com/apk/res/android"
android:id="@+id/txtListElement"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:background="#e4e3e3"
android:padding="5dp"
android:text="Hello World"
android:textColor="#000"
android:textSize="20sp"
android:textStyle="bold">

</TextView>

Now create two java classes in your Android Package with names GridViewActivity.java and DatabaseController.java. Edit them as shown below.

GridViewActivity.java:

package parallelcodes.listviewdatabase;

import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.text.TextUtils;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.GridView;
import android.widget.SimpleCursorAdapter;
import android.widget.Toast;

public class GridViewActivity extends AppCompatActivity {
Button btnAdd, btnClear;
GridView lstView;
EditText txtCompanyName;
DatabaseController dbController;

@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.gridlayout);
btnAdd = (Button) findViewById(R.id.btnAdd);
btnClear = (Button) findViewById(R.id.btnClear);
txtCompanyName = (EditText) findViewById(R.id.txtCompanyName);
lstView = (GridView) findViewById(R.id.lstView);

FillList();
}

public void AddData(View v) {
try {
if (TextUtils.isEmpty(txtCompanyName.getText().toString()))
Toast.makeText(this, "Please enter Company name", Toast.LENGTH_SHORT).show();
else {
dbController = new DatabaseController(this);
String s = dbController.InsertData(txtCompanyName.getText().toString());
Toast.makeText(this, s, Toast.LENGTH_SHORT).show();
FillList();
txtCompanyName.setText("");
}
} catch (Exception ex) {
Toast.makeText(this, ex.getMessage(), Toast.LENGTH_SHORT).show();
}
}

public void ClearData(View v) {
txtCompanyName.setText("");
}

public void FillList() {
try {
int[] id = {R.id.txtListElement};
String[] CompanyName = new String[]{"CompanyName"};
if (dbController == null)
dbController = new DatabaseController(this);
SQLiteDatabase sqlDb = dbController.getReadableDatabase();
Cursor c = dbController.getCompanies();

SimpleCursorAdapter adapter = new SimpleCursorAdapter(this,
R.layout.list_template, c, CompanyName, id, 0);
lstView.setAdapter(adapter);

} catch (Exception ex) {
Toast.makeText(GridViewActivity.this, ex.getMessage().toString(), Toast.LENGTH_SHORT).show();
}
}

}

DatabaseController.java:

package parallelcodes.listviewdatabase;

import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
import android.util.Log;

public class DatabaseController extends SQLiteOpenHelper {
private static final String LOGCAT = null;

public DatabaseController(Context applicationcontext) {
super(applicationcontext, "Companies.db", null, 1);
Log.d(LOGCAT, "Created");
}

@Override
public void onCreate(SQLiteDatabase database) {
String query;
query = "CREATE TABLE IF NOT EXISTS tblCompanies ( _id INTEGER PRIMARY KEY, CompanyName TEXT)";
database.execSQL(query);
}

public String InsertData(String companyName) {
try {
SQLiteDatabase database = this.getWritableDatabase();
String query = "insert into tblCompanies (CompanyName) values ('" + companyName + "')";
database.execSQL(query);
database.close();
return "Added Successfully";
} catch (Exception ex) {
return ex.getMessage().toString();
}

}

@Override
public void onUpgrade(SQLiteDatabase database, int version_old,
int current_version) {
String query;
query = "DROP TABLE IF EXISTS tblCompanies";
database.execSQL(query);
onCreate(database);
}

public Cursor getCompanies() {
try {
String selectQuery = "SELECT * FROM tblCompanies order by _id desc";
SQLiteDatabase database = this.getWritableDatabase();
Cursor cursor = database.rawQuery(selectQuery, null);
return cursor;
} catch (Exception ex) {
return null;
}
}
}

DatabaseController class will create the android sqlite database and methods accepting string values for adding a new company name into database.

GridViewActivity class has method “AddData” which calls databasecontroller’s method to add the company name.

FillList method will populate Android GridView from SQLite Database using dbController.getCompanies() method.

AndroidManifest.xml:

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="parallelcodes.listviewdatabase">

<application
android:allowBackup="true"
android:icon="@mipmap/ic_launcher"
android:label="@string/app_name"
android:roundIcon="@mipmap/ic_launcher_round"
android:supportsRtl="true"
android:theme="@style/AppTheme">
<activity android:name=".GridViewActivity"
android:label="GridView Database">
<intent-filter>
<action android:name="android.intent.action.MAIN" />

<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
</application>

</manifest>

Android GridView Binding from SQLite Database 02

Download Source code : Android Gridview bind from SQLite DB.
Password: listview


Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.