I have used Chris Banes implementation of pull to refresh list view for my app. The problem is if I set visibility for list view as gone or invisible and make it visible in java code, the list doesn't shows up. On the other hand, if I set its visibility as visible or don't set its visibility, every thing works fine. My requirement is such that I have two list views in the same activity. I have to set the visibility as one will appear first once it get data from server. The other will appear on search function. I had set the visibility for search result's listview as gone in the xml code, and making it visible only once it gets search results. Despite using setVisibility() for this listview, it never shows up screen. I had checked server response as well. It is showing search result on logcat.
I am posting my code below:
Code Snippet from Activity
//The result from this async task will populate the first list view
if(NetworkConnection.isOnline(MainCategory.this))
{
new MainMenuAsyncTask(dataUrl, MainCategory.this, listMainMenu, false).execute();
}
else
{
Log.v(TAG, "no network available");
SeattleNightLifeUtility.OpenWiFiDialog(MainCategory.this, getResources().getString(R.string.no_internet_msg));
}
loadListView();
//This will populate the list view that I have created for search results
_txtAutoSearch.setOnEditorActionListener(new TextView.OnEditorActionListener()
{
#Override
public boolean onEditorAction(TextView v, int actionId, KeyEvent event)
{
String term = _txtAutoSearch.getText().toString().trim();
if(! term.equals(""))
{
SeattleNightLifeUtility.hideSoftKeyboard(MainCategory.this, _txtAutoSearch);
if(NetworkConnection.isOnline(MainCategory.this))
{
search(term, false);
}
else
{
SeattleNightLifeUtility.OpenWiFiDialog(MainCategory.this, getResources().getString(R.string.no_internet_msg));
}
}
return true;
}//onEditorAction
});
listMainMenu.setOnRefreshListener(new PullToRefreshListView.OnRefreshListener()
{
#Override
public void onRefresh()
{
if(NetworkConnection.isOnline(MainCategory.this))
{
new MainMenuAsyncTask(dataUrl, MainCategory.this, listMainMenu, true).execute();
}
else
{
SeattleNightLifeUtility.OpenWiFiDialog(MainCategory.this, getResources().getString(R.string.no_internet_msg));
}
}
});
listViewSearch.setOnRefreshListener(new PullToRefreshListView.OnRefreshListener()
{
public void onRefresh()
{
if(NetworkConnection.isOnline(MainCategory.this))
{
search(_txtAutoSearch.getText().toString().trim(), true);
}
else
{
SeattleNightLifeUtility.OpenWiFiDialog(MainCategory.this, getResources().getString(R.string.no_internet_msg));
}
}
});
Search result Async Task
public class GetSearchAsyncTask extends AsyncTask<Void, Void, String>
{
Context ctx;
ProgressDialog pd;
PullToRefreshListView listViewSearch;
public static final String TAG = "GetSearchAsyncTask";
public static ArrayList<SearchDAO> searchArrayList;
private String term, callingclass;
private TextView txtNoData;
boolean flag;
public GetSearchAsyncTask(String term, Context ctx,
PullToRefreshListView listViewSearch, TextView txtNoData,
String callingclass, boolean flag)
{
this.term = term;
this.ctx = ctx;
this.listViewSearch = listViewSearch;
this.txtNoData = txtNoData;
this.callingclass = callingclass;
this.flag = flag;
}//Constructor
#Override
protected void onPreExecute()
{
if(flag == false)
{
pd = new ProgressDialog(ctx);
pd.setMessage(ctx.getResources().getString(R.string.please_wait));
pd.show();
}
}//onPreExecute
protected String doInBackground(Void... params)
{
String parsed = ServerConnection.getSearchedData(term);
try
{
if(flag == true)
{
Log.v(TAG, "doInBackground isListRefreshed is true");
Thread.sleep(2000);
}
}
catch(Exception e){}
return parsed;
}//doInBackground
#Override
protected void onPostExecute(String result)
{
searchArrayList = ParsedSearchData.getSearchedData(result);
listViewSearch.setVisibility(View.VISIBLE);
if(searchArrayList != null && searchArrayList.size() > 0)
{
Log.v(TAG, "searcharraylist not null");
for(int i = 0; i < searchArrayList.size(); i++)
{
Log.v(TAG, "Name: "+searchArrayList.get(i).getMerchant());
}
SearchAdapter mSearchAdapter = new SearchAdapter(ctx, searchArrayList);
mSearchAdapter.notifyDataSetChanged();
listViewSearch.setAdapter(mSearchAdapter);
if(callingclass.equals("EventActivity"))
{
Log.v(TAG, "callingclass EventActivity");
if(txtNoData.getVisibility() == View.VISIBLE)
{
Log.v(TAG, "txtNoData VISIBLE");
txtNoData.setVisibility(View.GONE);
}
if(((EventsActivity)ctx).txtNoEvent.getVisibility() == View.VISIBLE)
{
Log.v(TAG, "txtNoEvent VISIBLE");
((EventsActivity)ctx).txtNoEvent.setVisibility(View.GONE);
}
}
else
{
Log.v(TAG, "callingclass not EventActivity");
if(txtNoData.getVisibility() == View.VISIBLE)
{
Log.v(TAG, "else loop txtNoData VISIBLE");
txtNoData.setVisibility(View.GONE);
}
if(listViewSearch.getVisibility() == View.VISIBLE)
{
Log.v(TAG, "listViewSearch VISIBLE");
}
else
{
Log.v(TAG, "listViewSearch INVISIBLE");
}
}
}
else
{
Log.v(TAG, "searcharraylist null");
if(callingclass.equals("EventActivity"))
{
Log.v(TAG, "callingclass EventActivity");
txtNoData.setVisibility(View.VISIBLE);
listViewSearch.setVisibility(View.GONE);
if(((EventsActivity)ctx).txtNoEvent.getVisibility() == View.VISIBLE)
{
Log.v(TAG, "searcharraylist null else txtNoEvent VISIBLE");
((EventsActivity)ctx).txtNoEvent.setVisibility(View.GONE);
}
}
else
{
Log.v(TAG, "callingclass not EventActivitysearcharraylist null else txtNoEvent VISIBLE");
txtNoData.setVisibility(View.VISIBLE);
listViewSearch.setVisibility(View.GONE);
}
}
if(flag == false)
{
if(pd != null)
{
Log.v(TAG, "onPostExecute pd not null");
if(pd.isShowing())
{
Log.v(TAG, "onPostExecute pd is showing");
pd.dismiss();
}
}
}
else
{
listViewSearch.onRefreshComplete();
}
}//onPostExecute
}
Search Method
protected void search(String term, boolean result)
{
listMainMenu.setVisibility(View.GONE);
//listViewSearch.setVisibility(View.VISIBLE);
new GetSearchAsyncTask(term, MainCategory.this, listViewSearch , txtNoData, "MainCategory", result).execute();
}//search
Earlier I was setting visibility of in the XML as gone and in java code, I was making it VISIBLE. At that time, the list didn't showed up. When I removed the visibility attribute from XML layout file, and only set it in java code with setVisibility(), it worked perfect. I couldn't figured out the reason behind this. May be, I need to take a look at the implementation of library so that I find where did I went wrong. But, for the time being, this is what worked for me.
Related
i'm using backbutton as interface from activity but it's not working properly for me because on backpress showing 0 size of arraylist
// here is the activity class from where i'm getting backbutton interface..
public class Multiple_Images extends AppCompatActivity {
#Override
public void onBackPressed() {
if(twice ==true){
Intent intent =new Intent(this,MainActivity.class);
startActivity(intent);
}ImageAdapter imageAdapter =new ImageAdapter(this);
imageAdapter.onBackPress();
Toast.makeText(this, "Press twice", Toast.LENGTH_SHORT).show();
twice =true;
new Handler().postDelayed(new Runnable() {
#Override
public void run() {
twice =false; } }, 2000); }}
//here is the adapter class here i'm using backbutton
public class ImageAdapter extends BaseAdapter implements onBackPressListener {
ArrayList<String> selectedArraylist ;
#Override
public boolean onBackPress() {
selectedArraylist.clear();
Toast.makeText(context, "All values unselected", Toast.LENGTH_SHORT).show();
return true;
}
#Override
public View getView(int i, View view, ViewGroup viewGroup) {
urimodel=new ArrayList<>();
final ImageView imageGrid ;
Activity activity = (Activity) context;
actionMode = activity.startActionMode(new Actionmode());
final GridModel gridModel=(GridModel) this.getItem(i);
if(view==null) {
view = LayoutInflater.from(context).inflate(R.layout.model, null);
selectedArraylist =new ArrayList<>();
}
final CardView cardView= (CardView)view.findViewById(R.id.cardview_image);
imageGrid = (ImageView) view.findViewById(R.id.grid_image);
// gridText = (TextView) view.findViewById(R.id.grid_text);
imageGrid.setScaleType(ImageView.ScaleType.CENTER_CROP);
// imageGrid.setScaleType(ImageView.ScaleType.CENTER_CROP);
Picasso.get().load(gridModel.getImage()).resize(200,200).into(imageGrid);
if (selectedArraylist.contains(gridModel.getImage_text())) {
cardView.setCardBackgroundColor(CARD_SELECTED_COLOR);
}else {
cardView.setCardBackgroundColor(Color.WHITE);
}
return view;
}
}
Simply you can do this inside onBackPressed
#Override
public void onBackPressed() {
if (twice == true) {
super.onBackPressed(); //this backs to the previous activity, if you want to stay with Intent, add finish() after startActivity()
return;
} else {
for (int i = 0; i < list.size(); i++) {
if (gridView.isItemChecked(i)) {
gridView.setItemChecked(i, false);
}
}
//selectedArraylist.clear(); this is clearing your array of selected items
}
twice = true;
new Handler().postDelayed(new Runnable() {
#Override
public void run() {
twice = false;
}
}, 2000);
}
I don't know, why did you put selectedArraylist =new ArrayList<>(); in adapter getView() method. getView() is fired every time, when a new list item is inflated, that mean every time, when you are changing adapters source, scrolling list this method is called, and every time you are initialize you array, and all data inside lost. You should treat an adapter class just like a tool for displaying items, and all actions like above make outside adapter.
pretty much easy,
I give you my own project code, hope it help you.
StudentFragment.java:
private void MultiSelected_Student(int position) {
Student data = adapter_class.getItem(position);
if (data != null) {
if (selectedIds.contains(data)) selectedIds.remove(data);
else selectedIds.add(data);
}
}
private void Remove_MultiSelected() {
try {
selectedIds.clear();
} catch (Exception e) {
e.printStackTrace();
}
}
public void Group_UnSelect() {
Remove_MultiSelected();
MultiSelected = false;
fab.setVisibility(View.GONE);
homeeActivity.studentsMultiSelect = false;
notifyy();
}
private void notifyy() {
adapter_class.notifyDataSetChanged();
}
HomeActivity.java:
public boolean studentsMultiSelect = false;
#Override
public void onBackPressed() {
if (studentsMultiSelect) {
studentFragment.Group_UnSelect();
} else {
super.onBackPressed();
}
}
I have a problem.
I´m set an adapter when a asyctask end.
All code rules but when the code is inflated the screen keep white. The code dont throw any exception and i put some log to control execution flow. All is ok but the screen keep white.
I´m doing that:
protected class ObtenerCursos extends AsyncTask<Void, Void, Boolean> {
private JSONArray resultado;
private ProgressDialog dialog;
private Activity_Mis_Curso activity;
List <Curso> lista;
public ObtenerCursos(Activity_Mis_Curso misCursos){
this.activity=misCursos;
}
#Override
protected Boolean doInBackground(Void... params) {
resultado = getCursos(url,usuario);
if (resultado != null) {
lista=parseJSONDocumentos(resultado);
return true;
} else {
return false;
}
}
protected void onPreExecute() {
dialog = ProgressDialog.show(Activity_Mis_Curso.this,
"Obteniendo cursos", "Espere por favor...", true);
}
protected void onPostExecute(Boolean result) {
dialog.cancel();
if (result) {
gridView = (GridView) findViewById(R.id.miscursos_Grid);
if (getResources().getConfiguration().orientation == Configuration.ORIENTATION_LANDSCAPE) {
gridView.setNumColumns(3);
numColumns = 3;
} else {
numColumns = 2;
gridView.setNumColumns(2);
}
gridView.setAdapter(new MisCursosAdapter(Activity_Mis_Curso.this, listaCursos, numColumns));
gridView.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
if (listaCursos.get(position).getSoloReproduccion() == 0) {
Intent i = new Intent(Activity_Mis_Curso.this,
Activity_Main_Tradicional.class);
i.putExtra("Curso", listaCursos.get(position));
finish();
startActivity(i);
} else {
Intent i = new Intent(Activity_Mis_Curso.this,
Activity_Curso_SoloReproductor.class);
i.putExtra("Curso", listaCursos.get(position));
finish();
startActivity(i);
}
}
});
Log.e("ando", "por aqui \n\n");
} else {
Toast.makeText(getBaseContext(), "No se han encontrado cursos",
Toast.LENGTH_LONG).show();
Intent in = new Intent(Activity_Mis_Curso.this,
Activity_Index.class);
finish();
startActivity(in);
}
}
}
I can´t find where is my problem, i don´t know what i´m doing bad.
i'm doing an android application. I retrive data with GSON and display 10 elements each time i do a request. My problem is that i don't know how to add the new elements, to the elements before, in the bottom of the list. I use onScroll,so when i reach at the end of the list with 10 elements ,i make a request on the server.
I'm trying to integrate some libraries from github ,but it doesn't work.
Here is my code:
First is my method that populate the main list:
public void popullateMainList(final String url,final long expirationTime) {
//requestData(MAIN_LIST_URL);
new AsyncTask<Void, Void, Void>() {
ProgressBar pb = (ProgressBar)findViewById(R.id.progressBar);
#Override
protected void onPreExecute() {
pb.setVisibility(View.VISIBLE);
}
#Override
protected Void doInBackground(Void... voids) {
try {
elements = new Elements(url, expirationTime);
} catch (Exception e) {
e.printStackTrace();
e.printStackTrace();
}
return null;
}
#Override
protected void onPostExecute(final Void result) {
pb.setVisibility(View.GONE);
updateDisplay();
mainElementAdapter.notifyDataSetChanged();
}
}.execute();
}
And the method updateDisplay has the following code:
protected void updateDisplay() {
eList = (ListView) findViewById(R.id.mainView);
mainElementAdapter = new ElementListAdapter(this, elements.getElements());
// mainElementAdapter.add(elements.getElements());
footerView = ((LayoutInflater) this.getSystemService(Context.LAYOUT_INFLATER_SERVICE)).inflate(R.layout.loading_footer, null, false);
eList.addFooterView(footerView);
eList.setAdapter(mainElementAdapter);
eList.removeFooterView(footerView);
eList.setOnScrollListener(new AbsListView.OnScrollListener() {
#Override
public void onScrollStateChanged(AbsListView view, int scrollState) {
if (scrollState == SCROLL_STATE_IDLE) {
if (eList.getLastVisiblePosition() >= eList.getCount() - visibleThreshold) {
currentPage++;
actualUrl = Constants.MAIN_LIST_URL + "?pageNumber=" + currentPage;
popullateMainList(actualUrl,1);
}
}}
public boolean canChildScrollUp() {
//your condition to check scrollview reached at top while scrolling
if (swipeLayout.getScrollY() == 0.0)
return true;
else
return false;
}
#Override
public void onScroll(AbsListView absListView, int firstVisibleItem, int visibleItemCount, int totalItemCount)
{
if (firstVisibleItem == 0)
swipeLayout.setEnabled(true);
else
swipeLayout.setEnabled(false);
}
});
}
I hope that anybody help me. Thank you in advance!
Try save old.
when you use
elements = new Elements(url, expirationTime);
you override your Elements object and when you use
mainElementAdapter = new ElementListAdapter(this, elements.getElements());
you override your old data in adapter
added new method in your class Elemets
something like that
if(elements == null) {
elements = new Elements(url, expirationTime);
} else {
elements.add(new Elements(url, expirationTime).getElements());
}
I have number of fragments in a root activity which I set them true for retaining their instances on config changes.
However, this arises a serious issue for me;
I have an AsyncTask in my Fragment.onResume(...) which performs a background job and calls getSherlockActivity().invalidateOptionsMenu(...) method to change the action bar items. When the app first opens fragment worked as expected and invalidating options menu recalls Fragment.oncreateOptionMenu(...) method. But when I change the orientation, AsyncTask is started again and does this background job but invalidating doesn't call Fragment.oncreateOptionMenu(...) so my action bar remains in an unwanted state.
This is my task;
private class ContactListLoader extends AsyncTask<Void, Void, Void> {
#Override
protected void onPreExecute() {
super.onPreExecute();
Log.d("Contact List Fragment", "Task started...");
ContactListFragment.mIsRunning = true;
if (emptyView != null) {
if (emptyView instanceof TextView) {
((TextView) emptyView).setText(getResources().getString(
R.string.contact_list_loading_list_title));
}
}
getSherlockActivity().invalidateOptionsMenu();
getSherlockActivity().setSupportProgressBarIndeterminateVisibility(
true);
}
#Override
protected Void doInBackground(Void... params) {
createDataSet();
ContactListFragment.mIsRunning = false;
return null;
}
#Override
protected void onPostExecute(Void result) {
super.onPostExecute(result);
mContactsListView.setAdapter(mAdapter);
mIsContactsLoadedFirstTime = true;
if (emptyView != null) {
if (emptyView instanceof TextView) {
((TextView) emptyView).setText(getResources().getString(
R.string.contact_list_empty_list_title));
}
}
getSherlockActivity().invalidateOptionsMenu();
getSherlockActivity().setSupportProgressBarIndeterminateVisibility(
false);
if (mContactsLocal != null & !mContactsLocal.isEmpty()) {
listener.onContactListLoaded(mContactsLocal.get(0),
mContactsLocal);
}
try {
if (mCapabilityApi != null
&& mCapabilityApi.isImsConnected(getSherlockActivity()
.getApplicationContext())) {
mCapabilityApi.refreshAllCapabilities();
}
} catch (ClientApiException e) {
e.printStackTrace();
}
Toast.makeText(getSherlockActivity().getApplicationContext(),
getResources().getString(R.string.contact_list_updated),
Toast.LENGTH_SHORT).show();
}
#Override
protected void onCancelled() {
Log.d("Contact List Fragment", "task cancelled 2");
ContactListFragment.mIsRunning = false;
super.onCancelled();
}
}
Any ideas?
Sometimes I receive this error on my Activity below, sometimes not:
The content of the adapter has changed
but ListView did not receive a notification. Make sure the content of
your adapter is not modified from a background thread, but only from the
UI thread.
but I'm not sure where my mistake on my class below. Does anybody have idea?
public class FavoriteActivity extends SpeakSuperActivity {
private final static String TAG = FavoriteActivity.class.getSimpleName();
private Button btn_filter_topic, btn_filter_rating, btn_filter_none;
private TextView fav_filter_text;
private static ListView listViewFavorites;
private static TextView txtNoFavoritesYet;
private List<Favorite> currentFavorites;
private ArrayAdapter<Favorite> currentFavoritesArrayAdapter;
// required for list loading piece by piece
final int itemsPerLoading = Configuration.LOADED_ITEMS_ON_LIST_AT_ONCE;
boolean loadingMore = false;
private List<Long> idList;
int currentDataLoaded;
private static int oldBtnViewId = 0;
// set the start value as same as the loading value
int maximumDataLoadedYet = Configuration.LOADED_ITEMS_ON_LIST_AT_ONCE;
// 0 = not sorted, 1 = sorted by topic and minimum number of stars
private int caseSelection = 0;
private static View progressView;
private View footerView;
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.favorites);
Log.d(TAG, "FavoritesScreen onCreate()...");
// indicator for waiting processes
progressView = UIUtils.addBlockingProgressIndicatorBlack(this);
// init Listview
listViewFavorites = (ListView) findViewById(R.id.fav_listview_favorites);
// add the footer before adding the adapter, else the footer
// will not load!
footerView = ((LayoutInflater) getSystemService(Context.LAYOUT_INFLATER_SERVICE)).inflate(R.layout.listviewfooter, null, false);
listViewFavorites.addFooterView(footerView);
listViewFavorites = (ListView) findViewById(R.id.fav_listview_favorites);
fav_filter_text = (TextView) findViewById(R.id.fav_filter_text);
btn_filter_none = (Button) findViewById(R.id.btn_fav_filter_none);
btn_filter_topic = (Button) findViewById(R.id.btn_fav_filter_topic);
btn_filter_rating = (Button) findViewById(R.id.btn_fav_filter_rating);
toggleButtonStates(R.id.btn_fav_filter_none);
LoadDataTask ldTask = new LoadDataTask();
ldTask.execute();
// no favorites yet?
txtNoFavoritesYet = (TextView) findViewById(R.id.fav_no_favorites_yet);
updateUI();
}
/**
* An asynchronous Task (doesn't block the UI Thread) for loading the Data in background.
*
* #author Jonas Soukup
*/
private class LoadDataTask extends AsyncTask<Void, Void, LoudmouthException> {
private final String TAG = LoadDataTask.class.getName();
protected void onPreExecute() {
super.onPreExecute();
if (FavoriteProvider.getInstance().getNumOfFavorites() != 0)
progressView.setVisibility(View.VISIBLE);
else
progressView.setVisibility(View.GONE);
listViewFavorites.setVisibility(View.GONE);
fav_filter_text.setVisibility(View.GONE);
btn_filter_none.setVisibility(View.GONE);
btn_filter_topic.setVisibility(View.GONE);
btn_filter_rating.setVisibility(View.GONE);
}
protected LoudmouthException doInBackground(Void... params) {
LoudmouthException exception = null;
Log.d(TAG, "loading data..");
switch (caseSelection) {
case 0:
// Get FavoriteList without sorting
idList = FavoriteProvider.getInstance().getFavoritesByDate();
break;
case 1:
// Get FavoriteList sorted by
// Topics + amount of stars
SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(getApplicationContext());
float minRating = prefs.getFloat(getResources().getString(R.string.rating_filter_star_amount), 0);
idList = FavoriteProvider.getInstance().getFavoritesByTopicAndMinRating(minRating);
break;
default:
Log.e(TAG, "No Case with number: " + caseSelection);
}
// reset data loaded, so it loads till maximumDataLoadedYet on a
// refresh of the list
currentDataLoaded = 0;
// reset List on Data change
currentFavorites = new ArrayList<Favorite>();
Log.d(TAG, "..loading data finished");
return exception;
}
protected void onPostExecute(LoudmouthException result) {
try {
Log.d(TAG, "LoadDataTask.onPostExecute()");
super.onPostExecute(result);
progressView.setVisibility(View.GONE);
if (result != null) {
// Error ocurred during loading
android.content.DialogInterface.OnClickListener retryClickListener = new android.content.DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
new LoadDataTask().execute();
}
};
UIUtils.showRetryCancelAlertDialog(getApplicationContext(), result, retryClickListener, null);
} else {
// Everythings fine, data loaded
// showing & hiding
if (FavoriteProvider.getInstance().getNumOfFavorites() == 0) {
fav_filter_text.setVisibility(View.GONE);
btn_filter_none.setVisibility(View.GONE);
btn_filter_topic.setVisibility(View.GONE);
btn_filter_rating.setVisibility(View.GONE);
} else {
fav_filter_text.setVisibility(View.VISIBLE);
btn_filter_none.setVisibility(View.VISIBLE);
btn_filter_topic.setVisibility(View.VISIBLE);
btn_filter_rating.setVisibility(View.VISIBLE);
}
if (idList.size() == 0) {
txtNoFavoritesYet.setVisibility(View.VISIBLE);
listViewFavorites.setVisibility(View.GONE);
} else {
txtNoFavoritesYet.setVisibility(View.GONE);
listViewFavorites.setVisibility(View.VISIBLE);
runOnUiThread(new Runnable() {
public void run() {
btn_filter_none.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
caseSelection = 0;
FavoriteProvider.getInstance().setCurrentFavoriteListStateDirty(true);
toggleButtonStates(v.getId());
updateUI();
}
});
btn_filter_topic.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
caseSelection = 1;
TopicFilterFavDialog tfFavDialog = new TopicFilterFavDialog(FavoriteActivity.this, FavoriteActivity.this, v
.getId());
tfFavDialog.show();
}
});
btn_filter_rating.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
caseSelection = 1;
RatingFilterFavDialog ratDialog = new RatingFilterFavDialog(FavoriteActivity.this, FavoriteActivity.this, v
.getId());
ratDialog.show();
}
});
}
});
}
}
// init listview displaying with data loaded step by step
currentFavoritesArrayAdapter = new FavoriteArrayAdapter(FavoriteActivity.this, FavoriteActivity.this, R.layout.favorite_list_entry,
currentFavorites);
listViewFavorites.setAdapter(currentFavoritesArrayAdapter);
currentFavoritesArrayAdapter.notifyDataSetChanged();
} catch (Exception exception) {
// silent catch because activity could be closed meanwhile
Log.i(TAG, "silent exception catch in onPostExecute: " + exception.getMessage());
}
}
}
/**
* Update UI
*/
public void updateUI() {
LoadDataTask ldTask = new LoadDataTask();
ldTask.execute();
if (currentFavoritesArrayAdapter != null)
currentFavoritesArrayAdapter.notifyDataSetChanged();
}
#Override
protected void onResume() {
super.onResume();
updateUI();
}
private class ListMoreItemsTask extends AsyncTask<Void, Void, LoudmouthException> {
#Override
protected LoudmouthException doInBackground(Void... arg0) {
LoudmouthException exception = null;
loadingMore = true;
// reset loading values if adapter was reseted
if (currentFavoritesArrayAdapter.getCount() == 0)
maximumDataLoadedYet = Configuration.LOADED_ITEMS_ON_LIST_AT_ONCE;
// Get value of Configuration.LOADEDITEMSONLISTATONCE new listitems
for (; currentDataLoaded < maximumDataLoadedYet && currentDataLoaded < idList.size(); currentDataLoaded++) {
// Fill the list with new information
currentFavorites.add(FavoriteProvider.getInstance().getFavorite(idList.get(currentDataLoaded)));
}
maximumDataLoadedYet += itemsPerLoading;
// Done loading more.
loadingMore = false;
return exception;
}
protected void onPostExecute(LoudmouthException result) {
if (result == null) {
// Tell to the adapter that changes have been made, this will
// cause
// the list to refresh
currentFavoritesArrayAdapter.notifyDataSetChanged();
// remove loading view when maximum data is reached
if (currentFavorites.size() == idList.size()) {
listViewFavorites.removeFooterView(footerView);
}
}
}
}
public void toggleButtonStates(int viewId) {
// set clicked button as selected
if (viewId != 0) {
switch (viewId) {
case R.id.btn_fav_filter_none:
btn_filter_none.setCompoundDrawablesWithIntrinsicBounds(getResources().getDrawable(R.drawable.filter_neuste_selected), null, null,
null);
btn_filter_none.setTextColor(getResources().getColor(color.black));
break;
case R.id.btn_fav_filter_topic:
btn_filter_topic.setCompoundDrawablesWithIntrinsicBounds(getResources().getDrawable(R.drawable.filter_themen_selected), null, null,
null);
btn_filter_topic.setTextColor(getResources().getColor(color.black));
break;
case R.id.btn_fav_filter_rating:
btn_filter_rating.setCompoundDrawablesWithIntrinsicBounds(getResources().getDrawable(R.drawable.filter_rating_selected), null, null,
null);
btn_filter_rating.setTextColor(getResources().getColor(color.black));
break;
default:
Log.d("TAG", "No View with id: " + viewId);
}
}
// if previews Button exists and wasn't the same button set the old
// one
// to selected false
if (oldBtnViewId != 0 && oldBtnViewId != viewId) {
// set clicked button as not selected
switch (oldBtnViewId) {
case R.id.btn_fav_filter_none:
btn_filter_none.setCompoundDrawablesWithIntrinsicBounds(getResources().getDrawable(R.drawable.filter_neuste), null, null, null);
btn_filter_none.setTextColor(getResources().getColor(R.color.font_grey));
break;
case R.id.btn_fav_filter_topic:
btn_filter_topic.setCompoundDrawablesWithIntrinsicBounds(getResources().getDrawable(R.drawable.filter_themen), null, null, null);
btn_filter_topic.setTextColor(getResources().getColor(R.color.font_grey));
break;
case R.id.btn_fav_filter_rating:
btn_filter_rating.setCompoundDrawablesWithIntrinsicBounds(getResources().getDrawable(R.drawable.filter_rating), null, null, null);
btn_filter_rating.setTextColor(getResources().getColor(R.color.font_grey));
break;
default:
Log.d("TAG", "No View with id: " + viewId);
}
}
oldBtnViewId = viewId;
}
}
It fails because you modify currentFavorite in ListMoreItemsTasks, which is the underlying list that backs your adapter.
The modification is made in doInBackground, which is not the UI Thread.
I would recommend using publishProgress to receive the data to add on the UI Thread and add it to the adapter there (via the adapter's method, not the array, which you should probably not keep after having created the adapter)
edit
Replace
private class ListMoreItemsTask extends AsyncTask<Void, Void, LoudmouthException> {
with
private class ListMoreItemsTask extends AsyncTask<Void, Favorite, LoudmouthException> {
so progresses are Favorite elements, then
currentFavorites.add(FavoriteProvider.getInstance().getFavorite(idList.get(currentDataLoaded)));
with
publishProgress(FavoriteProvider.getInstance().getFavorite(idList.get(currentDataLoaded));
plus insert in the AsyncTask the onProgressUpdate :
onProgressUpdate(Favorite... values) {
currentFavorites.add(values[0]);
currentFavoritesArrayAdapter.notifyDataSetChanged();
}