Refreshing a ListView to reflect ArrayList population - java

I am running into an issue where my app crashes and I am given an error that reads
04-28 15:08:32.378: E/AndroidRuntime(27229): FATAL EXCEPTION: main
04-28 15:08:32.378: E/AndroidRuntime(27229): Process: com.example.datetracker, PID: 27229
04-28 15:08:32.378: E/AndroidRuntime(27229): java.lang.IndexOutOfBoundsException: Invalid index 0, size is 0
04-28 15:08:32.378: E/AndroidRuntime(27229): at java.util.ArrayList.throwIndexOutOfBoundsException(ArrayList.java:255)
I can successfully remove an item from the lstEvents arraylist and I can also remove the event object from the database, but I can't seem to have it disappear from the screen. No matter what I do it seems to keep refreshing the listview with the same contents.
What am I doing wrong? I keep getting this IndexOutOfBoundsException, and I am pretty sure it is because the view is not updating properly and it continues to allow me to swipe-to-dismiss which is in return trying to delete objects which eventually are not going to be there.
MainActivity
public class MainActivity extends FragmentActivity implements OnClickListener {
ListView listView;
int lastIndex = -1;
ArrayList<Event> lstEvents = new ArrayList<Event>();
ArrayList<Event> templstEvents = new ArrayList<Event>();
// detail view
TextView tvTitle, tvTime, tvDate;
ImageView ivPic;
View vw_master;
boolean _isBack = true;
ImageButton add;
String title;
String date;
String time;
int resId;
Context context;
static final int PICK_CONTACT_REQUEST = 0;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
// // get detail controls
tvTitle = (TextView) findViewById(R.id.textViewTitle);
tvDate = (TextView) findViewById(R.id.textViewDate);
tvTime = (TextView) findViewById(R.id.textViewTime);
ivPic = (ImageView) findViewById(R.id.imageView1);
add = (ImageButton) findViewById(R.id.add);
add.setOnClickListener(this);
// ///////////////////////////////LISTVIEW////////////////////////////////////////
// Create the adapter to convert the array to views
EventAdapter adapter = new EventAdapter(this, lstEvents);
// attach adapter to a list view
listView = (ListView) findViewById(R.id.listViewFragment);
listView.setAdapter(adapter);
context = this;
SwipeDismissListViewTouchListener touchListener = new SwipeDismissListViewTouchListener(
listView,
new SwipeDismissListViewTouchListener.DismissCallbacks() {
EventAdapter adapter = new EventAdapter(context, lstEvents);
DatabaseHandler db = new DatabaseHandler(context);
#Override
public boolean canDismiss(int position) {
return true;
}
#Override
public void onDismiss(ListView listView,
int[] reverseSortedPositions) {
for (int position : reverseSortedPositions) {
if (lstEvents.isEmpty()){
Log.e("EMPTYLIST","THELISTISEMPTY");
}
else
db.deleteEvent(lstEvents.get(position));
lstEvents.remove(position);
//adapter.remove(adapter.getItem(position));
}
adapter.notifyDataSetChanged();
}
});
listView.setOnTouchListener(touchListener);
// Setting this scroll listener is required to ensure that during
// ListView scrolling,
// we don't look for swipes.
listView.setOnScrollListener(touchListener.makeScrollListener());
// /////////////////////////////DATABASE/////////////////////////////////////////////
DatabaseHandler db = new DatabaseHandler(this);
// /////////////////////////////DATABASE/////////////////////////////////////////////
lstEvents = db.getAllContacts();
adapter.addAll(lstEvents);
adapter.notifyDataSetChanged();
}
// #Override
// protected void onResume() {
// // TODO Auto-generated method stub
// super.onResume();
// //
// /////////////////////////////DATABASE/////////////////////////////////////////////
// DatabaseHandler db = new DatabaseHandler(this);
// //
// /////////////////////////////DATABASE/////////////////////////////////////////////
//
// lstEvents = db.getAllContacts();
// EventAdapter adapter = new EventAdapter(this, lstEvents);
// adapter.addAll(lstEvents);
// adapter.notifyDataSetChanged();
// }
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
switch (v.getId()) {
case R.id.add:
Intent intent = new Intent(this, CreateActivity.class);
startActivityForResult(intent, 100);
break;
}
}
#Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
// /////////////////////////////DATABASE/////////////////////////////////////////////
DatabaseHandler db = new DatabaseHandler(this);
// /////////////////////////////DATABASE/////////////////////////////////////////////
// Create the adapter to convert the array to views
EventAdapter adapter = new EventAdapter(this, lstEvents);
// attach adapter to a list view
listView = (ListView) findViewById(R.id.listViewFragment);
listView.setAdapter(adapter);
if (requestCode == 100) {
if (resultCode == RESULT_OK) {
Bundle b = data.getExtras();
title = b.getString("TITLE");
time = b.getString("TIME");
date = b.getString("DATE");
Bitmap bitmap = b.getParcelable("BITMAP");
// ///CONVERTING A BITMAP TO A BYTE[]
byte[] image = null;
ByteArrayOutputStream bos = new ByteArrayOutputStream();
bitmap.compress(Bitmap.CompressFormat.PNG, 100, bos);
image = bos.toByteArray();
// ///////
// /////////////////////////////DATABASE/////////////////////////////////////////////
/**
* CRUD OPERATIONS
*/
Log.e("Insert: ", "Inserting ..");
db.addEvent(new Event((int) Math.floor(Math.random() * 101),
title, time, date, image));
// Reading all contacts
Log.e("Reading: ", "Reading all contacts..");
lstEvents = db.getAllContacts();
adapter.addAll(lstEvents);
adapter.notifyDataSetChanged();
// logging all events
for (Event ev : lstEvents) {
String log = "Id: " + ev.get_Id() + " ,Title: "
+ ev.get_title() + " ,Date: " + ev.get_date()
+ " ,RESOURCEID: " + ev.get_image();
// Writing Contacts to log
Log.e("Name: ", log);
}
// /////////////////////////////DATABASE/////////////////////////////////////////////
}
}
}
}
SwipeDismissListViewTouchListener
public class SwipeDismissListViewTouchListener implements View.OnTouchListener {
// Cached ViewConfiguration and system-wide constant values
private int mSlop;
private int mMinFlingVelocity;
private int mMaxFlingVelocity;
private long mAnimationTime;
// Fixed properties
private ListView mListView;
private DismissCallbacks mCallbacks;
private int mViewWidth = 1; // 1 and not 0 to prevent dividing by zero
// Transient properties
private List<PendingDismissData> mPendingDismisses = new ArrayList<PendingDismissData>();
private int mDismissAnimationRefCount = 0;
private float mDownX;
private boolean mSwiping;
private VelocityTracker mVelocityTracker;
private int mDownPosition;
private View mDownView;
private boolean mPaused;
/**
* The callback interface used by {#link SwipeDismissListViewTouchListener} to inform its client
* about a successful dismissal of one or more list item positions.
*/
public interface DismissCallbacks {
/**
* Called to determine whether the given position can be dismissed.
*/
boolean canDismiss(int position);
/**
* Called when the user has indicated they she would like to dismiss one or more list item
* positions.
*
* #param listView The originating {#link ListView}.
* #param reverseSortedPositions An array of positions to dismiss, sorted in descending
* order for convenience.
*/
void onDismiss(ListView listView, int[] reverseSortedPositions);
}
/**
* Constructs a new swipe-to-dismiss touch listener for the given list view.
*
* #param listView The list view whose items should be dismissable.
* #param callbacks The callback to trigger when the user has indicated that she would like to
* dismiss one or more list items.
*/
public SwipeDismissListViewTouchListener(ListView listView, DismissCallbacks callbacks) {
ViewConfiguration vc = ViewConfiguration.get(listView.getContext());
mSlop = vc.getScaledTouchSlop();
mMinFlingVelocity = vc.getScaledMinimumFlingVelocity() * 16;
mMaxFlingVelocity = vc.getScaledMaximumFlingVelocity();
mAnimationTime = listView.getContext().getResources().getInteger(
android.R.integer.config_shortAnimTime);
mListView = listView;
mCallbacks = callbacks;
}
/**
* Enables or disables (pauses or resumes) watching for swipe-to-dismiss gestures.
*
* #param enabled Whether or not to watch for gestures.
*/
public void setEnabled(boolean enabled) {
mPaused = !enabled;
}
/**
* Returns an {#link android.widget.AbsListView.OnScrollListener} to be added to the {#link
* ListView} using {#link ListView#setOnScrollListener(android.widget.AbsListView.OnScrollListener)}.
* If a scroll listener is already assigned, the caller should still pass scroll changes through
* to this listener. This will ensure that this {#link SwipeDismissListViewTouchListener} is
* paused during list view scrolling.</p>
*
* #see SwipeDismissListViewTouchListener
*/
public AbsListView.OnScrollListener makeScrollListener() {
return new AbsListView.OnScrollListener() {
#Override
public void onScrollStateChanged(AbsListView absListView, int scrollState) {
setEnabled(scrollState != AbsListView.OnScrollListener.SCROLL_STATE_TOUCH_SCROLL);
}
#Override
public void onScroll(AbsListView absListView, int i, int i1, int i2) {
}
};
}
/**
* Manually cause the item at the given position to be dismissed (trigger the dismiss
* animation).
*/
public void dismiss(int position) {
dismiss(getViewForPosition(position), position, true);
}
#Override
public boolean onTouch(View view, MotionEvent motionEvent) {
if (mViewWidth < 2) {
mViewWidth = mListView.getWidth();
}
switch (motionEvent.getActionMasked()) {
case MotionEvent.ACTION_DOWN: {
if (mPaused) {
return false;
}
// TODO: ensure this is a finger, and set a flag
// Find the child view that was touched (perform a hit test)
Rect rect = new Rect();
int childCount = mListView.getChildCount();
int[] listViewCoords = new int[2];
mListView.getLocationOnScreen(listViewCoords);
int x = (int) motionEvent.getRawX() - listViewCoords[0];
int y = (int) motionEvent.getRawY() - listViewCoords[1];
View child;
for (int i = 0; i < childCount; i++) {
child = mListView.getChildAt(i);
child.getHitRect(rect);
if (rect.contains(x, y)) {
mDownView = child;
break;
}
}
if (mDownView != null) {
mDownX = motionEvent.getRawX();
mDownPosition = mListView.getPositionForView(mDownView);
if (mCallbacks.canDismiss(mDownPosition)) {
mVelocityTracker = VelocityTracker.obtain();
mVelocityTracker.addMovement(motionEvent);
} else {
mDownView = null;
}
}
view.onTouchEvent(motionEvent);
return true;
}
case MotionEvent.ACTION_UP: {
if (mVelocityTracker == null) {
break;
}
float deltaX = motionEvent.getRawX() - mDownX;
mVelocityTracker.addMovement(motionEvent);
mVelocityTracker.computeCurrentVelocity(1000);
float velocityX = mVelocityTracker.getXVelocity();
float absVelocityX = Math.abs(velocityX);
float absVelocityY = Math.abs(mVelocityTracker.getYVelocity());
boolean dismiss = false;
boolean dismissRight = false;
if (Math.abs(deltaX) > mViewWidth / 2) {
dismiss = true;
dismissRight = deltaX > 0;
} else if (mMinFlingVelocity <= absVelocityX && absVelocityX <= mMaxFlingVelocity
&& absVelocityY < absVelocityX) {
// dismiss only if flinging in the same direction as dragging
dismiss = (velocityX < 0) == (deltaX < 0);
dismissRight = mVelocityTracker.getXVelocity() > 0;
}
if (dismiss) {
// dismiss
dismiss(mDownView, mDownPosition, dismissRight);
} else {
// cancel
mDownView.animate()
.translationX(0)
.alpha(1)
.setDuration(mAnimationTime)
.setListener(null);
}
mVelocityTracker.recycle();
mVelocityTracker = null;
mDownX = 0;
mDownView = null;
mDownPosition = ListView.INVALID_POSITION;
mSwiping = false;
break;
}
case MotionEvent.ACTION_CANCEL: {
if (mVelocityTracker == null) {
break;
}
if (mDownView != null) {
// cancel
mDownView.animate()
.translationX(0)
.alpha(1)
.setDuration(mAnimationTime)
.setListener(null);
}
mVelocityTracker.recycle();
mVelocityTracker = null;
mDownX = 0;
mDownView = null;
mDownPosition = ListView.INVALID_POSITION;
mSwiping = false;
break;
}
case MotionEvent.ACTION_MOVE: {
if (mVelocityTracker == null || mPaused) {
break;
}
mVelocityTracker.addMovement(motionEvent);
float deltaX = motionEvent.getRawX() - mDownX;
if (Math.abs(deltaX) > mSlop) {
mSwiping = true;
mListView.requestDisallowInterceptTouchEvent(true);
// Cancel ListView's touch (un-highlighting the item)
MotionEvent cancelEvent = MotionEvent.obtain(motionEvent);
cancelEvent.setAction(MotionEvent.ACTION_CANCEL |
(motionEvent.getActionIndex()
<< MotionEvent.ACTION_POINTER_INDEX_SHIFT));
mListView.onTouchEvent(cancelEvent);
cancelEvent.recycle();
}
if (mSwiping) {
mDownView.setTranslationX(deltaX);
mDownView.setAlpha(Math.max(0.15f, Math.min(1f,
1f - 2f * Math.abs(deltaX) / mViewWidth)));
return true;
}
break;
}
}
return false;
}
private void dismiss(final View view, final int position, boolean dismissRight) {
++mDismissAnimationRefCount;
if (view == null) {
// No view, shortcut to calling onDismiss to let it deal with adapter
// updates and all that.
mCallbacks.onDismiss(mListView, new int[] { position });
return;
}
view.animate()
.translationX(dismissRight ? mViewWidth : -mViewWidth)
.alpha(0)
.setDuration(mAnimationTime)
.setListener(new AnimatorListenerAdapter() {
#Override
public void onAnimationEnd(Animator animation) {
performDismiss(view, position);
}
});
}
private View getViewForPosition(int position) {
int index = position
- (mListView.getFirstVisiblePosition() - mListView.getHeaderViewsCount());
return (index >= 0 && index < mListView.getChildCount())
? mListView.getChildAt(index)
: null;
}
class PendingDismissData implements Comparable<PendingDismissData> {
public int position;
public View view;
public PendingDismissData(int position, View view) {
this.position = position;
this.view = view;
}
#Override
public int compareTo(PendingDismissData other) {
// Sort by descending position
return other.position - position;
}
}
private void performDismiss(final View dismissView, final int dismissPosition) {
// Animate the dismissed list item to zero-height and fire the dismiss callback when
// all dismissed list item animations have completed. This triggers layout on each animation
// frame; in the future we may want to do something smarter and more performant.
final ViewGroup.LayoutParams lp = dismissView.getLayoutParams();
final int originalHeight = dismissView.getHeight();
ValueAnimator animator = ValueAnimator.ofInt(originalHeight, 1).setDuration(mAnimationTime);
animator.addListener(new AnimatorListenerAdapter() {
#Override
public void onAnimationEnd(Animator animation) {
--mDismissAnimationRefCount;
if (mDismissAnimationRefCount == 0) {
// No active animations, process all pending dismisses.
// Sort by descending position
Collections.sort(mPendingDismisses);
int[] dismissPositions = new int[mPendingDismisses.size()];
for (int i = mPendingDismisses.size() - 1; i >= 0; i--) {
dismissPositions[i] = mPendingDismisses.get(i).position;
}
mCallbacks.onDismiss(mListView, dismissPositions);
ViewGroup.LayoutParams lp;
for (PendingDismissData pendingDismiss : mPendingDismisses) {
// Reset view presentation
pendingDismiss.view.setAlpha(1f);
pendingDismiss.view.setTranslationX(0);
lp = pendingDismiss.view.getLayoutParams();
lp.height = originalHeight;
pendingDismiss.view.setLayoutParams(lp);
}
mPendingDismisses.clear();
}
}
});
animator.addUpdateListener(new ValueAnimator.AnimatorUpdateListener() {
#Override
public void onAnimationUpdate(ValueAnimator valueAnimator) {
lp.height = (Integer) valueAnimator.getAnimatedValue();
dismissView.setLayoutParams(lp);
}
});
mPendingDismisses.add(new PendingDismissData(dismissPosition, dismissView));
animator.start();
}
}
DatabaseHandler
public class DatabaseHandler extends SQLiteOpenHelper {
// All Static variables
// Database Version
private static final int DATABASE_VERSION = 1;
// Database Name
private static final String DATABASE_NAME = "scheduleManager";
// Contacts table name
private static final String TABLE_EVENTS = "events";
// Contacts Table Columns names
private static final String KEY_ID = "id";
private static final String KEY_TITLE = "title";
private static final String KEY_TIME = "time";
private static final String KEY_DATE = "date";
private static final String KEY_IMAGE = "image";
public DatabaseHandler(Context context) {
super(context, DATABASE_NAME, null, DATABASE_VERSION);
}
#Override
public void onCreate(SQLiteDatabase db) {
// TODO Auto-generated method stub
String CREATE_EVENTS_TABLE = "CREATE TABLE " + TABLE_EVENTS + "("
+ KEY_ID + " INTEGER," + KEY_TITLE + " TEXT,"
+ KEY_TIME + " TEXT," + KEY_DATE + " TEXT," + KEY_IMAGE + " BLOB" + ")";
db.execSQL(CREATE_EVENTS_TABLE);
}
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
// Drop older table if existed
db.execSQL("DROP TABLE IF EXISTS " + TABLE_EVENTS);
// Create tables again
onCreate(db);
}
/**
* All CRUD(Create, Read, Update, Delete) Operations
*/
//adding an event (NEEDS TO ADD DRAWABLE)
public void addEvent(Event event) {
SQLiteDatabase db = this.getWritableDatabase();
ContentValues values = new ContentValues();
values.put(KEY_ID, event.get_Id()); //Event ID
values.put(KEY_TITLE, event.get_title()); // Event Title
values.put(KEY_TIME, event.get_time()); // Event Time
values.put(KEY_DATE, event.get_date()); // Event Date
values.put(KEY_IMAGE, event.get_image()); // Event RESOURCEID
// Inserting Row
db.insert(TABLE_EVENTS, null, values);
db.close(); // Closing database connection
}
// Getting single contact
public Event getEvent(int id) {
SQLiteDatabase db = this.getReadableDatabase();
Cursor cursor = db.query(TABLE_EVENTS, new String[] { KEY_ID,
KEY_TITLE, KEY_TIME, KEY_DATE, KEY_IMAGE }, KEY_ID + "=?",
new String[] { String.valueOf(id) }, null, null, null, null);
if (cursor != null)
cursor.moveToFirst();
Event event = new Event(Integer.parseInt(cursor.getString(0)),
cursor.getString(1), cursor.getString(2), cursor.getString(3), cursor.getBlob(4));
// return contact
return event;
}
// Getting All Contacts
public ArrayList<Event> getAllContacts() {
ArrayList<Event> eventList = new ArrayList<Event>();
// Select All Query
String selectQuery = "SELECT * FROM " + TABLE_EVENTS;
SQLiteDatabase db = this.getWritableDatabase();
Cursor cursor = db.rawQuery(selectQuery, null);
// looping through all rows and adding to list
if (cursor.moveToFirst()) {
do {
Event event = new Event();
event.set_Id(Integer.parseInt(cursor.getString(0)));
event.set_title(cursor.getString(1));
event.set_time(cursor.getString(2));
event.set_date(cursor.getString(3));
event.set_image(cursor.getBlob(4));
eventList.add(event);
} while (cursor.moveToNext());
}
// return contact list
return eventList;
}
// Getting event Count
public int getEventsCount() {
String countQuery = "SELECT * FROM " + TABLE_EVENTS;
SQLiteDatabase db = this.getReadableDatabase();
Cursor cursor = db.rawQuery(countQuery, null);
cursor.close();
// return count
return cursor.getCount();
}
// Updating single contact
public int updateEvent(Event event) {
SQLiteDatabase db = this.getWritableDatabase();
ContentValues values = new ContentValues();
values.put(KEY_TITLE, event.get_title());
values.put(KEY_TIME, event.get_time());
values.put(KEY_DATE, event.get_date());
// updating row
return db.update(TABLE_EVENTS, values, KEY_ID + " = ?",
new String[] { String.valueOf(event.get_Id()) });
}
// Deleting single contact
public void deleteEvent(Event event) {
SQLiteDatabase db = this.getWritableDatabase();
db.delete(TABLE_EVENTS, KEY_ID + " = ?",
new String[] { String.valueOf(event.get_Id()) });
db.close();
}
}
EventAdapter
public class EventAdapter extends ArrayAdapter<Event> {
// View lookup cache
private static class ViewHolder {
//adding drawable to imageview
ImageView img;
TextView title;
TextView time;
TextView date;
}
public EventAdapter(Context context, ArrayList<Event> objects) {
super(context, R.layout.date_detail);
// TODO Auto-generated constructor stub
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
// Get the data item for this position
Event event = getItem(position);
// Check if an existing view is being reused, otherwise inflate the view
ViewHolder viewHolder;
if (convertView == null) {
viewHolder = new ViewHolder();
LayoutInflater inflater = LayoutInflater.from(getContext());
convertView = inflater.inflate(R.layout.date_detail, null);
viewHolder.title = (TextView) convertView
.findViewById(R.id.textViewTitle);
viewHolder.time = (TextView) convertView
.findViewById(R.id.textViewTime);
viewHolder.date = (TextView) convertView
.findViewById(R.id.textViewDate);
//adding drawable to imageview
viewHolder.img = (ImageView) convertView
.findViewById(R.id.imageView1);
convertView.setTag(viewHolder);
} else {
viewHolder = (ViewHolder) convertView.getTag();
}
// Populate the data into the template view using the data object
viewHolder.title.setText(event._title);
viewHolder.time.setText(event._time);
viewHolder.date.setText(event._date);
//convert from byte array to bitmap
Bitmap bitmap = convertByteArrayToBitmap(event._image);
// CONVERT BITMAP TO DRAWABLE
viewHolder.img.setImageBitmap(bitmap);
// Return the completed view to render on screen
return convertView;
}
public static Bitmap convertByteArrayToBitmap(
byte[] byteArrayToBeCOnvertedIntoBitMap)
{
Bitmap bitmap = BitmapFactory.decodeByteArray(
byteArrayToBeCOnvertedIntoBitMap, 0,
byteArrayToBeCOnvertedIntoBitMap.length);
return bitmap;
}
}

You are trying to remove the first item from an empty list. It says so in the exception text.

The problem was solved by removing the following lines of code in the swipeDismissViewListener and the OnActivityResult.
DatabaseHandler db = new DatabaseHandler(context);
EventAdapter adapter = new EventAdapter(context, db.getAllContacts());

Related

pass data from one activity to another and save it

i have two activities, each one have a listview. The first one contain the data and i want the other one to be as a favorite list. Right now i can pass the data with intent but its not saving. it shows when i start the intent but when i exit the second activity and go back to it with a custom button nothing is saved in the listview. Please tell me what to do. here is my code
public class MainActivity extends AppCompatActivity {
DB_Sqlite dbSqlite;
ListView listView;
String fav_name;
long fav_id;
ArrayAdapter adapter;
ArrayList arrayList;
String[] number;
Button button;
StringResourcesHandling srh;
Cursor getAllDataInCurrentLocale,getDataInCurrentLocaleById;
SimpleCursorAdapter favourites_adapter,non_favourites_adapter;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
listView = (ListView) findViewById(R.id.list_view);
SharedPreferences mPrefs = getPreferences(MODE_PRIVATE);
arrayList = new ArrayList<String>();
listView.setAdapter(adapter);
button = (Button) findViewById(R.id.button);
button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Intent intent = new Intent(MainActivity.this, cc.class);
startActivity(intent);
}
});
/* Show the resources for demo */
for (String s : StringResourcesHandling.getAllStringResourceNames()) {
Log.d("RESOURCEDATA", "String Resource Name = " + s +
"\n\tValue = " + StringResourcesHandling.getStringByName(this, s)
);
}
dbSqlite = new DB_Sqlite(this);
Cursor csr = dbSqlite.getAllDataInCurrentLocale(this);
DatabaseUtils.dumpCursor(csr);
csr.close();
}
#Override
protected void onDestroy() {
super.onDestroy();
getAllDataInCurrentLocale.close();
}
#Override
protected void onResume() {
super.onResume();
manageNonFavouritesListView();
}
private void manageNonFavouritesListView() {
getAllDataInCurrentLocale = dbSqlite.getAllDataInCurrentLocale(this);
if (non_favourites_adapter == null) {
non_favourites_adapter = new SimpleCursorAdapter(
this,
R.layout.textview,
getAllDataInCurrentLocale,
new String[]{FAVOURITES_COL_NAME},
new int[]{R.id.textview10},
0
);
listView.setAdapter(non_favourites_adapter);
setListViewHandler(listView,false);
} else {
non_favourites_adapter.swapCursor(getAllDataInCurrentLocale);
}
}
private void setListViewHandler(ListView listView, boolean favourite_flag) {
if (!favourite_flag) {
listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
if (i == 0) {
Intent intent = new Intent(MainActivity.this,tc.class);
startActivity(intent);
}
if (i == 1) {
Intent intent = new Intent(MainActivity.this,vc.class);
startActivity(intent);
}
}
});
listView.setOnItemLongClickListener(new AdapterView.OnItemLongClickListener() {
#Override
public boolean onItemLongClick(AdapterView<?> parent, View view, int position, long l) {
if (position == 0) {
Intent intent = new Intent(MainActivity.this, cc.class);
intent.putExtra("EXTRAKEY_ID",l); // THIS ADDED
startActivity(intent);}
String name = getAllDataInCurrentLocale.getString(getAllDataInCurrentLocale.getColumnIndex(FAVOURITES_COL_NAME));
Toast.makeText(MainActivity.this, name+" Added To Favorite", Toast.LENGTH_SHORT).show();
return true;
}
});
}}
}
public class DB_Sqlite extends SQLiteOpenHelper {
public static final String BDname = "data.db";
public static final int DBVERSION = 1; /*<<<<< ADDED BUT NOT NEEDED */
public static final String TABLE_FAVOURITES = "mytable";
public static final String FAVOURITES_COL_ID = BaseColumns._ID; /*<<<< use the Android stock ID name*/
public static final String FAVOURITES_COL_NAME = "name";
public static final String FAVOURITES_COL_FAVOURITEFLAG = "favourite_flag"; /*<<<<< NEW COLUMN */
public DB_Sqlite(#Nullable Context context) {
super(context, BDname, null, DBVERSION /*<<<<< used constant above */);
}
#Override
public void onCreate(SQLiteDatabase db) {
db.execSQL("create table " + TABLE_FAVOURITES + " (" +
FAVOURITES_COL_ID + " INTEGER PRIMARY KEY," + /*<<<<< AUTOINCREMENT NOT NEEDED AND IS INEFFICIENT */
FAVOURITES_COL_NAME + " TEXT, " +
FAVOURITES_COL_FAVOURITEFLAG + " INTEGER DEFAULT 0" + /*<<<<< COLUMN ADDED */
")");
/* CHANGES HERE BELOW loop adding all Resource names NOT VALUES */
ContentValues cv = new ContentValues();
for (String s: StringResourcesHandling.getAllStringResourceNames()) {
cv.clear();
cv.put(FAVOURITES_COL_NAME,s);
db.insert(TABLE_FAVOURITES,null,cv);
}
}
#Override
public void onUpgrade(SQLiteDatabase db, int i, int i1) {
db.execSQL("DROP TABLE IF EXISTS " + TABLE_FAVOURITES);
onCreate(db);
}
public boolean insertData(String name){
SQLiteDatabase db = this.getWritableDatabase();
ContentValues contentValues = new ContentValues();
contentValues.put(FAVOURITES_COL_NAME, name);
long result = db.insert(TABLE_FAVOURITES,null, contentValues);
if (result == -1)
return false;
else
return true;
}
public Cursor getFavouriteRows(boolean favourites) {
SQLiteDatabase db = this.getWritableDatabase();
String whereclause = FAVOURITES_COL_FAVOURITEFLAG + "=?";
String compare = "<1";
if (favourites) {
compare =">0";
}
return db.query(
TABLE_FAVOURITES,null,
FAVOURITES_COL_FAVOURITEFLAG + compare,
null,null,null,null
);
}
private int setFavourite(long id, boolean favourite_flag) {
SQLiteDatabase db = this.getWritableDatabase();
String whereclause = FAVOURITES_COL_ID + "=?";
String[] whereargs = new String[]{String.valueOf(id)};
ContentValues cv = new ContentValues();
cv.put(FAVOURITES_COL_FAVOURITEFLAG,favourite_flag);
return db.update(TABLE_FAVOURITES,cv,whereclause,whereargs);
}
public int setAsFavourite(long id) {
return setFavourite(id,true);
}
public int setAsNotFavourite(long id) {
return setFavourite(id, false);
}
/* Getting everything and make MatrixCursor VALUES from Resource names from Cursor with Resource names */
public Cursor getAllDataInCurrentLocale(Context context) {
SQLiteDatabase db = this.getWritableDatabase();
Cursor csr = db.query(TABLE_FAVOURITES,null,null,null,null,null,null);
if (csr.getCount() < 1) return csr;
MatrixCursor mxcsr = new MatrixCursor(csr.getColumnNames(),csr.getCount());
while (csr.moveToNext()) {
mxcsr.addRow(convertCursorRow(context,csr,new String[]{FAVOURITES_COL_NAME}));
}
csr.close();
return mxcsr;
}
public Cursor getDataInCurrentLocaleById(Context context, long id) {
SQLiteDatabase db = this.getWritableDatabase();
String wherepart = FAVOURITES_COL_ID + "=?";
String[] args = new String[]{String.valueOf(id)};
Cursor csr = db.query(TABLE_FAVOURITES,null,wherepart,args,null,null,null);
if (csr.getCount() < 1) return csr;
MatrixCursor mxcsr = new MatrixCursor(csr.getColumnNames(),csr.getCount());
while (csr.moveToNext()) {
mxcsr.addRow(convertCursorRow(context,csr,new String[]{FAVOURITES_COL_NAME}));
}
csr.close();
return mxcsr;
}
/* This getting columns from Cursor into String array (no BLOB handleing)*/
private String[] convertCursorRow(Context context, Cursor csr, String[] columnsToConvert) {
String[] rv = new String[csr.getColumnCount()];
for (String s: csr.getColumnNames()) {
boolean converted = false;
for (String ctc: columnsToConvert) {
if (csr.getType(csr.getColumnIndex(s)) == Cursor.FIELD_TYPE_BLOB) {
//........ would have to handle BLOB here if needed (another question if needed)
}
if (ctc.equals(s)) {
rv[csr.getColumnIndex(s)] = StringResourcesHandling.getStringByName(context,csr.getString(csr.getColumnIndex(s)));
converted = true;
}
} if (!converted) {
rv[csr.getColumnIndex(s)] = csr.getString(csr.getColumnIndex(s));
}
}
return rv;
}
}
public class cc extends AppCompatActivity {
String fav_name;
long fav_id;
DB_Sqlite dbSqlite;
SimpleCursorAdapter favourites_adapter;
ListView listView1;
ArrayList<String> arrayList1;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_cc);
listView1 = (ListView) findViewById(R.id.list_view1);
arrayList1 = new ArrayList<String>();
fav_id = getIntent().getLongExtra("EXTRAKEY_ID", 0);
if (fav_id == 0) {
}
dbSqlite = new DB_Sqlite(this);
Cursor cursor = dbSqlite.getDataInCurrentLocaleById(this, fav_id);
if (cursor.moveToFirst()) {
fav_name = cursor.getString(cursor.getColumnIndex(FAVOURITES_COL_NAME));
manageNonFavouritesListView();
}
cursor.close();
}
private void manageNonFavouritesListView() {
Cursor cursor = dbSqlite.getDataInCurrentLocaleById(this,fav_id);
if (favourites_adapter == null) {
favourites_adapter = new SimpleCursorAdapter(
this,
R.layout.textview,
cursor,
new String[]{FAVOURITES_COL_NAME},
new int[]{R.id.textview10},
0
);
listView1.setAdapter(favourites_adapter);
setListViewHandler(listView1,true);
} else {
favourites_adapter.swapCursor(cursor);
}
}
private void setListViewHandler(ListView listView1, boolean b) {
listView1.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
if (fav_id == 1) {
Intent intent = new Intent(cc.this, tc.class);
startActivity(intent);
}
if (fav_id == 2) {
Intent intent = new Intent(cc.this, vc.class);
startActivity(intent);
}
}
});
}
}
public class StringResourcesHandling {
private static final String[] allowedStringResourcePrefixes = new String[]{"db_"};
private static boolean loaded = false;
private static Field[] fields = R.string.class.getFields();
private static ArrayList<String> allowedStringResourceNames = new ArrayList<>();
private static void loadStringResources() {
if (loaded) return;
for (Field f: fields) {
if (isResourceNameAllowedPrefix(f.getName())) {
allowedStringResourceNames.add(f.getName());
}
}
loaded = true;
}
private static boolean isResourceNameAllowedPrefix(String resourceName) {
if (allowedStringResourcePrefixes.length < 1) return true;
for (String s: allowedStringResourcePrefixes) {
if (resourceName.substring(0,s.length()).equals(s)) return true;
}
return false;
}
public static String getStringByName(Context context, String name) {
String rv = "";
boolean nameFound = false;
if (!loaded) {
loadStringResources();
}
for (String s: allowedStringResourceNames) {
if (s.equals(name)) {
nameFound = true;
break;
}
}
if (!nameFound) return rv;
return context.getString(context.getResources().getIdentifier(name,"string",context.getPackageName()));
}
public static List<String> getAllStringResourceNames() {
if (!loaded) {
loadStringResources();
}
return allowedStringResourceNames;
}
}
note: i get the data in 1st listview from strings.xml
please help me thank u in advance
You can add a column say 'isFavourite' in your db table which has list vew data. When user mark listitem as favourite, save the change in db table . When user navigates to favourite list populate the list from. db table with favourite filter in select query.
I suggest using SharedPreferences. You stated that your value gets overwritten. That won't be the case if you create multiple keys.
Example:
Say you have an ArrayList of String you want to pass from ClassA to ClassB:
ClassA:
for (int i = 0; i < list.size(); i++) {
sharedPref.edit().putString("text" + i, "abcde").apply();
}
ClassB:
for (int i = 0; i < list.size(); i++) {
sharedPref.getString("text" + i, null);
}
If you have problems with the listsize, you can also pass the listsize to sharedpref and retrieve it again.

Database refusing to delete item

I was working on an app where the user will input text through an editText, and it will be stored into listView and DataBase.
But when I ran the code, the Item refused to delete.
InputContract.java
public class InputContract {
public static final String DB_NAME = "com.dobleu.peek.db";
public static final int DB_VERSION = 1;
public class TaskEntry implements BaseColumns {
public static final String TABLE = "tasks";
public static final String COL_TASK_TITLE = "title";
}
}
InputDbHelper.java
public class InputDbHelper extends SQLiteOpenHelper {
public InputDbHelper(Context context) {
super(context, InputContract.DB_NAME, null, InputContract.DB_VERSION);
}
#Override
public void onCreate(SQLiteDatabase db) {
String createTable = "CREATE TABLE " + InputContract.TaskEntry.TABLE + " ( " +
InputContract.TaskEntry._ID + " INTEGER PRIMARY KEY AUTOINCREMENT, " +
InputContract.TaskEntry.COL_TASK_TITLE + " TEXT NOT NULL);";
db.execSQL(createTable);
}
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
db.execSQL("DROP TABLE IF EXISTS " + InputContract.TaskEntry.TABLE);
onCreate(db);
}
}
MainActivity.java
public class MainActivity extends AppCompatActivity {
ListView list;
private ArrayList<String> items;
private ArrayAdapter<String> itemsAdapter;
ConstraintLayout l1;
ConstraintLayout l2;
TextView displayText;
TextView amt;
TextView itms;
private static int TIME = 1000;
private InputDbHelper mHelper;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
requestWindowFeature(Window.FEATURE_NO_TITLE);
getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,
WindowManager.LayoutParams. FLAG_FULLSCREEN);
setContentView(R.layout.activity_main);
init();
mHelper = new InputDbHelper(this);
updateUI();
int no = list.getAdapter().getCount();
amt.setText("" + no);
setupListViewListener();
}
private void setupListViewListener() {
list.setOnItemLongClickListener(
new AdapterView.OnItemLongClickListener() {
#Override
public boolean onItemLongClick(AdapterView<?> adapter,
View item, int pos, long id) {
// Remove the item within array at position
items.remove(pos);
// Refresh the adapter
SQLiteDatabase db = mHelper.getWritableDatabase();
db.delete(InputContract.TaskEntry.TABLE,
InputContract.TaskEntry.COL_TASK_TITLE + " = ?",
new String[]{"Name of entry you want deleted"});
db.close();
updateUI();
itemsAdapter.notifyDataSetChanged();
// Return true consumes the long click event (marks it handled)
return true;
}
});
}
public void init(){
ActionBar ab = getSupportActionBar();
assert ab != null;
ab.hide();
list = (ListView)findViewById(R.id.list);
displayText = (TextView)findViewById(R.id.displayText);
amt = (TextView)findViewById(R.id.amt);
itms = (TextView)findViewById(R.id.itms);
items = new ArrayList<String>();
itemsAdapter = new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1, items);
list.setAdapter(itemsAdapter);
l1 = (ConstraintLayout)findViewById(R.id.one);
l2 = (ConstraintLayout)findViewById(R.id.two);
Typeface regular = Typeface.createFromAsset(getAssets(), "fonts/regular.ttf");
Typeface bold = Typeface.createFromAsset(getAssets(), "fonts/bold.ttf");
amt.setTypeface(bold);
itms.setTypeface(regular);
displayText.setTypeface(regular);
}
public void add(View v){
AlertDialog.Builder dialogBuilder = new AlertDialog.Builder(this);
LayoutInflater inflater = this.getLayoutInflater();
final View dialogView = inflater.inflate(R.layout.dialog, null);
dialogBuilder.setView(dialogView);
final EditText edt = (EditText) dialogView.findViewById(R.id.edit1);
dialogBuilder.setTitle("Add Item");
dialogBuilder.setMessage("Enter text below");
dialogBuilder.setPositiveButton("Done", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int whichButton) {
String txt = edt.getText().toString();
items.add(txt);
SQLiteDatabase db = mHelper.getWritableDatabase();
ContentValues values = new ContentValues();
values.put(InputContract.TaskEntry.COL_TASK_TITLE, txt);
db.insertWithOnConflict(InputContract.TaskEntry.TABLE, null, values, SQLiteDatabase.CONFLICT_REPLACE);
db.close();
updateUI();
int no = list.getAdapter().getCount();
amt.setText("" + no);
}
});
dialogBuilder.setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int whichButton) {
//pass
}
});
AlertDialog b = dialogBuilder.create();
b.show();
}
public void play(View v){
Animation fadeOut = AnimationUtils.loadAnimation(this, abc_fade_out);
Animation fadeIn = AnimationUtils.loadAnimation(this, abc_fade_in);
l1.startAnimation(fadeOut);
l1.setVisibility(View.GONE);
l2.setVisibility(View.VISIBLE);
l2.startAnimation(fadeIn);
String[] array = new String[items.size()];
final String[] mStringArray = items.toArray(array);
final android.os.Handler handler = new android.os.Handler();
handler.post(new Runnable() {
int i = 0;
#Override
public void run() {
displayText.setText(mStringArray[i]);
i++;
if (i == mStringArray.length) {
handler.removeCallbacks(this);
} else {
handler.postDelayed(this, TIME);
}
}
});
}
public void one(View v){TIME = 1000;}
public void three(View v){TIME = 3000;}
public void five(View v){TIME = 5000;}
public void seven(View v){TIME = 7000;}
public void ten(View v){TIME = 10000;}
private void updateUI() {
ArrayList<String> taskList = new ArrayList<>();
SQLiteDatabase db = mHelper.getReadableDatabase();
Cursor cursor = db.query(InputContract.TaskEntry.TABLE,
new String[]{InputContract.TaskEntry._ID, InputContract.TaskEntry.COL_TASK_TITLE},
null, null, null, null, null);
while (cursor.moveToNext()) {
int idx = cursor.getColumnIndex(InputContract.TaskEntry.COL_TASK_TITLE);
taskList.add(cursor.getString(idx));
}
if (itemsAdapter== null) {
itemsAdapter= new ArrayAdapter<>(this, android.R.layout.simple_list_item_1,
taskList);
list.setAdapter(itemsAdapter);
} else {
itemsAdapter.clear();
itemsAdapter.addAll(taskList);
itemsAdapter.notifyDataSetChanged();
}
cursor.close();
db.close();
}
}
In MainActivity.java, specifically in setupListViewListener(), when the listView is held, it is supposed to delete the item that is being held. But the list only vibrates and remains the same. How can I fix this?
I suspect that your issue is that you have hard coded the TASK_TITLE to be deleted as "Name of entry you want deleted" as opposed to getting the TASK_TITLE from the item that was long clicked.
So try using :-
private void setupListViewListener() {
list.setOnItemLongClickListener(
new AdapterView.OnItemLongClickListener() {
#Override
public boolean onItemLongClick(AdapterView<?> adapter,
View item, int pos, long id) {
String title_of_row_to_delete = list.getItemAtPosition(i).toString(); //<<<<<<<<
// Remove the item within array at position
items.remove(pos);
// Refresh the adapter
SQLiteDatabase db = mHelper.getWritableDatabase();
db.delete(InputContract.TaskEntry.TABLE,
InputContract.TaskEntry.COL_TASK_TITLE + " = ?",
new String[]{title_of_row_to_delete}); //<<<<<<<<
db.close();
updateUI();
itemsAdapter.notifyDataSetChanged();
// Return true consumes the long click event (marks it handled)
return true;
}
});
}
This will extract the TASK_TITLE from the list and then use that as the argument to find the row to be deleted.
//<<<<<<<< indicates changed lines.

Android Listview not updating after delete item

I am working with sqllite. I have successfully create a database and I can input some values in my database. I can also show all values in listview and also i can remove item by listview's onitemclicklistener.i have one problem. when i delete item listview not updated,but this item is deleted in database.how i can solve this problem ?
DatabaseHandler .java code
public class DatabaseHandler extends SQLiteOpenHelper {
private static final int DATABASE_VERSION = 1;
private static final String DATABASE_NAME = "lvstone_2";
private static final String TABLE_CONTACTS = "CardTable1";
private static final String KEY_ID = "id";
private static final String KEY_Tittle = "name";
private static final String KEY_Description = "description";
private static final String KEY_Price = "price";
private static final String KEY_Counter = "counter";
private static final String KEY_Image = "image";
private final ArrayList<Contact> contact_list = new ArrayList<Contact>();
public static SQLiteDatabase db;
public DatabaseHandler(Context context) {
super(context, DATABASE_NAME, null, DATABASE_VERSION);
}
// Creating Tables
#Override
public void onCreate(SQLiteDatabase db) {
String CREATE_CONTACTS_TABLE = "CREATE TABLE " + TABLE_CONTACTS + "("
+ KEY_ID + " INTEGER PRIMARY KEY," + KEY_Tittle + " TEXT,"
+ KEY_Description + " TEXT,"
+ KEY_Price + " TEXT,"
+ KEY_Counter + " TEXT,"
+ KEY_Image + " TEXT"
+ ")";
db.execSQL(CREATE_CONTACTS_TABLE);
}
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
db.execSQL("DROP TABLE IF EXISTS " + TABLE_CONTACTS);
// Create tables again
onCreate(db);
}
// Adding new contact
public void Add_Contact(Contact contact) {
db = this.getWritableDatabase();
ContentValues values = new ContentValues();
if (!somethingExists(contact.getTitle())) {
values.put(KEY_Tittle, contact.getTitle()); // Contact title
values.put(KEY_Description, contact.getDescription()); // Contact//
// description
values.put(KEY_Price, contact.getPrice()); // Contact price
values.put(KEY_Counter, contact.getCounter()); // Contact image
values.put(KEY_Image, contact.getImage()); // Contact image
// Inserting Row
db.insert(TABLE_CONTACTS, null, values);
Log.e("Table Result isss", String.valueOf(values));
db.close(); // Closing database connection
}
}
public void deleteUser(String userName)
{
db = this.getWritableDatabase();
try
{
db.delete(TABLE_CONTACTS, "name = ?", new String[] { userName });
}
catch(Exception e)
{
e.printStackTrace();
}
finally
{
db.close();
}
}
// Getting single contact
Contact Get_Contact(int id) {
SQLiteDatabase db = this.getReadableDatabase();
Cursor cursor = db.query(TABLE_CONTACTS,
new String[] { KEY_ID, KEY_Tittle, KEY_Description, KEY_Price,
KEY_Counter, KEY_Image }, KEY_ID + "=?",
new String[] { String.valueOf(id) }, null, null, null);
if (cursor != null)
cursor.moveToFirst();
Contact contact = new Contact(cursor.getString(0), cursor.getString(1),
cursor.getString(2), cursor.getString(4), cursor.getString(5));
// return contact
cursor.close();
db.close();
return contact;
}
public boolean somethingExists(String x) {
Cursor cursor = db.rawQuery("select * from " + TABLE_CONTACTS
+ " where name like '%" + x + "%'", null);
boolean exists = (cursor.getCount() > 0);
Log.e("Databaseeeeeeeee", String.valueOf(cursor));
cursor.close();
return exists;
}
public ArrayList<Contact> Get_Contacts() {
try {
contact_list.clear();
// Select All Query
String selectQuery = "SELECT * FROM " + TABLE_CONTACTS;
SQLiteDatabase db = this.getWritableDatabase();
Cursor cursor = db.rawQuery(selectQuery, null);
// looping through all rows and adding to list
if (cursor.moveToFirst()) {
do {
Contact contact = new Contact();
contact.setTitle(cursor.getString(1));
contact.setDescription(cursor.getString(2));
contact.setPrice(cursor.getString(3));
contact.setCounter(cursor.getString(4));
contact.setImage(cursor.getString(5));
contact_list.add(contact);
} while (cursor.moveToNext());
}
cursor.close();
db.close();
return contact_list;
} catch (Exception e) {
// TODO: handle exception
Log.e("all_contact", "" + e);
}
return contact_list;
}
public int getProfilesCount() {
String countQuery = "SELECT * FROM " + TABLE_CONTACTS;
SQLiteDatabase db = this.getReadableDatabase();
Cursor cursor = db.rawQuery(countQuery, null);
int cnt = cursor.getCount();
cursor.close();
return cnt;
}
}
SQLAdapter.java code
public class StradaSQLAdapter extends BaseAdapter {
Activity activity;
int layoutResourceId;
Contact user;
ArrayList<Contact> data = new ArrayList<Contact>();
public ImageLoader imageLoader;
UserHolder holder = null;
public int itemSelected = 0;
public StradaSQLAdapter(Activity act, int layoutResourceId,
ArrayList<Contact> data) {
this.layoutResourceId = layoutResourceId;
this.activity = act;
this.data = data;
imageLoader = new ImageLoader(act.getApplicationContext());
notifyDataSetChanged();
}
#Override
public View getView(final int position, View convertView, ViewGroup parent) {
View row = convertView;
if (row == null) {
LayoutInflater inflater = LayoutInflater.from(activity);
holder = new UserHolder();
row = inflater.inflate(layoutResourceId, parent, false);
holder.Title = (TextView) row.findViewById(R.id.smalltitle1);
holder.counter = (TextView) row.findViewById(R.id.smallCounter1);
holder.dbcounter = (TextView) row
.findViewById(R.id.DBSliderCounter);
holder.Description = (TextView) row.findViewById(R.id.smallDesc1);
holder.layout = (RelativeLayout) row
.findViewById(R.id.DBSlideLayout);
holder.layoutmain = (RelativeLayout) row
.findViewById(R.id.DBSlideLayoutMain);
holder.Price = (TextView) row.findViewById(R.id.smallPrice1);
holder.pt = (ImageView) row.findViewById(R.id.smallthumb1);
holder.close = (ImageView) row.findViewById(R.id.DBSliderClose);
holder.c_minus = (ImageView) row.findViewById(R.id.counter_minus);
holder.c_plus = (ImageView) row.findViewById(R.id.counter_plus);
row.setTag(holder);
} else {
holder = (UserHolder) row.getTag();
}
user = data.get(position);
holder.Title.setText(user.getTitle());
holder.Description.setText(user.getDescription());
holder.Price.setText(user.getPrice() + " GEL");
holder.counter.setText(user.getCounter());
holder.dbcounter.setText(user.getCounter());
Log.e("image Url is........", data.get(position).toString());
imageLoader.DisplayImage(user.getImage(), holder.pt);
return row;
}
#Override
public int getCount() {
return data.size();
}
#Override
public Object getItem(int position) {
return data.get(position);
}
#Override
public long getItemId(int position) {
return 0;
}
public class UserHolder {
public TextView Price, counter, Description, Title, dbcounter;
public ImageView pt,close,c_plus,c_minus;
public RelativeLayout layout, layoutmain;
}
}
and Main java code
public class StradaChartFragments extends Fragment {
public static ListView list;
ArrayList<Contact> contact_data = new ArrayList<Contact>();
StradaSQLAdapter cAdapter;
private DatabaseHandler dbHelper;
UserHolder holder;
private RelativeLayout.LayoutParams layoutParams;
private ArrayList<Contact> contact_array_from_db;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.strada_chart_fragment,
container, false);
dbHelper = new DatabaseHandler(getActivity());
list = (ListView) rootView.findViewById(R.id.chart_listview);
cAdapter = new StradaSQLAdapter(getActivity(),
R.layout.listview_row_db, contact_data);
contact_array_from_db = dbHelper.Get_Contacts();
Set_Referash_Data();
list.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view,
final int position, long id) {
holder = (UserHolder) view.getTag();
layoutParams = (RelativeLayout.LayoutParams) holder.layoutmain
.getLayoutParams();
if (holder.layout.getVisibility() != View.VISIBLE) {
ValueAnimator varl = ValueAnimator.ofInt(0, -170);
varl.setDuration(1000);
varl.addUpdateListener(new AnimatorUpdateListener() {
#Override
public void onAnimationUpdate(ValueAnimator animation) {
layoutParams.setMargins(
(Integer) animation.getAnimatedValue(), 0,
0, 0);
holder.layoutmain.setLayoutParams(layoutParams);
}
});
varl.start();
holder.layout.setVisibility(View.VISIBLE);
}
holder.close.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View arg0) {
ValueAnimator var2 = ValueAnimator.ofInt(-170, 0);
var2.setDuration(1000);
var2.addUpdateListener(new AnimatorUpdateListener() {
#Override
public void onAnimationUpdate(
ValueAnimator animation) {
dbHelper.deleteUser(contact_array_from_db.get(position).getTitle());
if (contact_data.size() > 0)
contact_data.remove(position);
layoutParams.setMargins(0, 0,
(Integer) animation.getAnimatedValue(),
0);
holder.layoutmain.setLayoutParams(layoutParams);
holder.layout.setVisibility(View.INVISIBLE);
}
});
var2.start();
}
});
}
});
return rootView;
}
public void Set_Referash_Data() {
contact_data.clear();
for (int i = 0; i < contact_array_from_db.size(); i++) {
String title = contact_array_from_db.get(i).getTitle();
String Description = contact_array_from_db.get(i).getDescription();
String Price = contact_array_from_db.get(i).getPrice();
String Counter = contact_array_from_db.get(i).getCounter();
String image = contact_array_from_db.get(i).getImage();
Contact cnt = new Contact();
cnt.setTitle(title);
cnt.setDescription(Description);
cnt.setPrice(Price);
cnt.setCounter(Counter);
cnt.setImage(image);
contact_data.add(cnt);
}
dbHelper.close();
list.setAdapter(cAdapter);
Log.e("Adapter issss ...", String.valueOf(cAdapter));
}
}
i can remove item in database ,but listview not updated . what am i doing wrong ? if anyone knows solution help me
thanks
Under your method dbHelper.deleteUser add this code:
contact_data.remove(position);
To function in addition to deleting it from the database also have to delete the array of objects that you sent to adapter.
EDIT:
Add one remove method in your adapter for you can remove object. Code:
Adapter:
public void removeObject (int position) {
this.data.remove(position);
}
Activity:
Change:
contact_data.remove(position);
to:
cAdapter.removeObject(position);
cAdapter.notifyDataSetChanged();
EDIT 2:
Just delete all the objects from ArrayList.
contact_data.clear();
or in your adapter
data.clear();

Android: Save Selected Contacts TO SQLite DataBase

In my app, I am allowing user to select five contact(one by one) so that I can send a custom message to selected contacts. I want to save the selected contacts to the DataBase. When user clicks on "Pick Contact Button", it opens phone's contact book and the selected contact will get displayed in List View. Similarly, he can add 5 contacts for which I want to save them in DataBase. I have been able to write some code but don't how to save the contact.Please Help.
MainActivity.java
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
message = (EditText) findViewById(R.id.et_message);
DatabaseHandler db = new DatabaseHandler(this);
/**
* CRUD Operations
* */
// Inserting Contacts
Log.d("Insert: ", "Inserting ..");
// Reading all contacts
Log.d("Reading: ", "Reading all contacts..");
List<ContactItems> contacts = db.getAllContacts();
for (ContactItems cn : contacts) {
String log = "Id: "+cn.getType()+" ,Name: " + cn.getName() + " ,Phone: " + cn.getNumber();
// Writing Contacts to log
Log.d("Name: ", log);
}
/************************** saving custom message *****************************/
// for saving text that user can change as per need
final SharedPreferences preferences = PreferenceManager
.getDefaultSharedPreferences(this);
// loads the text that has been stored to SP and set it to Edit Text
message.setText(preferences.getString("autoSave", ""));
// adding addTextChangedListner() to the Edit Text View
message.addTextChangedListener(new TextWatcher() {
#Override
public void onTextChanged(CharSequence s, int start, int before,
int count) {
// TODO Auto-generated method stub
}
#Override
public void beforeTextChanged(CharSequence s, int start, int count,
int after) {
// TODO Auto-generated method stub
}
#Override
public void afterTextChanged(Editable s) {
// TODO Auto-generated method stub
// saving text after it is changed by the user
preferences.edit().putString("autoSave", s.toString()).commit();
}
});
ListView contactlist = (ListView) findViewById(R.id.contactListitems);
Resources res = getResources();
adapter = new CustomAdapter(MainActivity.this, selectedContactList, res);
contactlist.setAdapter(adapter);
/**************************EDIT******************************************/
contactlist.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> arg0, View arg1, int arg2,
long arg3) {
// TODO Auto-generated method stub
String contactData = selectedContactList.get(arg2).toString();
}
});
// defining button elements for picking contacts from phone-book
btn_cntct = (Button) findViewById(R.id.bpickperson);
btn_cntct.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View arg0) {
if (selectedContactList.size() < 5) {
// TODO Auto-generated method stub
// using Intent for fetching contacts from phone-book
Intent intent = new Intent(Intent.ACTION_GET_CONTENT);
intent.setType(ContactsContract.CommonDataKinds.Phone.CONTENT_ITEM_TYPE);
startActivityForResult(intent, REQUESTCODE);
} else {
// print toast for not allowing user to add more contacts
Toast.makeText(getApplicationContext(),
"You Can Only Add 5 Contacts ", Toast.LENGTH_SHORT)
.show();
}
}
});
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
// TODO Auto-generated method stub
super.onActivityResult(requestCode, resultCode, data);
if (data != null) {
Uri uri = data.getData();
Log.i("data", uri.toString());
if (uri != null) {
Cursor c = null;
try {
c = getContentResolver()
.query(uri,
new String[] {
ContactsContract.CommonDataKinds.Phone.DISPLAY_NAME,
ContactsContract.CommonDataKinds.Phone.NUMBER,
ContactsContract.CommonDataKinds.Phone.TYPE },
null, null, null);
if (c != null && c.moveToFirst()) {
final ContactItems item = new ContactItems(
c.getString(0), c.getString(1), c.getInt(2));
item.setName(c.getString(0));
item.setNumber(c.getString(1));
item.setType(c.getInt(2));
selectedContactList.add(item);
Set<ContactItems> s = new TreeSet<ContactItems>(
new Comparator<ContactItems>() {
#Override
public int compare(ContactItems o1,
ContactItems o2) {
// for preventing duplicacy of contacts
// and calling toast
if (o1.number.equals(o2.number)) {
Toast.makeText(
getApplicationContext(),
"Selected Number Already Exists",
Toast.LENGTH_SHORT).show();
} else {
}
return o1.getNumber().compareTo(
o2.getNumber());
}
});
s.addAll(selectedContactList);
selectedContactList.clear();
selectedContactList.addAll(s);
adapter.notifyDataSetChanged();
// save the task list to preference
}
} finally {
if (c != null) {
c.close();
}
}
}
}
}
}
ContactItems.java
public class ContactItems {
String name = "";
String number = "";
int type = 0;
public ContactItems(String name, String number, int type) {
super();
this.name = name;
this.number = number;
this.type = type;
}
public ContactItems(Parcel source) {
// TODO Auto-generated constructor stub
this.name = source.readString();
this.number = source.readString();
this.type = source.readInt();
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getNumber() {
return number;
}
public void setNumber(String number) {
this.number = number;
}
public int getType() {
return type;
}
public void setType(int type) {
this.type = type;
}
public static final Parcelable.Creator<ContactItems> CREATOR = new Parcelable.Creator<ContactItems>() {
#Override
public ContactItems createFromParcel(Parcel source) {
return new ContactItems(source);
}
#Override
public ContactItems[] newArray(int size) {
return new ContactItems[size];
}
};
}
DatabaseHandler.java
public class DatabaseHandler extends SQLiteOpenHelper {
// All Static variables
// Database Version
private static final int DATABASE_VERSION = 1;
// Database Name
private static final String DATABASE_NAME = "contactManager";
// contact table name
private static final String TABLE_CONTACTS = "contacts";
// contacts table column names
private static final String KEY_NAME = "name";
private static final String KEY_PH_NO = "phone_number";
private static final String KEY_ID = "id";
public DatabaseHandler(Context context) {
super(context, DATABASE_NAME, null, DATABASE_VERSION);
// TODO Auto-generated constructor stub
}
// Creating Tables
#Override
public void onCreate(SQLiteDatabase db) {
// TODO Auto-generated method stub
String CREATE_CONACTS_TABLE = "CREATE TABLE " + TABLE_CONTACTS + "("
+ KEY_ID + " INTEGER PRIMARY KEY," + KEY_NAME + " TEXT,"
+ KEY_PH_NO + " TEXT" + ")";
db.execSQL(CREATE_CONACTS_TABLE);
}
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
// TODO Auto-generated method stub
db.execSQL("DROP TABLE IF EXISTS" + TABLE_CONTACTS);
onCreate(db);
}
/**
* All CRUD(Create, Read, Update, Delete) Operations
*/
// Adding new contact
void addContact(ContactItems contact) {
SQLiteDatabase db = this.getWritableDatabase();
ContentValues values = new ContentValues();
values.put(KEY_NAME, contact.getName()); // Contact Name
values.put(KEY_PH_NO, contact.getNumber()); // Contact Phone
// Inserting Row
db.insert(TABLE_CONTACTS, null, values);
db.close(); // Closing database connection
}
// Getting single contact
ContactItems getContact(int id) {
SQLiteDatabase db = this.getReadableDatabase();
Cursor cursor = db.query(TABLE_CONTACTS, new String[] { KEY_ID,
KEY_NAME, KEY_PH_NO }, KEY_ID + "=?",
new String[] { String.valueOf(id) }, null, null, null, null);
if (cursor != null)
cursor.moveToFirst();
ContactItems contact = new ContactItems(cursor.getString(2),
cursor.getString(1), Integer.parseInt(cursor.getString(0)));
// return contact
return contact;
}
// Getting All Contacts
public List<ContactItems> getAllContacts() {
List<ContactItems> contactList = new ArrayList<ContactItems>();
// Select All Query
String selectQuery = "SELECT * FROM " + TABLE_CONTACTS;
SQLiteDatabase db = this.getWritableDatabase();
Cursor cursor = db.rawQuery(selectQuery, null);
// looping through all rows and adding to list
if (cursor.moveToFirst()) {
do {
ContactItems contact = new ContactItems(null);
contact.setType(Integer.parseInt(cursor.getString(0)));
contact.setName(cursor.getString(1));
contact.setNumber(cursor.getString(2));
// Adding contact to list
contactList.add(contact);
} while (cursor.moveToNext());
}
// return contact list
return contactList;
}
// Updating single contact
public int updateContact(ContactItems contact) {
SQLiteDatabase db = this.getWritableDatabase();
ContentValues values = new ContentValues();
values.put(KEY_NAME, contact.getName());
values.put(KEY_PH_NO, contact.getNumber());
// updating row
return db.update(TABLE_CONTACTS, values, KEY_ID + " = ?",
new String[] { String.valueOf(contact.getType()) });
}
// Deleting single contact
public void deleteContact(ContactItems contact) {
SQLiteDatabase db = this.getWritableDatabase();
db.delete(TABLE_CONTACTS, KEY_ID + " = ?",
new String[] { String.valueOf(contact.getType()) });
db.close();
}
// Getting contacts Count
public int getContactsCount() {
String countQuery = "SELECT * FROM " + TABLE_CONTACTS;
SQLiteDatabase db = this.getReadableDatabase();
Cursor cursor = db.rawQuery(countQuery, null);
cursor.close();
// return count
return cursor.getCount();
}
}
CustomAdapter.java
public class CustomAdapter extends BaseAdapter {
/*********** Declare Used Variables *********/
private Activity activity;
private ArrayList<ContactItems> data;
private static LayoutInflater inflater = null;
public Resources res;
// ListModel tempValues=null;
int i = 0;
String selectedNum = " ";
/************* CustomAdapter Constructor *****************/
public CustomAdapter(Activity a, ArrayList<ContactItems> d,
Resources resLocal) {
/********** Take passed values **********/
activity = a;
data = d;
res = resLocal;
/*********** Layout inflator to call external xml layout () ***********/
inflater = (LayoutInflater) activity
.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
}
/******** What is the size of Passed Arraylist Size ************/
public int getCount() {
if (data.size() <= 0)
return 1;
return data.size();
}
public Object getItem(int position) {
return position;
}
public long getItemId(int position) {
return position;
}
/********* Create a holder Class to contain inflated xml file elements *********/
public static class ViewHolder {
public TextView text;
public TextView textNumber;
public ImageView image;
}
/****** Depends upon data size called for each row , Create each ListView row *****/
#SuppressLint("DefaultLocale")
public View getView(int position, View convertView, ViewGroup parent) {
final int pos = position;
View vi = convertView;
ViewHolder holder;
// check if converView is null, if it is null it probably means
if (convertView == null) {
/****** Inflate tabitem.xml file for each row ( Defined below ) *******/
vi = inflater.inflate(R.layout.contactlistitem, null);
/****** View Holder Object to contain tabitem.xml file elements ******/
// if it is not null, just reuse it from the recycler
holder = new ViewHolder();
holder.text = (TextView) vi.findViewById(R.id.contactname);
holder.textNumber = (TextView) vi.findViewById(R.id.contactnumber);
holder.image = (ImageView) vi.findViewById(R.id.deleteimage);
/************ Set holder with LayoutInflater ************/
vi.setTag(holder);
} else
holder = (ViewHolder) vi.getTag();
if (data.size() <= 0) {
holder.text.setText("Add Contacts");
holder.textNumber.setText(" ");
holder.image.setVisibility(View.GONE);
} else {
/***** Get each Model object from Arraylist ********/
/************ Set Model values in Holder elements ***********/
holder.text.setText("" + data.get(position).getName());
holder.textNumber.setText("" + data.get(position).getNumber());
holder.image.setVisibility(View.VISIBLE);
holder.image.setImageResource(res.getIdentifier("delete_button",
null, null));
holder.image.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
AlertDialog.Builder build = new AlertDialog.Builder(
activity);
build.setTitle("Delete");
build.setMessage("Are You Sure");
build.setPositiveButton("Delete",
new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog,
int which) {
// TODO Auto-generated method stub
data.remove(pos);
MainActivity.adapter.notifyDataSetChanged();
dialog.dismiss();
}
});
/*
* data.remove(pos);
* MainActivity.adapter.notifyDataSetChanged();
*/
build.setNegativeButton("Cancel",
new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog,
int which) {
// TODO Auto-generated method stub
dialog.dismiss();
}
});
build.show();
}
});
/******** Set Item Click Listner for LayoutInflater for each row *******/
}
// return the view for a single item in the listview
return vi;
}
}

Content Resolver pointing to wrong table with correct URI

I am having a problem on the line where I call the query to PostCategoryContent Provider
I get an error stating:
11-13 10:23:40.674: E/AndroidRuntime(26012): android.database.sqlite.SQLiteException: no such column: category_id (code 1): , while compiling: SELECT * FROM post WHERE (category_id=39)
Even though the URI points to another Table postCategory
Can anyone guide me on what I'm doing wrong?
public class PostFragment extends SherlockListFragment implements LoaderCallbacks<Cursor> {
private SimpleCursorAdapter adapter;
private boolean dataRetrieved;
private SlidingArea parent;
PullToRefreshListView pullToRefreshView;
EditText searchBox;
Bundle args = new Bundle();
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
parent = (SlidingArea) getActivity();
setHasOptionsMenu(true);
fillData(false);
}
#Override
public void onResume() {
super.onResume();
parent.getSupportActionBar().setCustomView(R.layout.kpmg_actionbar_list_view);
parent.getSupportActionBar().setDisplayShowCustomEnabled(true);
parent.getSupportActionBar().setDisplayHomeAsUpEnabled(true);
final ImageView searchButton = (ImageView) parent.findViewById(R.id.kpmg_actionbar_image_search_list);
searchButton.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
if (searchBox.getVisibility() == View.GONE)
{
searchBox.setVisibility(View.VISIBLE);
searchBox.requestFocus();
InputMethodManager imm = (InputMethodManager) parent.getSystemService(Context.INPUT_METHOD_SERVICE);
imm.showSoftInput(searchBox, InputMethodManager.SHOW_IMPLICIT);
} else {
searchBox.setVisibility(View.GONE);
searchBox.clearFocus();
hideKeyboard(v);
}
}
});
final ImageView refreshButton = (ImageView) parent.findViewById(R.id.kpmg_actionbar_image_refresh_list);
refreshButton.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
getData(getString(R.string.kpmg_json_get_articles), true);
refreshButton.setImageResource(R.drawable.kpmg_actionbar_refresh_dark);
fillData(true);
}
});
searchBox.addTextChangedListener(new TextWatcher() {
#Override
public void onTextChanged(CharSequence cs, int arg1, int arg2, int arg3) {
// When user changed the Text
filterData(cs);
}
#Override
public void beforeTextChanged(CharSequence arg0, int arg1, int arg2,
int arg3) {
// TODO Auto-generated method stub
}
#Override
public void afterTextChanged(Editable s) {
// TODO Auto-generated method stub
}
});
}
//Constant used as key for ID being passed in the bundle between fragments
public static final String NEWS_ID = "newsID";
private void getData(String url, boolean showProgressDialog) {
new Request(showProgressDialog).execute(new String[] {url});
}
public class Request extends AsyncTask<String, Void, String> {
ProgressDialog dialog;
/* This is the only file that needs to be edited */
private GetResponse response = null;
private boolean showProgressDialog = true;
public Request(boolean showProgressDialog)
{
super();
this.showProgressDialog = showProgressDialog;
response = new GetResponse();
}
#Override
protected void onPreExecute() {
if (showProgressDialog) {
dialog = new ProgressDialog(parent);
dialog.setMessage("Retrieving latest information...");
dialog.setIndeterminate(true);
dialog.setCancelable(false);
dialog.show();
}
}
//This method must return the type specified in the constructor
#Override
protected String doInBackground(String... url) {
response.setUrl(url[0]);
String res = response.execute();
// When it returns the "res" it will call onPostExecute
return res;
}
#Override
protected void onPostExecute(String result) {
// Here we have response from server
if ( isNetworkAvailable() ){
try {
JSONObject json = new JSONObject(result);
JSONArray arr = json.getJSONArray("posts");
for (int i = arr.length() - 1; i >= 0; --i) {
JSONObject row = arr.getJSONObject(i);
JSONArray arrCategories = row.getJSONArray("categories");
int Created = 0;
int Updated = 0;
for (int j = arrCategories.length() -1; j >= 0; --j){
JSONObject rowCategory = arrCategories.getJSONObject(j);
ContentValues categoryValues = new ContentValues();
categoryValues.put(PostCategoryTable.CATEGORY_ID, rowCategory.getInt("id"));
Cursor categoryCursor = parent.getContentResolver().query(PostCategoryContentProvider.CONTENT_URI, null, PostCategoryTable.CATEGORY_ID + "=" + categoryValues.getAsString(PostCategoryTable.CATEGORY_ID), null, null);
int categoryCount = categoryCursor.getCount();
if (categoryCount == 0) {
categoryValues.put(PostCategoryTable.ICON_NAME, rowCategory.getString("slug"));
categoryValues.put(PostCategoryTable.CATEGORY_NAME, rowCategory.getString("title"));
categoryValues.put(PostCategoryTable.PARENT_ID, rowCategory.getInt("parent"));
parent.getContentResolver().insert(PostCategoryContentProvider.CONTENT_URI, categoryValues);
Created++;
}
else {
categoryCursor.moveToFirst();
categoryValues.put(PostCategoryTable.ICON_NAME, rowCategory.getString("slug"));
categoryValues.put(PostCategoryTable.CATEGORY_NAME, rowCategory.getString("title"));
categoryValues.put(PostCategoryTable.PARENT_ID, rowCategory.getInt("parent"));
parent.getContentResolver().update(PostCategoryContentProvider.CONTENT_URI, categoryValues, PostCategoryTable.CATEGORY_ID + "=" + categoryValues.getAsString(PostCategoryTable.CATEGORY_ID), null);
Updated++;
}
categoryCursor.close();
}
Toast.makeText(parent,"Created : " + "" + Created + " | Updated : " + "" + Updated, Toast.LENGTH_SHORT).show();
if (row.getString("status").equals("publish")) {
ContentValues values = new ContentValues();
values.put(PostTable.POST_ID, row.getString("id"));
values.put(PostTable.CONTENT, Html.fromHtml(row.getString(PostTable.CONTENT)).toString());
values.put(PostTable.EXCERPT, Html.fromHtml(row.getString(PostTable.EXCERPT)).toString());
//image
//imageurl
values.put(PostTable.DATE_MODIFIED, row.getString(PostTable.DATE_MODIFIED));
values.put(PostTable.DATE_PUBLISHED, row.getString(PostTable.DATE_PUBLISHED));
//thumbnail
//thumbnailurl
values.put(PostTable.TITLE, row.getString(PostTable.TITLE));
values.put(PostTable.URL, row.getString("online-url"));
values.put(PostTable.VIDEO_URL, row.getString("video-url"));
//Check for new Categories
//getThumbnail
// byte[] image = AppHelper.getBlobFromURL(row.getString(BlogTable.THUMBNAIL));
// if (image != null) {
//
// values.put(BlogTable.THUMBNAIL, image);
//
// }
Cursor c = parent.getContentResolver().query(PostContentProvider.CONTENT_URI, null, PostTable.POST_ID + "=" + values.getAsString(PostTable.POST_ID), null, null);
int count = c.getCount();
if (count == 0) {
parent.getContentResolver().insert(PostContentProvider.CONTENT_URI, values);
}
else {
c.moveToFirst();
if (!(c.getString(c.getColumnIndex(PostTable.DATE_MODIFIED)).equalsIgnoreCase(values.getAsString(PostTable.DATE_MODIFIED)))) {
//
//
// if (c.getString(c.getColumnIndex(BlogTable.THUMBNAIL)) != values.get(BlogTable.THUMBNAIL)){
// //reset image
// }
//
parent.getContentResolver().update(PostContentProvider.CONTENT_URI, values, PostTable.POST_ID + "=" + values.getAsString(PostTable.POST_ID), null);
}
}
c.close();
//Here we should last retrieved time and used as part of the condition before retrieving data
}
else {
String currentID = row.getString("id");
// Delete unpublished fields
parent.getContentResolver().delete(PostContentProvider.CONTENT_URI, "_id = " + currentID, null);
}
}
} catch (JSONException e) {
e.printStackTrace();
}
}
else {
Toast toast = Toast.makeText( parent , "You are not connected to the internet. Please check your connection, or try again later",
Toast.LENGTH_SHORT);
toast.show();
}
// Call onRefreshComplete when the list has been refreshed.
pullToRefreshView.onRefreshComplete();
super.onPostExecute(result);
ImageView refreshButton = (ImageView) parent.findViewById(R.id.kpmg_actionbar_image_refresh_list);
refreshButton.setImageResource(R.drawable.kpmg_actionbar_refresh);
if (showProgressDialog) {
dialog.dismiss();
}
}
}
private void fillData(boolean isRefresh){
//_id is expected from this method that is why we used it earlier
String[] from = new String[] { PostTable.TITLE, PostTable.DATE_PUBLISHED, PostTable.EXCERPT};
int[] to = new int[] { R.id.kpmg_text_news_title, R.id.kpmg_text_news_date, R.id.kpmg_text_news_excerpt};
//initialize loader to call this class with a callback
if (!isRefresh){
getLoaderManager().initLoader(0, null, this);
}
else {
if (searchBox.getText().length() == 0) {
getLoaderManager().restartLoader(0, null, this);
}
else {
getLoaderManager().restartLoader(0, args, this);
}
}
//We create adapter to fill list with data, but we don't provide any data as it will be done by loader
adapter = new SimpleCursorAdapter(parent, R.layout.kpmg_list_view, null, from, to, 0);
adapter.setViewBinder(new SimpleCursorAdapter.ViewBinder() {
#Override
public boolean setViewValue(View view, Cursor cursor, int column) {
if( column == cursor.getColumnIndex(PostTable.DATE_PUBLISHED) ){ // let's suppose that the column 0 is the date
TextView textDate = (TextView) view.findViewById(R.id.kpmg_text_news_date);
String dateStr = cursor.getString(cursor.getColumnIndex(PostTable.DATE_PUBLISHED));
String formattedDate = AppHelper.calculateRelativeDate(dateStr);
textDate.setText( "Posted - " + formattedDate);
return true;
}
return false;
}
});
setListAdapter(adapter);
}
private void filterData(CharSequence cs){
args.putString("Selection", cs.toString());
getLoaderManager().restartLoader(0, args, this /*LoaderCallbacks<Cursor>*/);
}
#Override
public Loader<Cursor> onCreateLoader(int arg0, Bundle args) {
String[] projection = new String[] { PostTable.TITLE, PostTable.DATE_PUBLISHED, PostTable.EXCERPT, PostTable.ID };
CursorLoader loader;
if (args == null) {
Log.i("Arguments","None");
loader = new CursorLoader(parent, PostContentProvider.CONTENT_URI, projection, null, null, PostTable.DATE_PUBLISHED + " DESC");
}
else {
Log.i("Arguments","Full");
String selectionKeyword = args.getString("Selection");
String selection = PostTable.TITLE + " LIKE ? OR " + PostTable.CONTENT + " LIKE ? OR " + PostTable.EXCERPT + " LIKE ?";
String[] selectionArgs = new String[] {"%" + selectionKeyword + "%","%" + selectionKeyword + "%","%" + selectionKeyword + "%"};
loader = new CursorLoader(parent, PostContentProvider.CONTENT_URI, projection, selection, selectionArgs, PostTable.DATE_PUBLISHED + " DESC");
}
return loader;
}
public void onLoadFinished(Loader<Cursor> arg0, Cursor data) {
adapter.swapCursor(data);
}
public void onLoaderReset(Loader<Cursor> arg0) {
adapter.swapCursor(null);
}
}
On which line is the exception thrown? The problem is more likely an issue with your SQLite syntax than with anything having to do with Loaders or Cursors. Make sure your table is getting initialized as you require. Do a DatabaseUtils.dumpCursor(cursor) to analyze the contents of the Cursor between the exception is thrown. Also, I would look into your use of LIKE... I have seen people having issues with that keyword before.

Categories

Resources