Android Listview Binding from SQLite Database

Android Listview Binding from SQLite Database 01

In this post let’s see How we can bind Android Listview from SQLite Database. The application will be providing an Android EditText field to add new data into our Android SQLite database and also displaying the entered data on Listview. Android Listview Binding from SQLite Database.

In your Android studio project make two layout files named activity_main.xml and list_template.xml. Edit these files as below :

res > layout > activity_main.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>

<ListView
android:id="@+id/lstView"
android:layout_below="@+id/lv1"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_margin="0dp"
android:clickable="true"
android:divider="#000"
android:dividerHeight="1dp"
android:listSelector="#006cd9" />

</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>

Android Listview Binding from SQLite Database 01

Now we will create the database class file which will create our SQLite Database and methods to add and fetch the add from our Android SQLite database to view on Listview.

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

Now edit the MainActivity.java file as below :

MainActivity.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.ListView;
import android.widget.SimpleCursorAdapter;
import android.widget.TextView;
import android.widget.Toast;

public class MainActivity extends AppCompatActivity {
Button btnAdd, btnClear;
ListView lstView;
EditText txtCompanyName;
DatabaseController dbController;

@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
btnAdd = (Button) findViewById(R.id.btnAdd);
btnClear = (Button) findViewById(R.id.btnClear);
txtCompanyName = (EditText) findViewById(R.id.txtCompanyName);
lstView = (ListView) 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(MainActivity.this, ex.getMessage().toString(), Toast.LENGTH_SHORT).show();
}
}

}

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

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

FillList method will populate Android ListView 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=".MainActivity">
<intent-filter>
<action android:name="android.intent.action.MAIN" />

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

</manifest>

You can download the source code using the below link. Don’t forget the Password.

Download Link: Download Android ListView SQLite Sourcecode.

Password : Vertex

Android Listview Binding from SQLite Database 01


1 thought on “Android Listview Binding from SQLite Database”

  1. Pingback: Android Import CSV file to SQLite Database • ParallelCodes

Leave a Reply

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