Flickering of ListView item if deleting asynchronously - java

I am trying to remove a ListView item from it asynchronously with a slide animation by using a Content Provider and CursorAdapter, but as I am removing the item by calling a method in Content Provider, the deleted view with deleted data reappears on the screen. The data itself is correctly deleted from the database, but I am not able to fix the flickering issue of deleted view. If I use synchronous deleting from database, the flickering issue is not present. I have tried to implement solution, which have been proposed in the following articles, but couldn't solve the issue:
Correctly animate removing row in ListView?
CursorAdapter backed ListView delete animation "flickers" on delete
I am posting an example of the code to make the issue more empirical. Any help would be appreciated a lot :).
Class AndroidListViewCursorAdaptorActivity:
package com.example.keit.mytestapp;
import android.app.Activity;
import android.content.CursorLoader;
import android.database.Cursor;
import android.net.Uri;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ListView;
import android.widget.Toast;
import com.example.keit.mytestapp.contentprovider.CustomContentProvider;
public class AndroidListViewCursorAdaptorActivity extends Activity implements android.app.LoaderManager.LoaderCallbacks<Cursor> {
private CountriesDbAdapter dbHelper;
private MyCursorAdapter dataAdapter;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
dbHelper = new CountriesDbAdapter(this);
dbHelper.open();
//Clean all data
dbHelper.deleteAllCountries();
//Add some data
dbHelper.insertSomeCountries();
//Generate ListView from SQLite Database
displayListView();
}
private void displayListView() {
Cursor cursor = dbHelper.fetchAllCountries();
// the XML defined views which the data will be bound to
int[] to = new int[] {
R.id.code
};
ListView listView = (ListView) findViewById(R.id.listView1);
// CursorLoader and CursorAdapter are initialized.
getLoaderManager().initLoader(0, null, this);
dataAdapter = new MyCursorAdapter(this, null, 1, listView) {
#Override
public void deleteRow(long id) {
Log.i("DELETE", "Country code: " + id);
//dbHelper.deleteCountry(id);
Uri uri = Uri.parse(CustomContentProvider.CONTENT_URI + "/"
+ id);
getContentResolver().delete(uri, null, null);
}
};
listView.setAdapter(dataAdapter);
listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> listView, View view,
int position, long id) {
dataAdapter.setSelectedItemId(id);
Cursor cursor = (Cursor) listView.getItemAtPosition(position);
// Get the state's capital from this row in the database.
String countryCode =
cursor.getString(cursor.getColumnIndexOrThrow("code"));
Toast.makeText(getApplicationContext(),
countryCode, Toast.LENGTH_SHORT).show();
}
});
}
// Creates a new loader after the initLoader () call.
#Override
public android.content.Loader<Cursor> onCreateLoader(int id, Bundle args) {
String[] projection = {
CountriesDbAdapter.KEY_ROWID,
CountriesDbAdapter.KEY_CODE,
CountriesDbAdapter.KEY_NAME,
CountriesDbAdapter.KEY_CONTINENT,
CountriesDbAdapter.KEY_REGION
};
CursorLoader cursorLoader = new CursorLoader(this,
CustomContentProvider.CONTENT_URI, projection, null, null, null);
return cursorLoader;
}
#Override
public void onLoadFinished(android.content.Loader<Cursor> loader, Cursor cursor) {
dataAdapter.swapCursor(cursor);
}
#Override
public void onLoaderReset(android.content.Loader<Cursor> loader) {
dataAdapter.swapCursor(null);
}
}
Class CustomerContentProvider in package "contentprovider":
package com.example.keit.mytestapp.contentprovider;
import android.content.ContentResolver;
import android.content.ContentValues;
import android.content.UriMatcher;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
import android.database.sqlite.SQLiteQueryBuilder;
import android.net.Uri;
import android.text.TextUtils;
import android.util.Log;
import com.example.keit.mytestapp.CountriesDbAdapter;
import com.example.keit.mytestapp.DatabaseHelper;
public class CustomContentProvider extends android.content.ContentProvider {
// database
private SQLiteOpenHelper dbHelper;
// used for the UriMacher
private static final int DEBTS = 10;
private static final int DEBT_ID = 20;
private static final String AUTHORITY = "com.example.keit.mytestapp.contentprovider";
private static final String BASE_PATH = "mytestapp";
public static final Uri CONTENT_URI = Uri.parse("content://" + AUTHORITY
+ "/" + BASE_PATH);
public static final String CONTENT_TYPE = ContentResolver.CURSOR_DIR_BASE_TYPE
+ "/mytestapp";
public static final String CONTENT_ITEM_TYPE = ContentResolver.CURSOR_ITEM_BASE_TYPE
+ "/countries";
private static final UriMatcher sURIMatcher = new UriMatcher(UriMatcher.NO_MATCH);
static {
sURIMatcher.addURI(AUTHORITY, BASE_PATH, DEBTS);
sURIMatcher.addURI(AUTHORITY, BASE_PATH + "/#", DEBT_ID);
}
#Override
public boolean onCreate() {
dbHelper = new DatabaseHelper(getContext());
return false;
}
#Override
public Cursor query(Uri uri, String[] projection, String selection,
String[] selectionArgs, String sortOrder) {
// Using SQLiteQueryBuilder instead of query() method
SQLiteQueryBuilder queryBuilder = new SQLiteQueryBuilder();
// Set the table
queryBuilder.setTables(CountriesDbAdapter.SQLITE_TABLE);
int uriType = sURIMatcher.match(uri);
switch (uriType) {
case DEBTS:
break;
case DEBT_ID:
// adding the ID to the original query
queryBuilder.appendWhere(CountriesDbAdapter.KEY_ROWID + "="
+ uri.getLastPathSegment());
break;
default:
throw new IllegalArgumentException("Unknown URI: " + uri);
}
SQLiteDatabase db = dbHelper.getWritableDatabase();
Cursor cursor = queryBuilder.query(db, projection, selection,
selectionArgs, null, null, sortOrder);
// make sure that potential listeners are getting notified
cursor.setNotificationUri(getContext().getContentResolver(), uri);
return cursor;
}
#Override
public String getType(Uri uri) {
return null;
}
#Override
public Uri insert(Uri uri, ContentValues values) {
int uriType = sURIMatcher.match(uri);
SQLiteDatabase sqlDB = dbHelper.getWritableDatabase();
int rowsDeleted = 0;
long id = 0;
switch (uriType) {
case DEBTS:
id = sqlDB.insert(CountriesDbAdapter.SQLITE_TABLE, null, values);
break;
default:
throw new IllegalArgumentException("Unknown URI: " + uri);
}
getContext().getContentResolver().notifyChange(uri, null);
return Uri.parse(BASE_PATH + "/" + id);
}
#Override
public int delete(Uri uri, String selection, String[] selectionArgs) {
int uriType = sURIMatcher.match(uri);
SQLiteDatabase sqlDB = dbHelper.getWritableDatabase();
int rowsDeleted = 0;
switch (uriType) {
case DEBTS:
rowsDeleted = sqlDB.delete(CountriesDbAdapter.SQLITE_TABLE, selection,
selectionArgs);
Log.i("MyActivity", "DEBTS ");
break;
case DEBT_ID:
String id = uri.getLastPathSegment();
if (TextUtils.isEmpty(selection)) {
rowsDeleted = sqlDB.delete(CountriesDbAdapter.SQLITE_TABLE,
CountriesDbAdapter.KEY_ROWID + "=" + id,
null);
Log.i("MyActivity", "DEBT_ID");
} else {
rowsDeleted = sqlDB.delete(CountriesDbAdapter.SQLITE_TABLE,
CountriesDbAdapter.KEY_ROWID + "=" + id
+ " and " + selection,
selectionArgs);
Log.i("MyActivity", "ELSE");
}
break;
default:
throw new IllegalArgumentException("Unknown URI: " + uri);
}
getContext().getContentResolver().notifyChange(uri, null);
return rowsDeleted;
}
#Override
public int update(Uri uri, ContentValues values, String selection,
String[] selectionArgs) {
int uriType = sURIMatcher.match(uri);
SQLiteDatabase sqlDB = dbHelper.getWritableDatabase();
int rowsUpdated = 0;
switch (uriType) {
case DEBTS:
rowsUpdated = sqlDB.update(CountriesDbAdapter.SQLITE_TABLE,
values,
selection,
selectionArgs);
break;
case DEBT_ID:
String id = uri.getLastPathSegment();
if (TextUtils.isEmpty(selection)) {
rowsUpdated = sqlDB.update(CountriesDbAdapter.SQLITE_TABLE,
values,
CountriesDbAdapter.KEY_ROWID + "=" + id,
null);
} else {
rowsUpdated = sqlDB.update(CountriesDbAdapter.SQLITE_TABLE,
values,
CountriesDbAdapter.KEY_ROWID + "=" + id
+ " and "
+ selection,
selectionArgs);
}
break;
default:
throw new IllegalArgumentException("Unknown URI: " + uri);
}
getContext().getContentResolver().notifyChange(uri, null);
return rowsUpdated;
}
}
Class CountriesDbAdapter:
package com.example.keit.mytestapp;
import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.SQLException;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
import android.util.Log;
public class CountriesDbAdapter {
public static final String KEY_ROWID = "_id";
public static final String KEY_CODE = "code";
public static final String KEY_NAME = "name";
public static final String KEY_CONTINENT = "continent";
public static final String KEY_REGION = "region";
private static final String TAG = "CountriesDbAdapter";
private DatabaseHelper mDbHelper;
private SQLiteDatabase mDb;
public static final String DATABASE_NAME = "World";
public static final String SQLITE_TABLE = "Country";
public static final int DATABASE_VERSION = 1;
private final Context mCtx;
public static final String DATABASE_CREATE =
"CREATE TABLE if not exists " + SQLITE_TABLE + " (" +
KEY_ROWID + " integer PRIMARY KEY autoincrement," +
KEY_CODE + "," +
KEY_NAME + "," +
KEY_CONTINENT + "," +
KEY_REGION + "," +
" UNIQUE (" + KEY_CODE +"));";
private static class DatabaseHelper extends SQLiteOpenHelper {
DatabaseHelper(Context context) {
super(context, DATABASE_NAME, null, DATABASE_VERSION);
}
#Override
public void onCreate(SQLiteDatabase db) {
Log.w(TAG, DATABASE_CREATE);
db.execSQL(DATABASE_CREATE);
}
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
Log.w(TAG, "Upgrading database from version " + oldVersion + " to "
+ newVersion + ", which will destroy all old data");
db.execSQL("DROP TABLE IF EXISTS " + SQLITE_TABLE);
onCreate(db);
}
}
public CountriesDbAdapter(Context ctx) {
this.mCtx = ctx;
}
public CountriesDbAdapter open() throws SQLException {
mDbHelper = new DatabaseHelper(mCtx);
mDb = mDbHelper.getWritableDatabase();
return this;
}
public void close() {
if (mDbHelper != null) {
mDbHelper.close();
}
}
public long createCountry(String code, String name,
String continent, String region) {
ContentValues initialValues = new ContentValues();
initialValues.put(KEY_CODE, code);
initialValues.put(KEY_NAME, name);
initialValues.put(KEY_CONTINENT, continent);
initialValues.put(KEY_REGION, region);
return mDb.insert(SQLITE_TABLE, null, initialValues);
}
public void deleteCountry (long id) {
int doneDelete = 0;
doneDelete = mDb.delete(SQLITE_TABLE, "_id" + "=" + id , null);
}
public boolean deleteAllCountries() {
int doneDelete = 0;
doneDelete = mDb.delete(SQLITE_TABLE, null , null);
Log.w(TAG, Integer.toString(doneDelete));
return doneDelete > 0;
}
public Cursor fetchCountriesByName(String inputText) throws SQLException {
Log.w(TAG, inputText);
Cursor mCursor = null;
if (inputText == null || inputText.length () == 0) {
mCursor = mDb.query(SQLITE_TABLE, new String[] {KEY_ROWID,
KEY_CODE, KEY_NAME, KEY_CONTINENT, KEY_REGION},
null, null, null, null, null);
}
else {
mCursor = mDb.query(true, SQLITE_TABLE, new String[] {KEY_ROWID,
KEY_CODE, KEY_NAME, KEY_CONTINENT, KEY_REGION},
KEY_NAME + " like '%" + inputText + "%'", null,
null, null, null, null);
}
if (mCursor != null) {
mCursor.moveToFirst();
}
return mCursor;
}
public Cursor fetchAllCountries() {
Cursor mCursor = mDb.query(SQLITE_TABLE, new String[] {KEY_ROWID,
KEY_CODE, KEY_NAME, KEY_CONTINENT, KEY_REGION},
null, null, null, null, null);
if (mCursor != null) {
mCursor.moveToFirst();
}
return mCursor;
}
public void insertSomeCountries() {
createCountry("AFG","Afghanistan","Asia","Southern and Central Asia");
createCountry("ALB","Albania","Europe","Southern Europe");
createCountry("DZA","Algeria","Africa","Northern Africa");
createCountry("ASM","American Samoa","Oceania","Polynesia");
createCountry("AND","Andorra","Europe","Southern Europe");
createCountry("AGO","Angola","Africa","Central Africa");
createCountry("AIA","Anguilla","North America","Caribbean");
}
}
Class MyCursorAdapter:
package com.example.keit.mytestapp;
import android.content.Context;
import android.database.Cursor;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.ViewTreeObserver;
import android.widget.CursorAdapter;
import android.widget.ImageButton;
import android.widget.ListView;
import android.widget.TextView;
import java.util.HashMap;
public class MyCursorAdapter extends CursorAdapter {
private long selectedItemId;
private long previouslySelectedItemId;
private ListView adapterListView;
private static final int MOVE_DURATION = 300;
HashMap<Long, Integer> mItemIdTopMap = new HashMap<Long, Integer>();
public MyCursorAdapter(Context context, Cursor cursor, int flags) {
super(context, cursor, 0);
}
// A customer constructor for passing ListView inside a view in addition to default parameters.
public MyCursorAdapter(Context context, Cursor cursor, int flags, ListView listView) {
super(context, cursor, 0);
adapterListView = listView;
}
// The newView method is used to inflate a new view and return it,
// you don't bind any data to the view at this point.
#Override
public View newView(Context context, Cursor cursor, ViewGroup parent) {
return LayoutInflater.from(context).inflate(R.layout.country_info, parent, false);
}
// The bindView method is used to bind all data to a given view
// such as setting the text on a TextView.
#Override
public void bindView(View view, final Context context, Cursor cursor) {
TextView countryCodeView = (TextView) view.findViewById(R.id.code);
String countryCode = cursor.getString(cursor.getColumnIndexOrThrow(CountriesDbAdapter.KEY_CODE));
countryCodeView.setText(countryCode);
// Listener is created for "Delete" button.
ImageButton deleteItem = (ImageButton) view.findViewById(R.id.delete_item);
deleteItem.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(final View view) {
Log.i("onClick", "Executed");
adapterListView.requestDisallowInterceptTouchEvent(true); // Will disallow touch events.
adapterListView.setEnabled(false); // Will disable list view (e.g. to avoid scrolling).
final View activeView = (View) view.getParent(); //ListView item parent view is returned.
if (activeView != null) {
long duration = 800;
float endX = activeView.getWidth();
float endAlpha = 0; // Opacity will be set to 0.
activeView.animate().setDuration(duration).
alpha(endAlpha).translationX(endX).
withEndAction(new Runnable() {
#Override
public void run() {
activeView.setAlpha(1);
activeView.setTranslationX(0);
animateRemoval(adapterListView, activeView);
}
});
Log.i("FAFA", "Animation ended");
// notifyDataSetChanged();
}
}
});
}
// The method sets a global temporary value of selected item's id.
public void setSelectedItemId(long id) {
previouslySelectedItemId = selectedItemId;
selectedItemId = id;
}
// The method returns a global temporary value of selected item's id.
public long getSelectedItemId() {
return selectedItemId;
}
/**
* The method will be always be overwritten by calling class to handle database manipulation in activity.
* #param id
*/
public void deleteRow(long id) {
}
private void animateRemoval(final ListView listview, final View viewToRemove) {
int firstVisiblePosition = listview.getFirstVisiblePosition();
for (int i = 0; i < listview.getChildCount(); ++i) {
View child = listview.getChildAt(i);
if (child != viewToRemove) {
int position = firstVisiblePosition + i;
long itemId = getItemId(position);
mItemIdTopMap.put(itemId, child.getTop());
}
}
final int position = adapterListView.getPositionForView(viewToRemove);
final ViewTreeObserver observer = listview.getViewTreeObserver();
observer.addOnPreDrawListener(new ViewTreeObserver.OnPreDrawListener() {
public boolean onPreDraw() {
observer.removeOnPreDrawListener(this);
boolean firstAnimation = true;
int firstVisiblePosition = listview.getFirstVisiblePosition();
for (int i = 0; i < listview.getChildCount(); ++i) {
final View child = listview.getChildAt(i);
int position = firstVisiblePosition + i;
long itemId = getItemId(position);
Integer startTop = mItemIdTopMap.get(itemId);
int top = child.getTop();
if (startTop != null) {
if (startTop != top) {
int delta = startTop - top;
child.setTranslationY(delta);
child.animate().setDuration(MOVE_DURATION).translationY(0);
if (firstAnimation) {
child.animate().withEndAction(new Runnable() {
public void run() {
listview.requestDisallowInterceptTouchEvent(false); // Will allow touch events.
listview.setEnabled(true); // Will enable list view (e.g. to avoid scrolling).
}
});
firstAnimation = false;
}
}
} else {
// Animate new views along with the others. The catch is that they did not
// exist in the start state, so we must calculate their starting position
// based on neighboring views.
int childHeight = child.getHeight() + listview.getDividerHeight();
startTop = top + (i > 0 ? childHeight : -childHeight);
int delta = startTop - top;
child.setTranslationY(delta);
child.animate().setDuration(MOVE_DURATION).translationY(0);
if (firstAnimation) {
child.animate().withEndAction(new Runnable() {
public void run() {
listview.requestDisallowInterceptTouchEvent(false); // Will allow touch events.
listview.setEnabled(true); // Will enable list view (e.g. to avoid scrolling).
}
});
firstAnimation = false;
}
}
}
CustomCursorWrapper cursorWrapper = new CustomCursorWrapper(getCursor(), position);
swapCursor(cursorWrapper);
deleteRow(selectedItemId);
mItemIdTopMap.clear();
return true;
}
});
}
}
Class CustomCursorWrapper:
package com.example.keit.mytestapp;
import android.database.Cursor;
import android.database.CursorWrapper;
public class CustomCursorWrapper extends CursorWrapper
{
private int mVirtualPosition;
private int mHiddenPosition;
public CustomCursorWrapper(Cursor cursor, int hiddenPosition)
{
super(cursor);
mVirtualPosition = -1;
mHiddenPosition = hiddenPosition;
}
#Override
public int getCount()
{
return super.getCount() - 1;
}
#Override
public int getPosition()
{
return mVirtualPosition;
}
#Override
public boolean move(int offset)
{
return moveToPosition(getPosition() + offset);
}
#Override
public boolean moveToFirst()
{
return moveToPosition(0);
}
#Override
public boolean moveToLast()
{
return moveToPosition(getCount() - 1);
}
#Override
public boolean moveToNext()
{
return moveToPosition(getPosition() + 1);
}
#Override
public boolean moveToPosition(int position)
{
mVirtualPosition = position;
int cursorPosition = position;
if (cursorPosition >= mHiddenPosition)
{
cursorPosition++;
}
return super.moveToPosition(cursorPosition);
}
#Override
public boolean moveToPrevious()
{
return moveToPosition(getPosition() - 1);
}
#Override
public boolean isBeforeFirst()
{
return getPosition() == -1 || getCount() == 0;
}
#Override
public boolean isFirst()
{
return getPosition() == 0 && getCount() != 0;
}
#Override
public boolean isLast()
{
int count = getCount();
return getPosition() == (count - 1) && count != 0;
}
#Override
public boolean isAfterLast()
{
int count = getCount();
return getPosition() == count || count == 0;
}
}
Class DatabaseHelper:
package com.example.keit.mytestapp;
import android.content.Context;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
public class DatabaseHelper extends SQLiteOpenHelper {
// If you change the database schema, you must increment the database version.
public DatabaseHelper(Context context) {
super(context, CountriesDbAdapter.DATABASE_NAME, null, CountriesDbAdapter.DATABASE_VERSION);
}
// Creates SQL Lite database tables
public void onCreate(SQLiteDatabase db) {
db.execSQL(CountriesDbAdapter.DATABASE_CREATE);
}
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
// This database is only a cache for online data, so its upgrade policy is
// to simply to discard the data and start over
//db.execSQL(DatabaseContract.Debts.SQL_DELETE_TABLE);
onCreate(db);
}
public void onDowngrade(SQLiteDatabase db, int oldVersion, int newVersion) {
onUpgrade(db, oldVersion, newVersion);
}
}
country_info.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="wrap_content"
android:orientation="horizontal"
android:descendantFocusability="blocksDescendants"
android:background="#android:color/darker_gray"
android:padding="6dip">
<TextView
android:id="#+id/textView1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentLeft="true"
android:layout_alignParentTop="true"
android:text="Code: "
android:textAppearance="?android:attr/textAppearanceMedium" />
<TextView
android:id="#+id/code"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="TextView" />
<ImageButton
android:id="#+id/delete_item"
android:layout_width="40dp"
android:layout_height="fill_parent"
android:scaleType="centerInside"
android:src="#mipmap/ic_launcher"
android:focusable="false"
android:focusableInTouchMode="false"
android:background="#android:color/transparent"/>
</LinearLayout>
main.xml:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent" android:layout_height="fill_parent"
android:orientation="vertical">
<TextView android:layout_width="fill_parent"
android:layout_height="wrap_content" android:padding="10dp"
android:text="#string/some_text" android:textSize="20sp" />
<ListView android:id="#+id/listView1" android:layout_width="fill_parent"
android:layout_height="fill_parent" />
</LinearLayout>

Related

Can't find SQL column in android project

I have two classes:
Database class:
package com.qstra.soamazingtodoapp;
import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
import android.util.Log;
public class DBAdapter {
private static final String TAG = "DBAdapter"; // used for logging database
// version changes
// Field Names:
public static final String KEY_ROWID = "_id";
public static final String KEY_TASK = "task";
public static final String KEY_DATE = "date";
public static final String KEY_HOUR = "hour";
public static final String KEY_MINUTE = "minute";
public static final String[] ALL_KEYS = new String[] { KEY_ROWID, KEY_TASK,
KEY_DATE, KEY_HOUR, KEY_MINUTE };
// Column Numbers for each Field Name:
public static final int COL_ROWID = 0;
public static final int COL_TASK = 1;
public static final int COL_DATE = 2;
public static final int COL_HOUR = 3;
public static final int COL_MINUTE = 4;
// DataBase info:
public static final String DATABASE_NAME = "dbToDo";
public static final String DATABASE_TABLE = "mainToDo";
public static final int DATABASE_VERSION = 2; // The version number must be
// incremented each time a
// change to DB structure
// occurs.
// SQL statement to create database
private static final String DATABASE_CREATE_SQL = "CREATE TABLE "
+ DATABASE_TABLE + " (" + KEY_ROWID
+ " INTEGER PRIMARY KEY AUTOINCREMENT, " + KEY_TASK
+ " TEXT NOT NULL, " + KEY_DATE + " TEXT" + KEY_HOUR + " TEXT"
+ KEY_MINUTE + " TEXT" + ");";
private final Context context;
private DatabaseHelper myDBHelper;
private SQLiteDatabase db;
public DBAdapter(Context ctx) {
this.context = ctx;
myDBHelper = new DatabaseHelper(context);
}
// Open the database connection.
public DBAdapter open() {
db = myDBHelper.getWritableDatabase();
return this;
}
// Close the database connection.
public void close() {
myDBHelper.close();
}
// Add a new set of values to be inserted into the database.
public long insertRow(String task, String date, String hour, String minute) {
ContentValues initialValues = new ContentValues();
initialValues.put(KEY_TASK, task);
initialValues.put(KEY_DATE, date);
initialValues.put(KEY_HOUR, hour);
initialValues.put(KEY_MINUTE, minute);
// Insert the data into the database.
return db.insert(DATABASE_TABLE, null, initialValues);
}
// Delete a row from the database, by rowId (primary key)
public boolean deleteRow(long rowId) {
String where = KEY_ROWID + "=" + rowId;
return db.delete(DATABASE_TABLE, where, null) != 0;
}
public void deleteAll() {
Cursor c = getAllRows();
long rowId = c.getColumnIndexOrThrow(KEY_ROWID);
if (c.moveToFirst()) {
do {
deleteRow(c.getLong((int) rowId));
} while (c.moveToNext());
}
c.close();
}
// Return all data in the database.
public Cursor getAllRows() {
String where = null;
Cursor c = db.query(true, DATABASE_TABLE, ALL_KEYS, where, null, null,
null, null, null);
if (c != null) {
c.moveToFirst();
}
return c;
}
// Get a specific row (by rowId)
public Cursor getRow(long rowId) {
String where = KEY_ROWID + "=" + rowId;
Cursor c = db.query(true, DATABASE_TABLE, ALL_KEYS, where, null, null,
null, null, null);
if (c != null) {
c.moveToFirst();
}
return c;
}
// Change an existing row to be equal to new data.
public boolean updateRow(long rowId, String task, String date, String hour, String minute) {
String where = KEY_ROWID + "=" + rowId;
ContentValues newValues = new ContentValues();
newValues.put(KEY_TASK, task);
newValues.put(KEY_DATE, date);
newValues.put(KEY_HOUR, hour);
newValues.put(KEY_MINUTE, minute);
// Insert it into the database.
return db.update(DATABASE_TABLE, newValues, where, null) != 0;
}
private static class DatabaseHelper extends SQLiteOpenHelper {
DatabaseHelper(Context context) {
super(context, DATABASE_NAME, null, DATABASE_VERSION);
}
#Override
public void onCreate(SQLiteDatabase _db) {
_db.execSQL(DATABASE_CREATE_SQL);
}
#Override
public void onUpgrade(SQLiteDatabase _db, int oldVersion, int newVersion) {
Log.w(TAG, "Upgrading application's database from version "
+ oldVersion + " to " + newVersion
+ ", which will destroy all old data!");
// Destroy old database:
_db.execSQL("DROP TABLE IF EXISTS " + DATABASE_TABLE);
// Recreate new database:
onCreate(_db);
}
}
}
MainActivity class:
package com.qstra.soamazingtodoapp;
import com.qstratwo.soamazingtodoapp.R;
import android.app.Activity;
import android.app.Dialog;
import android.app.TimePickerDialog;
import android.database.Cursor;
import android.os.Bundle;
import android.text.TextUtils;
import android.text.format.Time;
import android.view.View;
import android.widget.AdapterView;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.SimpleCursorAdapter;
import android.widget.TimePicker;
import android.widget.Toast;
public class MainActivity extends Activity {
Time today = new Time(Time.getCurrentTimezone());
DBAdapter myDb;
EditText etTasks;
static final int DIALOG_ID = 0;
int hour_x;
int minute_x;
String string_hour_x, string_minute_x="None";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
etTasks = (EditText) findViewById(R.id.editText1);
openDB();
listViewItemClick();
listViewItemLongClick();
populateListView();
// setNotification();
}
#Override
protected Dialog onCreateDialog(int idD){
if (idD== DIALOG_ID){
return new TimePickerDialog(MainActivity.this, kTimePickerListener, hour_x,minute_x, false);
}
return null;
}
protected TimePickerDialog.OnTimeSetListener kTimePickerListener =
new TimePickerDialog.OnTimeSetListener() {
#Override
public void onTimeSet(TimePicker view, int hourOfDay, int minute) {
hour_x=hourOfDay;
minute_x=minute;
string_hour_x = Integer.toString(hour_x);
string_minute_x = Integer.toString(minute_x);
Toast.makeText(MainActivity.this, hour_x+" : "+ minute_x,Toast.LENGTH_LONG).show();
}
};
public void setNotification(View v) {
showDialog(DIALOG_ID);
}
private void openDB() {
myDb = new DBAdapter(this);
myDb.open();
}
public void onClick_AddTask (View v) {
today.setToNow();
String timestamp = today.format("%Y-%m-%d %H:%m:%s");
if(!TextUtils.isEmpty(etTasks.getText().toString())) {
myDb.insertRow(etTasks.getText().toString(),timestamp,string_hour_x, string_minute_x);
}
populateListView();
}
private void populateListView() {
Cursor cursor = myDb.getAllRows();
String[] fromFieldNames=new String[] {
DBAdapter.KEY_ROWID, DBAdapter.KEY_TASK };
int[] toViewIDs = new int[] {
R.id.textViewItemNumber, R.id.textViewItemTasks};
SimpleCursorAdapter myCursorAdapter;
myCursorAdapter = new SimpleCursorAdapter(getBaseContext(), R.layout.item_layout, cursor, fromFieldNames, toViewIDs, 0);
ListView myList = (ListView) findViewById(R.id.listViewTask);
myList.setAdapter(myCursorAdapter);
}
private void updateTask(long id){
Cursor cursor = myDb.getRow(id);
if (cursor.moveToFirst()){
String task = etTasks.getText().toString(); // POBIERANIE Z TEXTFIELD
today.setToNow();
String date = today.format("%Y-%m-%d %H:%m");
// String string_minute_x= Integer.toString(minute_x);
// String string_houte_x=Integer.toString(hour_x);
myDb.updateRow(id, task, date, string_hour_x, string_minute_x );
}
cursor.close();
}public void onClick_DeleteTasks(View v) {
myDb.deleteAll();
populateListView();
}
public void onClick_AppClose(View v) {
moveTaskToBack(true);
MainActivity.this.finish();
}
public void listViewItemLongClick(){
ListView myList = (ListView) findViewById(R.id.listViewTask);
myList.setOnItemLongClickListener(new AdapterView.OnItemLongClickListener() {
#Override
public boolean onItemLongClick(AdapterView<?> arg0, View arg1,
int arg2, long id) {
// TODO Auto-generated method stub
myDb.deleteRow(id);
populateListView();
return false;
}
});
}
private void listViewItemClick(){
ListView myList = (ListView) findViewById(R.id.listViewTask);
myList.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> arg0, View arg1, int arg2, long id) {
updateTask(id);
populateListView();
displayToast(id);
}
});
}
private void displayToast(long id){
Cursor cursor = myDb.getRow(id);
if(cursor.moveToFirst()) {
long idDB = cursor.getLong(DBAdapter.COL_ROWID);
String task = cursor.getString(DBAdapter.COL_TASK);
String date = cursor.getString(DBAdapter.COL_DATE);
String message = "ID: " + idDB + "\n" + "Task: " + task + "\n" + "Date: " + date;
Toast.makeText(MainActivity.this, message, Toast.LENGTH_LONG).show();
}
cursor.close();
}
}
(getting id and text from texfield to database works fine but..)
I'm trying to get hour and minutes values from TimePickerDialog and insert in to database but it seems not working.
Screen shot from log cat:
Why can't it see column named 'hour'?
Add commas in your statement to create database
// SQL statement to create database
private static final String DATABASE_CREATE_SQL = "CREATE TABLE "
+ DATABASE_TABLE + " (" + KEY_ROWID
+ " INTEGER PRIMARY KEY AUTOINCREMENT, " + KEY_TASK
+ " TEXT NOT NULL, " + KEY_DATE + " TEXT," + KEY_HOUR + " TEXT,"
+ KEY_MINUTE + " TEXT" + ")";

Total price using rawQuery in android [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 8 years ago.
Improve this question
I've been trying to get the price value from the database and try to make a grand total. I used the rawQuery but always crashed.I think theres a problem in my rawQuery..i still cant get the total after many times i've tried..
this is the code:
DBAdapter
import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
import android.util.Log;
// ------------------------------------ DBAdapter.java ---------------------------------------------
// TO USE:
// Change the package (at top) to match your project.
// Search for "TODO", and make the appropriate changes.
public class DBAdapter {
/////////////////////////////////////////////////////////////////////
// Constants & Data
/////////////////////////////////////////////////////////////////////
// For logging:
private static final String TAG = "DBAdapter";
// DB Fields
public static final String KEY_ROWID = "_id";
public static final int COL_ROWID = 0;
/*
* CHANGE 1:
*/
// TODO: Setup your fields here:
public static final String KEY_NAME = "name";
public static final String KEY_QUANTITY = "studentnum";
public static final String KEY_PRICE = "favcolour";
// TODO: Setup your field numbers here (0 = KEY_ROWID, 1=...)
public static final int COL_NAME = 1;
public static final int COL_QUANTITY = 2;
public static final int COL_PRICE = 3;
public static final String[] ALL_KEYS = new String[] {KEY_ROWID, KEY_NAME, KEY_QUANTITY, KEY_PRICE};
// DB info: it's name, and the table we are using (just one).
public static final String DATABASE_NAME = "MyDb";
public static final String DATABASE_TABLE = "mainTable";
// Track DB version if a new version of your app changes the format.
public static final int DATABASE_VERSION = 2;
private static final String DATABASE_CREATE_SQL =
"create table " + DATABASE_TABLE
+ " (" + KEY_ROWID + " integer primary key autoincrement, "
/*
* CHANGE 2:
*/
// TODO: Place your fields here!
// + KEY_{...} + " {type} not null"
// - Key is the column name you created above.
// - {type} is one of: text, integer, real, blob
// (http://www.sqlite.org/datatype3.html)
// - "not null" means it is a required field (must be given a value).
// NOTE: All must be comma separated (end of line!) Last one must have NO comma!!
+ KEY_NAME + " text not null, "
+ KEY_QUANTITY + " integer not null, "
+ KEY_PRICE + " string not null"
// Rest of creation:
+ ");";
// Context of application who uses us.
private final Context context;
private DatabaseHelper myDBHelper;
private SQLiteDatabase db;
/////////////////////////////////////////////////////////////////////
// Public methods:
/////////////////////////////////////////////////////////////////////
public DBAdapter(Context ctx) {
this.context = ctx;
myDBHelper = new DatabaseHelper(context);
}
// Open the database connection.
public DBAdapter open() {
db = myDBHelper.getWritableDatabase();
return this;
}
// Close the database connection.
public void close() {
myDBHelper.close();
}
// Add a new set of values to the database.
public long insertRow(String name, String studentNum, String favColour) {
/*
* CHANGE 3:
*/
// TODO: Update data in the row with new fields.
// TODO: Also change the function's arguments to be what you need!
// Create row's data:
ContentValues initialValues = new ContentValues();
initialValues.put(KEY_NAME, name);
initialValues.put(KEY_QUANTITY, studentNum);
initialValues.put(KEY_PRICE, favColour);
// Insert it into the database.
return db.insert(DATABASE_TABLE, null, initialValues);
}
// Delete a row from the database, by rowId (primary key)
public boolean deleteRow(long rowId) {
String where = KEY_ROWID + "=" + rowId;
return db.delete(DATABASE_TABLE, where, null) != 0;
}
public Cursor getTotalPrice() {
Cursor c = db.rawQuery("SELECT SUM("+ KEY_PRICE +")from " + DATABASE_TABLE, null);
return c;
}
public void deleteAll() {
Cursor c = getAllRows();
long rowId = c.getColumnIndexOrThrow(KEY_ROWID);
if (c.moveToFirst()) {
do {
deleteRow(c.getLong((int) rowId));
} while (c.moveToNext());
}
c.close();
}
// Return all data in the database.
public Cursor getAllRows() {
String where = null;
Cursor c = db.query(true, DATABASE_TABLE, ALL_KEYS,
where, null, null, null, null, null);
if (c != null) {
c.moveToFirst();
}
return c;
}
// Get a specific row (by rowId)
public Cursor getRow(long rowId) {
String where = KEY_ROWID + "=" + rowId;
Cursor c = db.query(true, DATABASE_TABLE, ALL_KEYS,
where, null, null, null, null, null);
if (c != null) {
c.moveToFirst();
}
return c;
}
// Change an existing row to be equal to new data.
public boolean updateRow(long rowId, String name, int studentNum, String favColour) {
String where = KEY_ROWID + "=" + rowId;
/*
* CHANGE 4:
*/
// TODO: Update data in the row with new fields.
// TODO: Also change the function's arguments to be what you need!
// Create row's data:
ContentValues newValues = new ContentValues();
newValues.put(KEY_NAME, name);
newValues.put(KEY_QUANTITY, studentNum);
newValues.put(KEY_PRICE, favColour);
// Insert it into the database.
return db.update(DATABASE_TABLE, newValues, where, null) != 0;
}
/////////////////////////////////////////////////////////////////////
// Private Helper Classes:
/////////////////////////////////////////////////////////////////////
/**
* Private class which handles database creation and upgrading.
* Used to handle low-level database access.
*/
private static class DatabaseHelper extends SQLiteOpenHelper
{
DatabaseHelper(Context context) {
super(context, DATABASE_NAME, null, DATABASE_VERSION);
}
#Override
public void onCreate(SQLiteDatabase _db) {
_db.execSQL(DATABASE_CREATE_SQL);
}
#Override
public void onUpgrade(SQLiteDatabase _db, int oldVersion, int newVersion) {
Log.w(TAG, "Upgrading application's database from version " + oldVersion
+ " to " + newVersion + ", which will destroy all old data!");
// Destroy old database:
_db.execSQL("DROP TABLE IF EXISTS " + DATABASE_TABLE);
// Recreate new database:
onCreate(_db);
}
}
}
Listprice:
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.support.v7.app.ActionBarActivity;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.*;
/**
* Created by User on 6/2/2015.
*/
public class Listprice extends ActionBarActivity {
DBAdapter myDb;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.listprice);
openDB();
TextView textView = (TextView) findViewById(R.id.order90);
TextView textView1 = (TextView) findViewById(R.id.quan90);
TextView textView2 = (TextView) findViewById(R.id.price90);
TextView textView3 = (TextView) findViewById(R.id.totalprice);
Bundle extras = getIntent().getExtras();
if (extras != null) {
String newText = extras.getString("firstmessage");
String newText1 = extras.getString("secondmessage");
String newText2 = extras.getString("thirdmessage");
if (newText != null) {
textView.setText(newText);
}
if (newText1 != null) {
textView1.setText(newText1);
}
if (newText2 != null) {
textView2.setText(newText2);
}
}
String num1 = textView.getText().toString().trim();
int num2 = Integer.parseInt(textView1.getText().toString());
int num3 = Integer.parseInt(textView2.getText().toString());
int num4 = num2 * num3;
registerListClickCallBack();
myDb.insertRow(num1, "Quantity = " + num2, ""+num4);
populateListViewFromDB();
Cursor sum=myDb.getTotalPrice();
textView3.setText(""+sum);
}
private void populateListViewFromDB() {
Cursor cursor = myDb.getAllRows();
//Query for the record we just added.
//Use the ID:
startManagingCursor(cursor);
String[] fromFieldNames = new String[]
{DBAdapter.KEY_NAME, DBAdapter.KEY_QUANTITY, DBAdapter.KEY_PRICE};
int[] toViewIDs = new int[]
{R.id.item_name, R.id.quantities, R.id.pricest};
SimpleCursorAdapter myCursorAdapter =
new SimpleCursorAdapter(
this,
R.layout.item_layout,
cursor,
fromFieldNames,
toViewIDs
);
// Set the adapter for the list view
ListView myList = (ListView) findViewById(R.id.listViewFromDB);
myList.setAdapter(myCursorAdapter);
}
private void openDB(){
myDb = new DBAdapter(this);
myDb.open();
}
#Override
protected void onDestroy() {
super.onDestroy();
closeDB();
}
private void closeDB() {
myDb.close();
}
private void registerListClickCallBack() {
ListView myList = (ListView) findViewById(R.id.listViewFromDB);
myList.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View viewClicked,
int position, long idInDB) {
updateItemForId(idInDB);
}
});
}
private void updateItemForId(final long idInDB) {
final Cursor cursor = myDb.getRow(idInDB);
if (cursor.moveToFirst()) {
AlertDialog.Builder alertDialog = new AlertDialog.Builder(Listprice.this);
// Setting Dialog Title
alertDialog.setTitle("Confirm Delete...");
// Setting Dialog Message
alertDialog.setMessage("Are you sure you want delete this?");
// Setting Positive "Yes" Button
alertDialog.setPositiveButton("YES", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog,int which) {
// Write your code here to invoke YES event
Toast.makeText(getApplicationContext(), "You clicked on YES", Toast.LENGTH_SHORT).show();
myDb.deleteRow(idInDB);
populateListViewFromDB();
}
});
// Setting Negative "NO" Button
alertDialog.setNegativeButton("NO", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
// Write your code here to invoke NO event
Toast.makeText(getApplicationContext(), "You clicked on NO", Toast.LENGTH_SHORT).show();
dialog.cancel();
}
});
// Showing Alert Message
alertDialog.show();
}
cursor.close();
populateListViewFromDB();
}
public void clear(View view) {
myDb.deleteAll();
populateListViewFromDB();
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.menu_main, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
//noinspection SimplifiableIfStatement
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
public void addFood(View view) {
Intent gotofood = new Intent(this, food.class);
startActivity(gotofood);
}
public void addDrinks(View view) {
Intent gotodrinks = new Intent(this, drink.class);
startActivity(gotodrinks);
}
public void gotomainmaenu(View view) {
Intent gotomain = new Intent(this, MainActivity.class);
startActivity(gotomain);
}
}
It sounds like you want the sum of each item's price multiplied by that item's quantity. If so, this should work:
public double getTotalPrice() {
String sql = "select sum(" + KEY_QUANTITY + " * " + KEY_PRICE + ") from "
+ DATABASE_TABLE;
Cursor cursor = db.rawQuery(sql, null);
if (cursor.moveToFirst()) {
return cursor.getDouble(0);
}
return 0;
}

How to store and fetch list view data from sqlite in android?

I have created a simple demo in which I have simply stored the two value that is first name and last name in sqlite and display that in list view.But when I tried two add more value like phone no.address,state,country etc . I got error.and it display the message like could not read the row and column data.
please help me two add 9 or 10 value and display in list view.here is my code.
AddActivity.Java
public class AddActivity extends Activity implements OnClickListener {
private Button btn_save;
private EditText edit_first,edit_last,phoneNo;
private DbHelper mHelper;
private SQLiteDatabase dataBase;
private String id,fname,lname,pno;
private boolean isUpdate;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.add);
btn_save=(Button)findViewById(R.id.save_btn);
edit_first=(EditText)findViewById(R.id.frst_editTxt);
edit_last=(EditText)findViewById(R.id.last_editTxt);
phoneNo=(EditText)findViewById(R.id.phoneNo);
isUpdate=getIntent().getExtras().getBoolean("update");
if(isUpdate)
{
id=getIntent().getExtras().getString("ID");
fname=getIntent().getExtras().getString("Fname");
lname=getIntent().getExtras().getString("Lname");
pno=getIntent().getExtras().getString("Pno");
edit_first.setText(fname);
edit_last.setText(lname);
phoneNo.setText(pno);
}
btn_save.setOnClickListener(this);
mHelper=new DbHelper(this);
}
public void onClick(View v) {
fname=edit_first.getText().toString().trim();
lname=edit_last.getText().toString().trim();
pno=phoneNo.getText().toString().trim();
if(fname.length()>0 && lname.length()>0)
{
saveData();
}
else
{
AlertDialog.Builder alertBuilder=new AlertDialog.Builder(AddActivity.this);
alertBuilder.setTitle("Invalid Data");
alertBuilder.setMessage("Please, Enter valid data");
alertBuilder.setPositiveButton("Ok", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
dialog.cancel();
}
});
alertBuilder.create().show();
}
}
private void saveData(){
dataBase=mHelper.getWritableDatabase();
ContentValues values=new ContentValues();
values.put(DbHelper.KEY_FNAME,fname);
values.put(DbHelper.KEY_LNAME,lname );
values.put(DbHelper.KEY_PHONENO,pno );
System.out.println("");
if(isUpdate)
{
dataBase.update(DbHelper.TABLE_NAME, values, DbHelper.KEY_ID+"="+id, null);
}
else
{
dataBase.insert(DbHelper.TABLE_NAME, null, values);
}
dataBase.close();
finish();
}
}
DisplayAdapter.java
public class DisplayAdapter extends BaseAdapter {
private Context mContext;
private ArrayList<String> id;
private ArrayList<String> firstName;
private ArrayList<String> lastName;
private ArrayList<String> phoneNo;
public DisplayAdapter(Context c, ArrayList<String> id,ArrayList<String> fname, ArrayList<String> lname,ArrayList<String> pno) {
this.mContext = c;
this.id = id;
this.firstName = fname;
this.lastName = lname;
this.phoneNo = pno;
}
public int getCount() {
// TODO Auto-generated method stub
return id.size();
}
public Object getItem(int position) {
// TODO Auto-generated method stub
return null;
}
public long getItemId(int position) {
// TODO Auto-generated method stub
return 0;
}
public View getView(int pos, View child, ViewGroup parent) {
Holder mHolder;
LayoutInflater layoutInflater;
if (child == null) {
layoutInflater = (LayoutInflater) mContext.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
child = layoutInflater.inflate(R.layout.listcell, null);
mHolder = new Holder();
mHolder.txt_id = (TextView) child.findViewById(R.id.txt_id);
mHolder.txt_fName = (TextView) child.findViewById(R.id.txt_fName);
mHolder.txt_lName = (TextView) child.findViewById(R.id.txt_lName);
mHolder.phoneTextView = (TextView) child.findViewById(R.id.phoneTextView);
child.setTag(mHolder);
} else {
mHolder = (Holder) child.getTag();
}
mHolder.txt_id.setText(id.get(pos));
mHolder.txt_fName.setText(firstName.get(pos));
mHolder.txt_lName.setText(lastName.get(pos));
mHolder.phoneTextView.setText(phoneNo.get(pos));
return child;
}
public class Holder {
TextView txt_id;
TextView txt_fName;
TextView txt_lName;
TextView phoneTextView;
}
}
Database Helper.java
public class DbHelper extends SQLiteOpenHelper {
static String DATABASE_NAME="userdata";
public static final String TABLE_NAME="user";
public static final String KEY_FNAME="fname";
public static final String KEY_LNAME="lname";
public static final String KEY_PHONENO="pno";
public static final String KEY_ID="id";
public DbHelper(Context context) {
super(context, DATABASE_NAME, null, 1);
}
#Override
public void onCreate(SQLiteDatabase db) {
String CREATE_TABLE="CREATE TABLE "+TABLE_NAME+" ("+KEY_ID+" INTEGER PRIMARY KEY, "+KEY_FNAME+" TEXT, "+KEY_LNAME+" TEXT, "+KEY_PHONENO+" TEXT)";
db.execSQL(CREATE_TABLE);
}
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
db.execSQL("DROP TABLE IF EXISTS "+TABLE_NAME);
onCreate(db);
}
}
DisplayActivity.java
public class DisplayActivity extends Activity {
private DbHelper mHelper;
private SQLiteDatabase dataBase;
private ArrayList<String> userId = new ArrayList<String>();
private ArrayList<String> user_fName = new ArrayList<String>();
private ArrayList<String> user_lName = new ArrayList<String>();
private ArrayList<String> user_phoneNo = new ArrayList<String>();
private ListView userList;
private AlertDialog.Builder build;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.display_activity);
userList = (ListView) findViewById(R.id.List);
mHelper = new DbHelper(this);
//add new record
findViewById(R.id.btnAdd).setOnClickListener(new OnClickListener() {
public void onClick(View v) {
Intent i = new Intent(getApplicationContext(), AddActivity.class);
i.putExtra("update", false);
startActivity(i);
}
});
//click to update data
userList.setOnItemClickListener(new OnItemClickListener() {
public void onItemClick(AdapterView<?> arg0, View arg1, int arg2, long arg3) {
Intent i = new Intent(getApplicationContext(), AddActivity.class);
i.putExtra("Fname", user_fName.get(arg2));
i.putExtra("Lname", user_lName.get(arg2));
i.putExtra("Lname", user_phoneNo.get(arg2));
i.putExtra("ID", userId.get(arg2));
i.putExtra("update", true);
startActivity(i);
}
});
//long click to delete data
userList.setOnItemLongClickListener(new OnItemLongClickListener() {
public boolean onItemLongClick(AdapterView<?> arg0, View arg1, final int arg2, long arg3) {
build = new AlertDialog.Builder(DisplayActivity.this);
build.setTitle("Delete " + user_fName.get(arg2) + " " + user_lName.get(arg2));
build.setMessage("Do you want to delete ?");
build.setPositiveButton("Yes",new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
Toast.makeText( getApplicationContext(),
user_fName.get(arg2) + " "
+ user_lName.get(arg2)
+user_phoneNo.get(arg2)
+ " is deleted.", 3000).show();
dataBase.delete(
DbHelper.TABLE_NAME,
DbHelper.KEY_ID + "="
+ userId.get(arg2), null);
displayData();
dialog.cancel();
}
});
build.setNegativeButton("No", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
dialog.cancel();
}
});
AlertDialog alert = build.create();
alert.show();
return true;
}
});
}
#Override
protected void onResume() {
displayData();
super.onResume();
}
/**
* displays data from SQLite
*/
private void displayData() {
dataBase = mHelper.getWritableDatabase();
Cursor mCursor = dataBase.rawQuery("SELECT * FROM " + DbHelper.TABLE_NAME, null);
userId.clear();
user_fName.clear();
user_lName.clear();
user_phoneNo.clear();
if (mCursor.moveToFirst()) {
do {
userId.add(mCursor.getString(mCursor.getColumnIndex(DbHelper.KEY_ID)));
user_fName.add(mCursor.getString(mCursor.getColumnIndex(DbHelper.KEY_FNAME)));
user_lName.add(mCursor.getString(mCursor.getColumnIndex(DbHelper.KEY_LNAME)));
user_phoneNo.add(mCursor.getString(mCursor.getColumnIndex(DbHelper.KEY_PHONENO)));
} while (mCursor.moveToNext());
}
DisplayAdapter disadpt = new DisplayAdapter(DisplayActivity.this,userId, user_fName, user_lName,user_phoneNo);
userList.setAdapter(disadpt);
mCursor.close();
}
}
Below is an example of storing and fetching data from database.
public class Database extends SQLiteOpenHelper {
public static final String KEY_ID= "id";
public static final String KEY_SURVEY_UPLOAD = "IS_SURVEY_UPLOAD";
public static final String KEY_SURVEY_COMPLETE = "IS_SURVEY_COMPLETE";
public static final String KEY_DEVICE_ID = "DEVICE_ID";
public static final String KEY_LATITUDE = "LATITUDE";
public static final String KEY_LONGITUDE = "LONGITUDE";
public static final String KEY_FILE_ID = "FILE_ID";
public static final String DATABASE_NAME = "DatabaseName";
public static final String DATABASE_TABLE_one = "Table1";
private static final String CREATE_TABLE__NUM = "create table "+DATABASE_TABLE_SURVEY+
" ("+KEY_SURVEY_COMPLETE+" TEXT,"+KEY_FILE_ID+" INTEGER,"+KEY_DEVICE_ID+" TEXT,"+KEY_LATITUDE+" TEXT, "+KEY_LONGITUDE+" TEXT, "+KEY_SURVEY_UPLOAD+" TEXT, "+KEY_SURVEYID+" INTEGER PRIMARY KEY AUTOINCREMENT )";
public Database(Context context, String name, CursorFactory factory,
int version) {
super(context, name, null, 1);
// TODO Auto-generated constructor stub
}
#Override
public void onCreate(SQLiteDatabase db) {
// TODO Auto-generated method stub
System.out.println("crteate table");
db.execSQL(CREATE_TABLE_SURVEY_CONTENT);
}
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
// TODO Auto-generated method stub
db.execSQL("DROP TABLE IF EXISTS " + DATABASE_TABLE_one);
onCreate(db);
}
public boolean insertData(SurveyBean bean)
{
System.out.println("insert_SURVEY");
SQLiteDatabase db = this.getWritableDatabase();
ContentValues contentValues = new ContentValues();
contentValues.put(KEY_SURVEY_COMPLETE, "false");
contentValues.put(KEY_SURVEY_UPLOAD, "0");
contentValues.put(KEY_LATITUDE, bean.getLatitude());
contentValues.put(KEY_LONGITUDE, bean.getLongitude());
contentValues.put(KEY_DEVICE_ID, bean.getDeviceId());
contentValues.put(KEY_FILE_ID, Integer.getInteger(bean.getFileId()));
long id=db.insert(DATABASE_TABLE_SURVEY, null, contentValues);
System.out.println("last inserted ID"+id);
db.close();
return true;
}
public ArrayList<SurveyBean> getAllData(){
ArrayList<SurveyBean> arrayList = new ArrayList<SurveyBean>();
SQLiteDatabase db = this.getWritableDatabase();
Cursor cc = db.rawQuery("SELECT *" + " FROM " + DATABASE_TABLE_SURVEY, null);
cc.moveToFirst();
while(cc.isAfterLast() == false){
SurveyBean bean = new SurveyBean();
bean.set_isSurveyComplete(cc.getString(cc.getColumnIndex(KEY_SURVEY_COMPLETE)));
bean.set_isSurveyUpload(cc.getString(cc.getColumnIndex(KEY_SURVEY_UPLOAD)));
bean.set_surveyId(Integer.parseInt(cc.getString(cc.getColumnIndex(KEY_SURVEYID))));
bean.setDeviceId(cc.getString(cc.getColumnIndex(KEY_DEVICE_ID)));
bean.setLatitude(cc.getString(cc.getColumnIndex(KEY_LATITUDE)));
bean.setLongitude(cc.getString(cc.getColumnIndex(KEY_LONGITUDE)));
bean.setFileId(String.valueOf(cc.getInt(cc.getColumnIndex(KEY_FILE_ID))));
arrayList.add(bean);
cc.moveToNext();
}
db.close();
return arrayList ;
}
}
Look i had done a simple app to create a list view from sqlite database in android. Have a look at it.It may help you.
main.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
>
<TextView
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="#string/hello"
/>
</LinearLayout>
DBHelper.java
import android.content.Context;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteException;
import android.database.sqlite.SQLiteOpenHelper;
public class DBHelper extends SQLiteOpenHelper{
public SQLiteDatabase DB;
public String DBPath;
public static String DBName = "testdb";
public static final int version = '1';
public static Context currentContext;
public static String tableName = "tbl_details";
public DBHelper(Context context) {
super(context, DBName, null, version);
currentContext = context;
DBPath = "/data/data/" + context.getPackageName() + "/databases";
createDatabase();
}
#Override
public void onCreate(SQLiteDatabase db) {
// TODO Auto-generated method stub
}
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
// TODO Auto-generated method stub
}
private void createDatabase() {
boolean dbExists = checkDbExists();
if (dbExists) {
// do nothing
} else {
DB = currentContext.openOrCreateDatabase(DBName, 0, null);
DB.execSQL("CREATE TABLE IF NOT EXISTS " +
tableName +
" (LastName VARCHAR, FirstName VARCHAR," +
" Country VARCHAR, Age INT(3));");
DB.execSQL("INSERT INTO " +
tableName +
" Values ('A','vijay','India',20);");
DB.execSQL("INSERT INTO " +
tableName +
" Values ('B','ajay','Pakistan',25);");
DB.execSQL("INSERT INTO " +
tableName +
" Values ('C','suraj','Bangladesh',30);");
DB.execSQL("INSERT INTO " +
tableName +
" Values ('D','jayesh','China',35);");
DB.execSQL("INSERT INTO " +
tableName +
" Values ('E','ramesh','Nepal',40);");
DB.execSQL("INSERT INTO " +
tableName +
" Values ('F','suresh','SriLanka',45);");
}
}
private boolean checkDbExists() {
SQLiteDatabase checkDB = null;
try {
String myPath = DBPath + DBName;
checkDB = SQLiteDatabase.openDatabase(myPath, null,
SQLiteDatabase.OPEN_READONLY);
} catch (SQLiteException e) {
// database does't exist yet.
}
if (checkDB != null) {
checkDB.close();
}
return checkDB != null ? true : false;
}
}
manifest.xml
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.example.ListViewFromSQLiteDB"
android:versionCode="1"
android:versionName="1.0">
<application android:icon="#drawable/icon" android:label="#string/app_name">
<activity android:name="com.example.ListViewFromSQLiteDB.DataListView"
android:label="#string/app_name">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
</application>
</manifest>
ListViewFromSQLiteDB.java
import java.util.ArrayList;
import android.app.ListActivity;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteException;
import android.os.Bundle;
import android.util.Log;
import android.widget.ArrayAdapter;
import android.widget.TextView;
public class DataListView extends ListActivity {
private ArrayList<String> results = new ArrayList<String>();
private String tableName = DBHelper.tableName;
private SQLiteDatabase newDB;
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
openAndQueryDatabase();
displayResultList();
}
private void displayResultList() {
TextView tView = new TextView(this);
tView.setText("This data is retrieved from the database and only 4 " +
"of the results are displayed");
getListView().addHeaderView(tView);
setListAdapter(new ArrayAdapter<String>(this,
android.R.layout.simple_list_item_1, results));
getListView().setTextFilterEnabled(true);
}
private void openAndQueryDatabase() {
try {
DBHelper dbHelper = new DBHelper(this.getApplicationContext());
newDB = dbHelper.getWritableDatabase();
Cursor c = newDB.rawQuery("SELECT FirstName, Age FROM " +
tableName +
" where Age > 10 LIMIT 4", null);
if (c != null ) {
if (c.moveToFirst()) {
do {
String firstName = c.getString(c.getColumnIndex("FirstName"));
int age = c.getInt(c.getColumnIndex("Age"));
results.add("Name: " + firstName + ",Age: " + age);
}while (c.moveToNext());
}
}
} catch (SQLiteException se ) {
Log.e(getClass().getSimpleName(), "Could not create or Open the database");
} finally {
if (newDB != null)
newDB.execSQL("DELETE FROM " + tableName);
newDB.close();
}
}
}
}

how read values from sqlite database

Question for me is i want to get a data from sqlite database for specific Id and if the That ID is Not Exists in the database i need to show a message saying Invalid ID , Problem is in my code is it works when the Id matches .but when database does not have the value which i search for i get crashed the app. im a newbie to programming i know this is something wrong in my logic where i put this.please help.tried several times
package com.my.myapp;
import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.SQLException;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteDatabase.CursorFactory;
import android.database.sqlite.SQLiteOpenHelper;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
public class DBSqliteAddSTDinfo {
public static final String KEY_STDNO = "S_no";
public static final String KEY_NAME = "First_Name";
public static final String KEY_AGE = "Age";
private static final String DBNAME = "second";
private static final String TBLNAME = "details";
private static final int DBversion = 1;
private DbHelper OurHelper;
private final Context OurContext;
private SQLiteDatabase OurDatabase;
private static class DbHelper extends SQLiteOpenHelper {
public DbHelper(Context context) {
super(context, DBNAME, null, DBversion);
// TODO Auto-generated constructor stub
}
#Override
public void onCreate(SQLiteDatabase db) {
// TODO Auto-generated method stub
db.execSQL("CREATE TABLE " + TBLNAME + " (" +
KEY_STDNO + " INTEGER PRIMARY KEY, " +
KEY_NAME + " TEXT NOT NULL, " +
KEY_AGE + " TEXT NOT NULL);"
);
}
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
// TODO Auto-generated method stub
db.execSQL("DROP TABLE IF EXISTS " + TBLNAME );
onCreate(db);
}
}
public DBSqliteAddSTDinfo(Context c){
OurContext = c;
}
public DBSqliteAddSTDinfo open()throws SQLException{
OurHelper = new DbHelper(OurContext);
OurDatabase = OurHelper.getWritableDatabase();
return this;
}
public void close(){
if (OurDatabase != null){
OurDatabase.close();
OurHelper.close();
}
}
/*EditText editID,editFname,editLname,editDOB,editSname,editGrade_Year,editClass;
Button Submit;
SQLiteDatabase db;*/
public long creatEntry(String Id, String Name, String Age) {
// TODO Auto-generated method stub
ContentValues cv = new ContentValues();
cv.put(KEY_STDNO, Id);
cv.put(KEY_NAME, Name);
cv.put(KEY_AGE, Age);
return OurDatabase.insert(TBLNAME, null, cv);
}
public String getName(long l) {
// TODO Auto-generated method stub
String[] columns = new String[]{ KEY_STDNO, KEY_NAME, KEY_AGE};
Cursor c = OurDatabase.query(TBLNAME, columns, KEY_STDNO + "=" + l, null, null, null, null);
if(c != null){
c.moveToFirst();
String name = c.getString(1);
return name;
}
return null;
}
public String getAge(long l) {
// TODO Auto-generated method stub
String[] columns = new String[]{ KEY_STDNO, KEY_NAME, KEY_AGE};
Cursor c = OurDatabase.query(TBLNAME, columns, KEY_STDNO + "=" + l, null, null, null, null);
if(c != null){
c.moveToFirst();
String age = c.getString(2);
return age;
}
return null;
}
public void updateEntry(long lRow, String sname, String sage) {
// TODO Auto-generated method stub
ContentValues update = new ContentValues();
update.put(KEY_NAME, sname);
update.put(KEY_AGE, sage);
OurDatabase.update(TBLNAME, update, KEY_STDNO + "=" + lRow, null);
}
public void deleteEntry(long lRowdel) {
// TODO Auto-generated method stub
OurDatabase.delete(TBLNAME, KEY_STDNO + "=" + lRowdel, null);
}
public String getNo(long l) {
// TODO Auto-generated method stub
String[] columns = new String[]{ KEY_STDNO, KEY_NAME, KEY_AGE};
Cursor c = OurDatabase.query(TBLNAME, columns, KEY_STDNO + "=" + l, null, null, null, null);
if(c != null){
c.moveToFirst();
String sno = c.getString(0);
return sno;
}
return null;
}
}
package com.my.myapp;
import android.app.AlertDialog.Builder;
import android.app.Dialog;
import android.os.Bundle;
import android.support.v7.app.ActionBarActivity;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import com.my.myapp.DBSqliteAddSTDinfo;
public class ViewData extends ActionBarActivity {
EditText id,name,age,ID;
Button ViewData,Update;
#SuppressWarnings("static-access")
public void onClick(View v){
id = (EditText)findViewById(R.id.ViewId);
name = (EditText)findViewById(R.id.ViewName);
age = (EditText)findViewById(R.id.ViewAge);
ID = (EditText)findViewById(R.id.editTextID);
ViewData = (Button) findViewById(R.id.btnViewData);
DBSqliteAddSTDinfo hon = new DBSqliteAddSTDinfo(this);
hon.open();
if(id.getText().toString().trim().length()==0)
{
Dialog d = new Dialog(ViewData.this);
d.setTitle("ID Can Not Be Empty");
TextView tv = new TextView(ViewData.this);
tv.setText("Unsuccessful ! ");
d.setContentView(tv);
d.show();
return;
}
String s = id.getText().toString();
long l = Long.parseLong(s);
String returnedName = hon.getName(l);
String returnedAge = hon.getAge(l);
String returnedSno = hon.getNo(l);
//String NewSno = Long.toString(l);
if(returnedSno.equals(s)){
name.setText(returnedName);
age.setText(returnedAge);
ID.setText(returnedSno);
/*Dialog d = new Dialog(ViewData.this);
d.setTitle("Invalied ID");
TextView tv = new TextView(ViewData.this);
tv.setText("Unsuccessful ! ");
d.setContentView(tv);
d.show();*/
//return;
}
if(hon.getNo(l)== null && hon.getName(l)== null && hon.getAge(l)== null ){
Dialog d = new Dialog(ViewData.this);
d.setTitle("Invalied ID");
TextView tv = new TextView(ViewData.this);
tv.setText("Unsuccessful ! ");
d.setContentView(tv);
d.show();
//return;
/*name.setText(returnedName);
age.setText(returnedAge);
ID.setText(returnedSno); */
}
hon.close();
}
private void clearText() {
// TODO Auto-generated method stub
id.setText("");
name.setText("");
age.setText("");
}
private void showMessage(String title, String message) {
// TODO Auto-generated method stub
{
Builder builder=new Builder(this);
builder.setCancelable(true);
builder.setTitle(title);
builder.setMessage(message);
builder.show();
}
}
public void onClickUpdate(View v){
String sname = name.getText().toString();
String sage = age.getText().toString();
String sRow = id.getText().toString();
long lRow = Long.parseLong(sRow);
DBSqliteAddSTDinfo upd = new DBSqliteAddSTDinfo(this);
upd.open();
upd.updateEntry(lRow, sname, sage);
upd.close();
}
public void onClickDelete(View v){
String sRowdel = id.getText().toString();
long lRowdel = Long.parseLong(sRowdel);
DBSqliteAddSTDinfo del = new DBSqliteAddSTDinfo(this);
del.open();
del.deleteEntry(lRowdel);
del.close();
}
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_view_data);
/*id = (EditText)findViewById(R.id.ViewId);
name = (EditText)findViewById(R.id.ViewName);
age = (EditText)findViewById(R.id.ViewAge);
ViewData = (Button) findViewById(R.id.btnViewData);
String s = id.getText().toString();
long l = Long.parseLong(s);
DBSqliteAddSTDinfo hon = new DBSqliteAddSTDinfo(this);
hon.open();
String returnedName = hon.getName(l);
String returnedAge = hon.getAge(l);
name.setText(returnedName);
age.setText(returnedAge);
hon.close(); */
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.view_data, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
}
Change
if(c != null){
c.moveToFirst();
to
if(c.moveToFirst()){
The cursor won't be null and you need to check the return value of moveToFirst() to see whether the cursor contains any rows before accessing its data with getString() and such.

filtering data from the database using setFilterQueryProvider?

I have here my code. Data on the database are filtered by the title, how can i filter data by title or author? I think it is on these lines of codes on Catalogue.java:
dataAdapter.setFilterQueryProvider(new FilterQueryProvider() {
public Cursor runQuery(CharSequence constraint) {
return dbHelper.fetchCollectionsByTitle(constraint.toString());
Here are my codes:
Catalogue.java
package com.cvsu.catalogue.db;
import com.cvsu.catalogue.R;
import android.annotation.SuppressLint;
import android.app.Activity;
import android.content.Intent;
import android.database.Cursor;
import android.os.Bundle;
import android.text.Editable;
import android.text.TextWatcher;
import android.view.View;
import android.widget.AdapterView;
import android.widget.EditText;
import android.widget.FilterQueryProvider;
import android.widget.ListView;
import android.widget.SimpleCursorAdapter;
//import android.widget.Toast;
import android.widget.AdapterView.OnItemClickListener;
#SuppressLint("NewApi")
public class Catalogue extends Activity {
private CollectionsDbAdapter dbHelper;
private SimpleCursorAdapter dataAdapter;
public final static String TITLE_EXTRA = "com.cvsu.catalogue.db._TITLE";
public final static String AUTHOR_EXTRA = "com.cvsu.catalogue.db._AUTHOR";
public final static String LOCATION_EXTRA = "com.cvsu.catalogue.db._LOCATION";
public final static String CALLNUMBER_EXTRA = "com.cvsu.catalogue.db._CALLNUMBER";
public final static String PUBLISHER_EXTRA = "com.cvsu.catalogue.db._PUBLISHER";
public final static String DATEPUBLISHED_EXTRA = "com.cvsu.catalogue.db._DATEPUBLISHED";
public final static String DESCRIPTION_EXTRA = "com.cvsu.catalogue.db._DESCRIPTION";
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.catalogue_title);
dbHelper = new CollectionsDbAdapter(this);
dbHelper.open();
//Generate ListView from SQLite Database
displayListView();
}
private void displayListView() {
Cursor cursor = dbHelper.fetchAllCollections();
// The desired columns to be bound
String[] columns = new String[] {
CollectionsDbAdapter.KEY_TITLE,
CollectionsDbAdapter.KEY_AUTHOR,
CollectionsDbAdapter.KEY_LOCATION,
CollectionsDbAdapter.KEY_CALLNUMBER,
CollectionsDbAdapter.KEY_PUBLISHER,
CollectionsDbAdapter.KEY_DATEPUBLISHED,
CollectionsDbAdapter.KEY_DESCRIPTION
};
// the XML defined views which the data will be bound to
int[] to = new int[] {
R.id.txtTitle,
R.id.txtAuthor,
//R.id.location,
//R.id.callnumber,
//R.id.publisher,
//R.id.datepublished,
//R.id.description,
};
// create the adapter using the cursor pointing to the desired data
//as well as the layout information
dataAdapter = new SimpleCursorAdapter(
this, R.layout.book_info_title,
cursor,
columns,
to,
0);
final ListView listView = (ListView) findViewById(R.id.listView1);
// Assign adapter to ListView
listView.setAdapter(dataAdapter);
listView.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> listview, View view,
int position, long id ) {
// Get the cursor, positioned to the corresponding row in the result set
/*Cursor cursor = (Cursor) listView.getItemAtPosition(position);
// Get the state's capital from this row in the database.
String bookTitle =
cursor.getString(cursor.getColumnIndexOrThrow("title"));
Toast.makeText(getApplicationContext(),
bookTitle, Toast.LENGTH_SHORT).show();*/
Intent i = new Intent (CatalogueTitle.this, BookInfoPage.class);
i.putExtra(TITLE_EXTRA, String.valueOf(id));
i.putExtra(AUTHOR_EXTRA, String.valueOf(id));
i.putExtra(LOCATION_EXTRA, String.valueOf(id));
i.putExtra(CALLNUMBER_EXTRA, String.valueOf(id));
i.putExtra(PUBLISHER_EXTRA, String.valueOf(id));
i.putExtra(DATEPUBLISHED_EXTRA, String.valueOf(id));
i.putExtra(DESCRIPTION_EXTRA, String.valueOf(id));
startActivity(i);
}
});
EditText myFilter = (EditText) findViewById(R.id.myFilter);
myFilter.addTextChangedListener(new TextWatcher() {
public void afterTextChanged(Editable s) {
}
public void beforeTextChanged(CharSequence s, int start,
int count, int after) {
}
public void onTextChanged(CharSequence s, int start,
int before, int count) {
dataAdapter.getFilter().filter(s.toString());
}
});
dataAdapter.setFilterQueryProvider(new FilterQueryProvider() {
public Cursor runQuery(CharSequence constraint) {
return dbHelper.fetchCollectionsByTitle(constraint.toString());
}
});
}
public static void main(String[] args) {
}
}
Collections.Java
package com.cvsu.catalogue.db;
public class Collections {
String title = null;
String author = null;
String location = null;
String callnumber = null;
String publisher = null;
String datepublished = null;
String description = null;
public String getTitle() {
return title;
}
public void setTitle(String title) {
this.title = title;
}
public String getAuthor() {
return author;
}
public void setAuthor(String author) {
this.author = author;
}
public String getLocation() {
return location;
}
public void setLocation(String location) {
this.location = location;
}
public String getCallNumber() {
return callnumber;
}
public void setCallNumber(String callnumber) {
this.callnumber = callnumber;
}
public String getPublisher() {
return publisher;
}
public void setPublisher(String publisher) {
this.publisher = publisher;
}
public String getDatePublished() {
return datepublished;
}
public void setDatePublished(String datepublished) {
this.datepublished = datepublished;
}
public String getDescription() {
return description;
}
public void setDescription(String description) {
this.description = description;
}
}
CollectionsDbAdapter.java
package com.cvsu.catalogue.db;
import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.SQLException;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
import android.util.Log;
public class CollectionsDbAdapter {
public static final String KEY_ROWID = "_id";
public static final String KEY_TITLE = "title";
public static final String KEY_AUTHOR = "author";
public static final String KEY_LOCATION = "location";
public static final String KEY_CALLNUMBER = "callnumber";
public static final String KEY_PUBLISHER = "publisher";
public static final String KEY_DATEPUBLISHED = "datepublished";
public static final String KEY_DESCRIPTION = "description";
private static final String TAG = "CollectionsDbAdapter";
private DatabaseHelper mDbHelper;
private SQLiteDatabase mDb;
private static final String DATABASE_NAME = "LibraryCollections";
private static final String SQLITE_TABLE = "Collections";
private static final int DATABASE_VERSION = 1;
private final Context mCtx;
private static final String DATABASE_CREATE =
"CREATE TABLE if not exists " + SQLITE_TABLE + " (" +
KEY_ROWID + " integer PRIMARY KEY autoincrement," +
KEY_TITLE + "," +
KEY_AUTHOR + "," +
KEY_LOCATION + "," +
KEY_CALLNUMBER + "," +
KEY_PUBLISHER + "," +
KEY_DATEPUBLISHED + "," +
KEY_DESCRIPTION + "," +
" UNIQUE (" + KEY_CALLNUMBER +"));";
private static class DatabaseHelper extends SQLiteOpenHelper {
DatabaseHelper(Context context) {
super(context, DATABASE_NAME, null, DATABASE_VERSION);
}
#Override
public void onCreate(SQLiteDatabase db) {
Log.w(TAG, DATABASE_CREATE);
db.execSQL(DATABASE_CREATE);
}
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
Log.w(TAG, "Upgrading database from version " + oldVersion + " to "
+ newVersion + ", which will destroy all old data");
db.execSQL("DROP TABLE IF EXISTS " + SQLITE_TABLE);
onCreate(db);
}
}
public CollectionsDbAdapter(Context ctx) {
this.mCtx = ctx;
}
public CollectionsDbAdapter open() throws SQLException {
mDbHelper = new DatabaseHelper(mCtx);
mDb = mDbHelper.getWritableDatabase();
return this;
}
public void close() {
if (mDbHelper != null) {
mDbHelper.close();
}
}
public long createCollections(String title, String author,
String location, String callnumber, String publisher, String datepublished, String description) {
ContentValues initialValues = new ContentValues();
initialValues.put(KEY_TITLE, title);
initialValues.put(KEY_AUTHOR, author);
initialValues.put(KEY_LOCATION, location);
initialValues.put(KEY_CALLNUMBER, callnumber);
initialValues.put(KEY_PUBLISHER, publisher);
initialValues.put(KEY_DATEPUBLISHED, datepublished);
initialValues.put(KEY_DESCRIPTION, description);
return mDb.insert(SQLITE_TABLE, null, initialValues);
}
public Cursor fetchCollectionsByTitle(String inputText) throws SQLException {
Log.w(TAG, inputText);
Cursor mCursor = null;
if (inputText == null || inputText.length () == 0) {
mCursor = mDb.query(SQLITE_TABLE, new String[] {KEY_ROWID,
KEY_TITLE, KEY_AUTHOR, KEY_LOCATION, KEY_CALLNUMBER, KEY_PUBLISHER, KEY_DATEPUBLISHED, KEY_DESCRIPTION},
null, null, null, null, null);
}
else {
mCursor = mDb.query(true, SQLITE_TABLE, new String[] {KEY_ROWID,
KEY_TITLE, KEY_AUTHOR, KEY_LOCATION, KEY_CALLNUMBER, KEY_PUBLISHER, KEY_DATEPUBLISHED, KEY_DESCRIPTION},
KEY_TITLE + " like '%" + inputText + "%'", null,
null, null, null, null);
}
if (mCursor != null) {
mCursor.moveToFirst();
}
return mCursor;
}
public Cursor fetchCollectionsByAuthor(String inputText) throws SQLException {
Log.w(TAG, inputText);
Cursor mCursor = null;
if (inputText == null || inputText.length () == 0) {
mCursor = mDb.query(SQLITE_TABLE, new String[] {KEY_ROWID,
KEY_TITLE, KEY_AUTHOR, KEY_LOCATION, KEY_CALLNUMBER, KEY_PUBLISHER, KEY_DATEPUBLISHED, KEY_DESCRIPTION},
null, null, null, null, null);
}
else {
mCursor = mDb.query(true, SQLITE_TABLE, new String[] {KEY_ROWID,
KEY_TITLE, KEY_AUTHOR, KEY_LOCATION, KEY_CALLNUMBER, KEY_PUBLISHER, KEY_DATEPUBLISHED, KEY_DESCRIPTION},
KEY_AUTHOR + " like '%" + inputText + "%'", null,
null, null, null, null);
}
if (mCursor != null) {
mCursor.moveToFirst();
}
return mCursor;
}
public Cursor fetchAllCollections() {
Cursor mCursor = mDb.query(SQLITE_TABLE, new String[] {KEY_ROWID,
KEY_TITLE, KEY_AUTHOR, KEY_LOCATION, KEY_CALLNUMBER, KEY_PUBLISHER, KEY_DATEPUBLISHED, KEY_DESCRIPTION},
null, null, null, null, null);
if (mCursor != null) {
mCursor.moveToFirst();
}
return mCursor;
}
}
#Override
public Cursor runQuery(CharSequence constraint) {
Cursor cur = null;
database.openDataBase();
if(constraint!=null){
cur = database.selectDataWithConstrain(constraint.toString());
}
return cur;
}
using this constarint write a query in your Database Class and get the data required either title or author
public Cursor selectDataWithConstrain(String c) {
// TODO Auto-generated method stub
Cursor cursor = myDataBase.rawQuery("SELECT * FROM tbl_xxx WHERE title LIKE '%"+c+"%'", null);
return cursor;
}
public Cursor fetchdatabyfilter(String inputText, String filtercolumn) throws SQLException {
Cursor row = null;
String query = "SELECT * FROM " + dbTable;
if (inputText == null || inputText.length() == 0 ) {
row = sqlDb.rawQuery(query, null);
} else {
query = "SELECT * FROM " + dbTable + " WHERE " + filtercolumn + " like '%" + inputText + "%' ";
row = sqlDb.rawQuery(query, null);
}
if (row != null)
{
row.moveToFirst();
}
return row;
}
mainactivity:
adapter.setFilterQueryProvider(new FilterQueryProvider() {
public Cursor runQuery(CharSequence constraint) {
return db.fetchdatabyfilter(constraint.toString(),"title" );
}
});

Categories

Resources