Listview not getting refreshed with SimpleCursorAdapter - android

I have written a program to update my listview using SimpleCursorAdapter.
I have an EditText to enter mobile number and when I click on add , the mobile number is getting stored inside my sqlite database and at the same time displaying it inside the listview. But the problem is the listview is not getting refreshed , I have tried using notifyDataSetChanged() but not working.
Home_Page.java : This is the activity where I am updating my listview
try{
dbListHelper = new DriverSqliteHelper(getBaseContext());
dbListHelper.open(getBaseContext());
}catch (Exception e){
e.printStackTrace();
}
columns = new String[]{DriverSqliteHelper.DbListHelper.DRIVER_USER_ID};
to = new int[]{R.id.DriverId};
getLoaderManager().initLoader(0, null, this);
columns = new String[]{DriverSqliteHelper.DbListHelper.DRIVER_USER_ID};
to = new int[]{R.id.DriverId};
driverStatusAdapter = new DriverStatusAdapter(getBaseContext(),
R.layout.view_userid_item,null,columns,to,0);
listDriverId.setAdapter(driverStatusAdapter);
#Override
public Loader<Cursor> onCreateLoader(int i, Bundle bundle) {
return new CustomCursorLoader(getBaseContext());
}
#Override
public void onLoadFinished(Loader<Cursor> loader, Cursor cursor) {
if(driverStatusAdapter!=null && cursor!=null) {
driverStatusAdapter.swapCursor(cursor);
driverStatusAdapter.notifyDataSetChanged();
}else {
Log.v("Adapter null","OnLoadFinished: mAdapter is null");
}
}
#Override
public void onLoaderReset(Loader<Cursor> loader) {
if(driverStatusAdapter!=null) {
driverStatusAdapter.swapCursor(null);
} else {
Log.v("Adapter null", "OnLoadReset: mAdapter is null");
}
}
#Override
protected void onResume() {
super.onResume();
getLoaderManager().restartLoader(0x01, null, this);
}
I have used CustomCursorLoader class for querying the results.
public class CustomCursorLoader extends CursorLoader{
Context context;
DriverSqliteHelper driverSqliteHelper;
Cursor cursor;
public CustomCursorLoader(Context context) {
super(context);
try {
driverSqliteHelper = new DriverSqliteHelper(context);
driverSqliteHelper.open(context);
}catch (Exception e){
e.printStackTrace();
}
}
public Cursor loadInBackground(){
cursor = driverSqliteHelper.getDriverStatus();
return cursor;
}
}
When I restart my app the listview is updated but not automatically when I click on add button from the same activity.
I have been stuck on this for a long time and I don't know what to do now to refresh the listview whenever I click on add.
Any help is appreciated.

Related

AsyncTaskLoader not calling onFinishedLoad after orientation change

Some background information:
I am using a Activity>ParentFragment(Holds ViewPager)>Child fragments.
Child Fragments are added dynamically with add, remove buttons.
I am using MVP architecture
Actual Problem:
In child fragment, we have listview that populates using an asynctaskloader via a presenter.
Child Fragment:
//Initialize Views
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
root = inflater.inflate(R.layout.fragment_search_view_child, container, false);
.......
mSearchViewPresenter= new SearchViewPresenter(
getActivity(),
new GoogleSuggestLoader(getContext()),
getActivity().getLoaderManager(),
this, id
);
SearchList list=new SearchList();
//requestList from presenter
searchListAdapter =new SearchViewListAdapter(getActivity(), list, this);
listView.setAdapter(searchListAdapter);
......
return root;
}
#Override
public void onResume(){
super.onResume();
mSearchViewPresenter.start();
searchBar.addTextChangedListener(textWatcher);
}
In the presenter class we have:
public SearchViewPresenter(#NonNull Context context, #NonNull GoogleSuggestLoader googleloader,#NonNull LoaderManager loaderManager,
#NonNull SearchViewContract.View tasksView, #NonNull String id) {
// mLoader = checkNotNull(loader, "loader cannot be null!");
mLoaderManager = checkNotNull(loaderManager, "loader manager cannot be null");
// mTasksRepository = checkNotNull(tasksRepository, "tasksRepository cannot be null");
mSearchView = checkNotNull(tasksView, "tasksView cannot be null!");
mSearchView.setPresenter(this);
searchList=new SearchList();
this.googleLoader=googleloader;
this.context=context;
this.id=loaderID;
// this.id=Integer.parseInt(id);
}
#Override
public void start() {
Log.d("start>initloader","log");
mLoaderManager.restartLoader(1, null, this);
}
//TODO implement these when you are ready to use loader to cache local browsing history
#Override
public android.content.Loader<List<String>> onCreateLoader(int i, Bundle bundle) {
int loaderid=googleLoader.getId();
Log.d("Loader: ", "created");
googleLoader=new GoogleSuggestLoader(context);
googleLoader.setUrl("");
googleLoader.setUrl(mSearchView.provideTextQuery());
return googleLoader;
}
#Override
public void onLoadFinished(android.content.Loader<List<String>> loader, List<String> data) {
Log.d("Loader: ", "loadFinished");
searchList.clear();
for (int i = 0; i < data.size(); ++i) {
searchList.addListItem(data.get(i), null, LIST_TYPE_SEARCH, android.R.drawable.btn_plus);
Log.d("data Entry: ",i+ " is: "+searchList.getText(i));
}
mSearchView.updateSearchList(searchList);
}
#Override
public void onLoaderReset(android.content.Loader<List<String>> loader) {
}
Also we have this code in the presenter that is triggered by a edittext box on the fragment view being edited.
#Override
public void notifyTextEntry() {
//DETERMINE HOW TO GIVE LIST HERE
// Dummy List
Log.d("notifyTextEntry","log");
if(googleLoader==null)googleLoader=new GoogleSuggestLoader(context);
googleLoader.setUrl(mSearchView.provideTextQuery());
// mLoaderManager.getLoader(id).abandon();
mLoaderManager.getLoader(1).forceLoad();
mLoaderManager.getLoader(1).onContentChanged();
Log.d("length ", searchList.length().toString());
// googleLoader.onContentChanged();
}
Lastly we have the loader here:
public class GoogleSuggestLoader extends AsyncTaskLoader<List<String>>{
/** Query URL */
private String mUrl;
private static final String BASE_URL="https://suggestqueries.google.com/complete/search?client=firefox&oe=utf-8&q=";
private List<String> suggestions =new ArrayList<>();
public GoogleSuggestLoader(Context context) {
super(context);
this.mUrl=BASE_URL;
}
public void setUrl(String mUrl){
this.mUrl=BASE_URL+mUrl;
};
#Override
protected void onStartLoading() {forceLoad(); }
#Override
public List<String> loadInBackground() {
if (mUrl == null) {
return null;
}
try {
suggestions = new ArrayList<>();
Log.d("notifyinsideLoader","log");
String result=GoogleSuggestParser.parseTemp(mUrl);
if(result!=null) {
JSONArray json = new JSONArray(result);
if (json != null) {
JSONArray inner=new JSONArray((json.getString(1)));
if(inner!=null){
for (int i = 0; i < inner.length(); ++i) {
//only show 3 results
if(i==3)break;
Log.d("notifyinsideLoader",inner.getString(i));
suggestions.add(inner.getString(i));
}
}
}
}
} catch (IOException e) {
e.printStackTrace();
} catch (JSONException e) {
e.printStackTrace();
}
return suggestions;
}
}
So the problem:
The code loads the data fine to the listview on the fragment. When orientation changes loader is not calling onLoadFinished. I have tested the loader and it is processing the data fine.
I have already tried forceload and onContentChanged in the presenter to no avail.
If you need anymore info or if I should just use something else like RxJava let me know. But I would really like to get this working.
Before you ask I have seen similar problems like: AsyncTaskLoader: onLoadFinished not called after orientation change however I am using the same id so this problem should not exist.
The answer was on this page AsyncTaskLoader doesn't call onLoadFinished
but details were not given as to how to move to this.
So let me explain here for anyone else with this problem in future.
Support library is meant for fragments. So the class that is in charge of callbacks has to be importing AND implementing the correct methods from the support library. Same as if you are using MVP your presenter must extend from support loadermanager.
i.e: import android.support.v4.app.LoaderManager; Then implement correct callbacks.
Like
#Override
public android.support.v4.content.Loader<List<String>> onCreateLoader(int i, Bundle bundle) {
...
return new loader
}
and
#Override
public void onLoadFinished(android.support.v4.content.Loader<List<String>> loader, List<String> data) {
//do something here to your UI with data
}
Secondly: The loader itself must be extending from support asynctaskloader.
i.e: import android.support.v4.content.AsyncTaskLoader;

Delete the entire table from sqLite database

This is my fragment which have a listview. here data is read and entered in the listview.
I put a button here which deleted entire data of that particular table from the database. Now when I press that button, I get no response from the listview (i.e. the listview itmes are still there).
but when the fragment is restarted (either orientation changed or restarting the entire app), the data is deleted.
public class tasksListFrag extends Fragment implements View.OnClickListener {
ListView taskslist;
private ArrayList<singleRow> todoItems = new ArrayList<>();
String taskentered, dateentered, timeentered;
taskListRecycler adapter;
Button delete;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.tasks_list_frag, container, false);
Log.d("HirakDebug", "tasksListFrag View Created");
taskslist = (ListView) view.findViewById(R.id.tasks_list);
adapter = new taskListRecycler(getActivity(), todoItems);
taskslist.setAdapter(adapter);
Log.d("HirakDebug", "tasksListFrag Adapter set");
delete = (Button) view.findViewById(R.id.deleteAll);
delete.setOnClickListener(this);
return view;
}
#Override
public void onResume() {
super.onResume();
Log.d("HirakDebug", "taskListFrag resumed");
tasks_Database_Operations tasksDatabaseOperations = new tasks_Database_Operations(getActivity());
String[] columns = {tasksDatabaseOperations.ASSIS_TASK, tasksDatabaseOperations.ASSIS_DATE, tasksDatabaseOperations.ASSIS_TIME};
SQLiteDatabase sqLiteDatabase = tasksDatabaseOperations.getWritableDatabase();
Cursor cursor = sqLiteDatabase.query(tasksDatabaseOperations.ASSIS_TASK_TABLE_NAME, columns, null, null, null, null, null);
while (cursor.moveToNext()) {
Log.d("HirakDebug", "Cursor Moved To Next");
int index0 = cursor.getColumnIndex(tasks_Database_Operations.ASSIS_TASK);
int index1 = cursor.getColumnIndex(tasks_Database_Operations.ASSIS_DATE);
int index2 = cursor.getColumnIndex(tasks_Database_Operations.ASSIS_TIME);
String task = cursor.getString(index0);
Log.d("HirakDebug", "tasks_Database_Operations got Task from table");
String date = cursor.getString(index1);
Log.d("HirakDebug", "tasks_Database_Operations got Date from table");
String time = cursor.getString(index2);
Log.d("HirakDebug", "tasks_Database_Operations got Time from table");
singleRow ld = new singleRow();
ld.setTask(task);
Log.d("HirakDebug", "tasks_Database_Operations setTask called");
ld.setDate(date);
Log.d("HirakDebug", "tasks_Database_Operations setDate called");
ld.setTime(time);
Log.d("HirakDebug", "tasks_Database_Operations setTime called");
todoItems.add(ld);
Log.d("HirakDebug", "tasksListFrag Data Chenged Notified");
adapter.notifyDataSetChanged();
sqLiteDatabase.close();
Log.d("HirakDebug", "tasksListFrag Database Closed");
/* tasks_Database_Operations tasksDatabaseOperations = new tasks_Database_Operations(getActivity());
Cursor cursor = tasksDatabaseOperations.readData();
String[] from = new String[]{tasksDatabaseOperations.ASSIS_TASK,
tasksDatabaseOperations.ASSIS_DATE,
tasksDatabaseOperations.ASSIS_TIME};
int[] to = new int[]{R.id.task_added, R.id.date_added, R.id.time_added};
SimpleCursorAdapter simpleCursorAdapter = new SimpleCursorAdapter(getActivity(),R.layout.single_row,
cursor,from, to);
simpleCursorAdapter.notifyDataSetChanged();
taskslist.setAdapter(simpleCursorAdapter);*/
}
}
#Override
public void onPause() {
super.onPause();
Log.d("LifeCycle", "tLF Pause");
}
#Override
public void onStop() {
super.onStop();
Log.d("LifeCycle", "tLF Stop");
}
#Override
public void onDestroyView() {
super.onDestroyView();
Log.d("LifeCycle", "tLF DestroyView");
}
#Override
public void onDestroy() {
super.onDestroy();
Log.d("LifeCycle", "tLF Destroy");
}
#Override
public void onDetach() {
super.onDetach();
Log.d("LifeCycle", "tLF Detach");
}
#Override
public void onAttach(Activity activity) {
super.onAttach(activity);
Log.d("LifeCycle", "tLF Attach");
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
Log.d("LifeCycle", "tLF Create");
}
#Override
public void onStart() {
super.onStart();
Log.d("LifeCycle", "tLF Start");
}
#Override
public void onSaveInstanceState(Bundle outState) {
super.onSaveInstanceState(outState);
outState.putSerializable("list", (Serializable) todoItems);
Log.d("LifeCycle", "tLF saveInstance State");
}
#Override
public void onActivityCreated(Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
if (savedInstanceState != null) {
//probably orientation change
todoItems = (ArrayList<singleRow>) savedInstanceState.getSerializable("list");
} else {
if (todoItems != null) {
//returning from backstack, data is fine, do nothing
}
}
}
#Override
public void onClick(View v) {
tasks_Database_Operations tasksDatabaseOperations = new tasks_Database_Operations(getActivity());
SQLiteDatabase sqLiteDatabase = tasksDatabaseOperations.getWritableDatabase();
sqLiteDatabase.delete(tasksDatabaseOperations.ASSIS_TASK_TABLE_NAME, null, null);
Log.d("HirakDebug", "All Data Deleted");
adapter.notifyDataSetChanged();
sqLiteDatabase.close();
}
}
You are not clearing todolItems. So you need to clear it after deleting your table.
Add the below line just before adapter.notifyDataSetChanged() inside your onClick() method.
todolItems.clear();
It's a bit hard to tell from your code since you have a lot of lines per method but you don't seem to be emptying the actual ArrayList of display items when the onClick happens?
To make debugging easier you should really refactor large blocks of code into separate methods with clear names.

Listview and data updating

I have a question.
I am programming a application to add records to a Content Provider.
The content provider is working perfectly.
My problem is when I tried to insert some data into the listview. It inserts, but I'm not able to see the data(Except that I restart the app).
I was calling notifydatasetchanged from the adapter but it didn't work.
public class MainActivity extends Activity implements
LoaderManager.LoaderCallbacks<Cursor> {
ListView listContacts;
ListView listView;
Button addContactButton;
MyAdapter adapter;
ContentValues values;
ContentResolver contentResolver;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
contentResolver = getContentResolver();
listView = (ListView) findViewById(R.id.listView1);
values = new ContentValues();
getLoaderManager().initLoader(0, null, this);
addContactButton = (Button) findViewById(R.id.button1);
addContactButton.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
final Dialog dialogForm = new Dialog(v.getContext());
dialogForm.setTitle("Add a new Address");
dialogForm.setContentView(R.layout.dialog);
dialogForm.show();
Button saveButton = (Button) dialogForm
.findViewById(R.id.saveButton);
final EditText addressEditText = (EditText) dialogForm
.findViewById(R.id.addressEditText);
saveButton.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
try {
values.put(Contract.DATA, addressEditText.getText()
.toString());
contentResolver.insert(
Contract.CONTENT_URI, values);
values.clear();
dialogForm.dismiss();
} catch (Exception ex) {
ex.printStackTrace();
}
}
});
((MyAdapter)listView.getAdapter()).notifyDataSetChanged() ;
}
});
}
#Override
public Loader<Cursor> onCreateLoader(int arg0, Bundle arg1) {
return new CursorLoader(this, Contract.CONTENT_URI, null, null, null,
null);
}
#Override
public void onLoadFinished(Loader<Cursor> loader, Cursor cursor) {
adapter = new MyAdapter(this, R.layout.list_item, cursor, 0);
listView.setAdapter(adapter);
adapter.swapCursor(cursor);
}
#Override
public void onLoaderReset(Loader<Cursor> loader) {
adapter.swapCursor(null);
}
}
Can someone give me a clue about this problem?
Also, I have another question. Is efficient the implementation of onLoadFinished method?
Greetings
You need to call restartLoader to refresh the data inside the listview.
http://developer.android.com/reference/android/app/LoaderManager.html
when you make changes to ContentProvider data, you must call getLoaderManager().restartLoader().It will discard any old data and onCreateLoader will be called again which will in turn fetch updated records and ListView will be updated.
Below is nice tutorial on Loaders.
http://www.grokkingandroid.com/using-loaders-in-android/

Call Custom Listener in ListFragment from CursorAdapter Event

I have a SherlockListFragment in which I have a custom list item (checkbox, icon and some text) - works fine. The list is populated from a custom CursorAdapter and it is in here that I trap the Checkbox events (so I can preserve the data through orientation changes as well - also works). I want to be able to raise an event in the ListFragment when the user checks one or more checkboxes to display an actionbar item.
I've implemented an interface in the fragment to accept the event but just cannot work out the syntax for raising the fragment event in the cursoradapter's checkbox onClick listener - the event triggers ok but a can't call the listener, can't suss the object to use.
Fragment:
public class ContactListFragment extends SherlockListFragment implements
LoaderManager.LoaderCallbacks<Cursor>
{
public interface ListItemCheckedListener
{
public void OnListItemChecked(int count);
}
private SimpleCursorAdapter mAdapter;
public ListItemCheckedListener checkListener;
public void setListItemListener(ListItemCheckedListener listener)
{
checkListener = listener;
}
<snip>
#Override
public void onActivityCreated(Bundle savedInstanceState)
{
super.onActivityCreated(savedInstanceState);
<snip>
setListItemListener(new ListItemCheckedListener()
{
#Override
public void OnListItemChecked(int count)
{
// Turn on/off Action Bar Item
//if (count > 0)...
}
});
CursorAdapter:
public class ContactCursorAdapter extends SimpleCursorAdapter
{
<snip>
#Override
public void bindView(View view, Context context, Cursor cursor)
{
<snip>
CheckBox cBox = (CheckBox)view.findViewById(R.id.checkBox);
final int pos = cursor.getPosition();
cBox.setOnClickListener(new OnClickListener()
{
public void onClick(View view)
{
CheckBox cb = (CheckBox)view.findViewById(R.id.checkBox);
if (cb.isChecked())
{
itemChecked.set(pos, true);
countChecked++;
<something>.checkListener(countChecked); // <----- Umm?
}
else if (!cb.isChecked())
{
itemChecked.set(pos, false);
countChecked--;
<something>.checkListener(countChecked); // <----- ditto
}
}
});
cBox.setChecked(itemChecked.get(pos));
}
I've tried all manner of objects for "something" but can't seem to quite get the right one.
Help... please...!
Well, after quite a few dead ends I finally came up with a solution. Don't know if it is a good solution or if it is the "correct" way to do it but it works...
I simply added a public ListItemCheckedListener variable to the CursorAdapter class, assigned my ListFragment ListItemCheckedListener instance to it straight after setting up the adapter and then could call the local instance of the listener within the CursorAdapter and the event would propagate out to the ListFragment.
ListFragment:
public class ContactListFragment extends SherlockListFragment implements
LoaderManager.LoaderCallbacks<Cursor>// , OnQueryTextListener
{
private ContactCursorAdapter _adapter; // <----- HERE
<snip>
#Override
public void onActivityCreated(Bundle savedInstanceState)
{
super.onActivityCreated(savedInstanceState);
setListItemListener(new ContactListItemCheckedListener()
{
#Override
public void OnListItemChecked(int count)
{
if (count > 0)
{
if (_mode == null)
{
_loaderManager = getLoaderManager();
ContactsActivity activity = (ContactsActivity)getActivity();
_mode = activity.startActionMode(_actionModeCallback);
}
if (_contactInvite != null)
_contactInvite.setRecipCount(count);
}
else
{
if (_mode != null)
{
_mode.finish();
_mode = null;
}
}
}
});
_fragment = this;
setListProcessedListener(new ContactListProcessedListener()
{
public void OnListProcessed(int contactMethod)
{
for (int i = 0; i < _adapter.itemChecked.size(); i++)
_adapter.itemChecked.set(i, false);
_fragment.setListAdapter(_adapter);
_loaderManager.initLoader(0, null, _fragment);
}
});
setEmptyText(this.getString(R.string.contacts_none));
setHasOptionsMenu(true);
_adapter = new ContactCursorAdapter(getActivity(),
R.layout.contact_list_item,
null,
new String[] { Contacts._ID,
Contacts.DISPLAY_NAME,
Contacts.CONTACT_STATUS },
CONTACT_SUMMARY_FIELDS,
0);
_adapter.checkListener = checkListener;
boolean[] iChecked = null;
if (savedInstanceState != null)
{
if (savedInstanceState.containsKey("itemChecked"))
{
iChecked = savedInstanceState.getBooleanArray("itemChecked");
for (int i = 0; i < iChecked.length; i++)
_adapter.itemChecked.add(i, iChecked[i]);
_adapter.countChecked = savedInstanceState.getInt("countChecked");
checkListener.OnListItemChecked(_adapter.countChecked);
}
}
try
{
setListAdapter(_adapter);
setListShown(false);
// Prepare the loader. Either re-connect with an existing one,
// or start a new one.
getLoaderManager().initLoader(0, null, this);
((ContactsActivity)getActivity()).setSearchTextListener(new ContactsActivity.SearchTextListener()
{
#Override
public void OnSearchTextChange(String text)
{
onQueryTextChange(text);
}
});
}
catch (Exception e)
{
Singletons.Logger().error(TAG + ".onActivityCreated() failed",
e.getMessage());
}
}
CursorAdapter:
public class ContactCursorAdapter extends SimpleCursorAdapter
{
<snip>
public ListItemCheckedListener checkListener; // <----- HERE
<snip>
#Override
public void bindView(View view, Context context, Cursor cursor)
{
<snip>
cBox.setOnClickListener(new OnClickListener()
{
public void onClick(View view)
{
CheckBox cb = (CheckBox)view.findViewById(R.id.checkBox);
if (cb.isChecked())
{
itemChecked.set(pos, true);
countChecked++;
checkListener.OnListItemChecked(countChecked); // <----- HERE
}
else if (!cb.isChecked())
{
itemChecked.set(pos, false);
countChecked--;
checkListener.OnListItemChecked(countChecked); // <----- HERE
}
}
});
cBox.setChecked(itemChecked.get(pos));
}
Quite simple and fairly elegant, if I do say so myself. Well... at least it is in comparison to some of my earlier failed attempts(!). I still get the feeling that it isn't the best way to do it, somehow just feels wrong, but hey... it works.
If anyone has any better ways of doing this, I'd love to hear them. In the meanwhile, I hope this helps someone else.

CursorLoader not showing DB entires

I've got a CursorLoader in a ListFragment (that is inside a ViewPager) that queries a database. I have a content provider for that database, which I've verified works.
The issue is this: when the app runs for the very first time a separate service calls a bulk insert in a ContentProvider:
public int bulkInsert(Uri uri, ContentValues[] values) {
if(LOGV) Log.v(TAG, "insert(uri=" + uri + ", values" + values.toString() + ")");
final SQLiteDatabase db = openHelper.getWritableDatabase();
final int match = uriMatcher.match(uri);
switch(match) {
case SNAP: {
db.beginTransaction();
for(ContentValues cv : values) {
db.insertOrThrow(Tables.SNAP, null, cv);
}
db.setTransactionSuccessful();
db.endTransaction();
getContext().getApplicationContext().getContentResolver().notifyChange(uri, null);
return values.length;
}
The CursorLoader in the list fragment returns 0 rows though on the very first run (when the database gets created). If I close and restart the app then the CursorLoader works great and returns exactly what I need. I've tried to implement waiting via a handler, but it doesn't seem to help. Here is the ListFragment that utilizes the CursorLoader:
public class DataBySnapFragment extends ListFragment implements LoaderCallbacks<Cursor> {
public static final String TAG = "DataBySnapFragment";
protected Cursor cursor = null;
private DataBySnapAdapter adapter;
private Handler handler = new Handler() {
#Override
public void handleMessage(Message msg) {
super.handleMessage(msg);
Log.d(TAG, "RELOADING!!!!!");
onLoadDelay();
}
};
#Override
public void onActivityCreated(Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
Log.d(TAG, "onActivityCreated");
adapter = new DataBySnapAdapter(getActivity(),
R.layout.list_item_databysnap,
null,
new String[]{},
new int[]{},
0);
setListAdapter(adapter);
getLoaderManager().initLoader(0, null, this);
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_databysnap, null);
return view;
}
#Override
public void onSaveInstanceState(Bundle outState) {
super.onSaveInstanceState(outState);
outState.putString("error_workaround_1",
"workaroundforerror:Issue 19917,
http://code.google.com/p/android/issues/detail?id=19917");
}
#Override
public Loader<Cursor> onCreateLoader(int id, Bundle args) {
CursorLoader cursorLoader = new CursorLoader(getActivity(),
Snap.CONTENT_URI,
null,
null,
null,
Snap.DATA_MONTH_TO_DATE + " DESC LIMIT 6");
return cursorLoader;
}
#Override
public void onLoadFinished(Loader<Cursor> loader, Cursor data) {
Log.d(TAG, "data rows: " + data.getCount());
if(data.getCount() <= 0) {
delayThread();
} else {
adapter.swapCursor(data);
}
}
#Override
public void onLoaderReset(Loader<Cursor> loader) {
adapter.swapCursor(null);
}
private void onLoadDelay() {
getLoaderManager().initLoader(0, null, this);
}
private void delayThread() {
new Thread() {
public void run() {
longTimeMethod();
handler.sendEmptyMessage(0);
}
}.start();
}
private void longTimeMethod() {
try {
Thread.sleep(12000);
} catch (InterruptedException e) {
Log.e("tag", e.getMessage());
}
}
}
Can anyone let me know why this might be happening, or at least steer me in the right direction? Thanks!
Unless you were stalling the main thread, making a new thread and telling it to sleep wouldn't really solve anything.
I can't really say what exactly might be wrong, but it sounds like you might need to refresh your data. To test you could try to make a button with an OnClickListener which refreshes the data content, and re-pull it from the database.
Whenever your bulk insert is done you should send a message back to the fragment/activity implementing LoaderManager.LoaderCallbacks interface.
When the activity/fragment receives the message you would need to call getLoaderManager().restartLoader(0, null, this) to requery the DB.
This is what the sample app does too http://developer.android.com/guide/topics/fundamentals/loaders.html
Try to modify onLoadFinished this way:
#Override
public void onLoadFinished(Loader<Cursor> loader, Cursor data) {
Log.d(TAG, "data rows: " + data.getCount());
if(data.getCount() <= 0) {
delayThread();
} else {
// set the notification for the cursor
data.setNotificationUri(getActivity().getContentResolver(), Snap.CONTENT_URI);
adapter.swapCursor(data);
}
}

Categories

Resources