android notifydatasetchange() not working - android

I have an error on notifydatasetchanged(). Can anyone give me a proper solution?
I have tried all possible cases but I am not finding a solution.
I have attached notifydatasetchanged() as adapter.notifydatasetchanged() and but it's not working at all and if I give this: oncreate(null) it's showing an error in MainActivity.
My doInBackground method is:
protected Void doInBackground(Void... voids) {
if (phones != null) {
Log.e("count", "" + phones.getCount());
if (phones.getCount() == 0) {
Log.d("No Contacts", "No Contacts");
}
while (phones.moveToNext()) {
Bitmap bit_thumb = null;
String name = phones.getString(phones.getColumnIndex(ContactsContract.CommonDataKinds.Phone.DISPLAY_NAME));
String phoneNumber = phones.getString(phones.getColumnIndex(ContactsContract.CommonDataKinds.Phone.NUMBER));
String image_thumb = phones.getString(phones.getColumnIndex(ContactsContract.CommonDataKinds.Phone.PHOTO_URI));
try {
if (image_thumb == null) {
//bit_thumb = MediaStore.Images.Media.getBitmap(resolver, Uri.parse(image_thumb));
} else {
bit_thumb = MediaStore.Images.Media.getBitmap(resolver, Uri.parse(image_thumb));
}
} catch (IOException e) {
e.printStackTrace();
}
SelectUser selectUser = new SelectUser();
selectUser.setThumb(bit_thumb);
selectUser.setName(name);
selectUser.setPhone(phoneNumber);
selectUser.setCheckedBox();
selectUsers.add(selectUser);
}
} else {
Log.e("Cursor close 1", "----------------");
}
//phones.close();
return null;
}
protected void onPostExecute(Void aVoid) {
super.onPostExecute(aVoid);
adapter = new SelectUserAdapter(selectUsers, MainActivity.this);
listView.setAdapter(adapter);
adapter.notifyDataSetChanged();
listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#TargetApi(Build.VERSION_CODES.LOLLIPOP)
#Override
public void onItemClick(AdapterView<?> adapterView, View view, int position, long l) {
synchronized (MainActivity.this) {
if (firstClickTime == 0) {
firstClickTime = SystemClock.elapsedRealtime();
nonDoubleClick = true;
} else {
long deltaTime = SystemClock.elapsedRealtime() - firstClickTime;
firstClickTime = 0;
if (deltaTime < DOUBLE_CLICK_TIMEOUT) {
nonDoubleClick = false;
this.onItemDoubleClick(adapterView, view, position, l);
return;
}
}
view.postDelayed(new Runnable() {
#Override
public void run() {
if (nonDoubleClick) {
Log.d("Single click", "single click");
}
}
}, DOUBLE_CLICK_TIMEOUT);
}
}
public void onItemDoubleClick(AdapterView<?> parent, View view, int position, long id) {
String selected = ((TextView) view.findViewById(com.jamol.contacts.R.id.no)).getText().toString();
try {
mediaPlayer = MediaPlayer.create(MainActivity.this, R.raw.call);
mediaPlayer.setVolume(1.0f, 1.0f);
mediaPlayer.setLooping(false);
mediaPlayer.start();
Vibrator v = (Vibrator) MainActivity.this.getSystemService(Context.VIBRATOR_SERVICE);
v.vibrate(500);
Intent in = new Intent(Intent.ACTION_CALL, Uri.parse("tel:" + selected));
startActivity(in);
} catch (SecurityException e) {
Log.e("PERMISSION_EXCEPTION", "PERMISSION_NOT_GRANTED");
}
}
});
listView.setFastScrollEnabled(true);
}
And the adapter is:
public SelectUserAdapter(List<SelectUser> selectUsers, Context context) {
_data = selectUsers;
_c = context;
this.arraylist = new ArrayList<>();
this.arraylist.addAll(_data);
}
#Override
public int getCount() {
return _data.size();
}
#Override
public Object getItem(int i) {
return _data.get(i);
}
#Override
public long getItemId(int i) {
return i;
}
#SuppressLint("InflateParams")
#TargetApi(Build.VERSION_CODES.LOLLIPOP)
#Override
public View getView(int i, View convertView, ViewGroup viewGroup) {
View view = convertView;
if (view == null) {
LayoutInflater li = (LayoutInflater) _c.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
view = li.inflate(com.jamol.contacts.R.layout.contact_info, null);
} else {
view = convertView;
}
ViewHolder v = new ViewHolder();
v.title = (TextView) view.findViewById(com.jamol.contacts.R.id.name);
v.check = (CheckBox) view.findViewById(com.jamol.contacts.R.id.check);
v.setPhone((TextView) view.findViewById(com.jamol.contacts.R.id.no));
v.imageView = (ImageView) view.findViewById(com.jamol.contacts.R.id.pic);
final SelectUser data = _data.get(i);
v.title.setText(data.getName());
v.check.setChecked(data.getCheckedBox());
v.getPhone().setText(data.getPhone());
try {
if (data.getThumb() != null) {
v.imageView.setImageBitmap(data.getThumb());
} else {
v.imageView.setImageResource(com.jamol.contacts.R.drawable.ic_user);
}
} catch (OutOfMemoryError e) {
v.imageView.setImageDrawable(this._c.getDrawable(com.jamol.contacts.R.drawable.ic_user));
e.printStackTrace();
}
view.setTag(data);
return view;
}
public void filter(String charText) {
if (charText != null) {
charText = charText.toLowerCase(Locale.getDefault());
_data.clear();
if (charText.length() == 0) {
_data.addAll(arraylist);
} else {
for (SelectUser wp : arraylist)
if (wp.getName().toLowerCase(Locale.getDefault())
.contains(charText)) {
_data.add(wp);
}
}
}
}
static class ViewHolder {
ImageView imageView;
TextView title;
CheckBox check;
private TextView phone;
public TextView getPhone() {
return phone;
}
public void setPhone(TextView phone) {
this.phone = phone;
}
}
And this is the logcat:
FATAL EXCEPTION: main Process: com.jamol.contacts, PID: 18190 java.lang.IllegalStateException: 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. Make sure your adapter calls notifyDataSetChanged() when its content changes. [in ListView(2131492978, class android.widget.ListView) with Adapter(class com.jamol.contacts.SelectUserAdapter)]
at android.widget.ListView.layoutChildren(ListView.java:1584)
at android.widget.AbsListView.onLayout(AbsListView.java:2645)
at android.view.View.layout(View.java:16939)
at android.view.ViewGroup.layout(ViewGroup.java:5409)
at android.widget.RelativeLayout.onLayout(RelativeLayout.java:1077)
at android.view.View.layout(View.java:16939)
at android.view.ViewGroup.layout(ViewGroup.java:5409)
at android.widget.FrameLayout.layoutChildren(FrameLayout.java:579)
at android.widget.FrameLayout.onLayout(FrameLayout.java:514)
at android.view.View.layout(View.java:16939)
at android.view.ViewGroup.layout(ViewGroup.java:5409)
at android.widget.LinearLayout.setChildFrame(LinearLayout.java:1702)

Don't do it in Activity.
Override this method in adaptor Create one method for getting updated values.
#Override
public void notifyDataSetChanged() {
super.notifyDataSetChanged();
}
public SelectUserAdapter(List<SelectUser> selectUsers, Context context) {
_data = selectUsers;
_c = context;
updateResults(selectUsers);
}
public void updateResults(List<SelectUser> results) {
userList = results;//List<SelectUser> userList
notifyDataSetChanged();
}

Related

custom Adapter not working properly after filter applied in android

There is adapter set to Station(Name/Code) AutocompleteTextView. First time whole list is setting. After that If I filter for ch, It will display all filtered Items.
And Now If i remove ch, It will display whole list. Here there is no problem.
But Now If click back button or navigate tot other screen and coming to this screen again, there is only filtered Items are displaying(which are starts with ch).
Why only filtered Items are showing?
Please help me.
This is very important for my project.
I tried many solutions on google. But not got the output.
Any help would be appreciated.
This is my custom Adapter:
public class CustomAdapter extends ArrayAdapter {
private final Context mContext;
private ArrayList<TextItem> textObjects;
private ArrayList<TextItem> textObjects_All;
private final int mLayoutResourceId;
View rowView;
private LayoutInflater inflater;
public CustomAdapter(Context mContext, int resource, ArrayList<TextItem> AObjects) {
super(mContext, resource, AObjects);
this.mContext = mContext;
mLayoutResourceId = resource;
setTextObjects(AObjects);
}
public void setTextObjects(ArrayList<TextItem> AObjects) {
try {
textObjects = AObjects;
textObjects_All = new ArrayList<>();
synchronized (this) {
textObjects_All.addAll(AObjects);
}
}catch (Exception e){
Log.d("eEmp/setTextObj", "Expt due to " + e.toString());
}
}
public int getCount() {
return textObjects.size();
}
public TextItem getItem(int position) {
return textObjects.get(position);
//return (textObjects != null ? textObjects.get(position) : "");
}
public long getItemId(int position) {
return position;
}
public void addTextObject(TextItem newItem) {
try {
if ((textObjects_All != null) && (!textObjects_All.contains(newItem))) {
textObjects_All.add(newItem);
}
} catch (Exception expt) {
Log.d("eEmp/setTextObj", "Expt due to " + expt.toString());
}
}
#NonNull
#Override
public View getView(int position, #Nullable View convertView, #NonNull ViewGroup parent) {
try {
rowView = convertView;
if (rowView == null){
inflater = LayoutInflater.from(mContext);
rowView = inflater.inflate(mLayoutResourceId, parent, false);
}
TextItem selectedItem = (TextItem) getItem(position);
TextView txtHeaderObject = (TextView) rowView.findViewById(R.id.tvHeaderItem);
txtHeaderObject.setText(selectedItem.headItemName);
TextView txtSubItem1Object = (TextView) rowView.findViewById(R.id.tvSub1Item);
if (txtSubItem1Object != null) {
txtSubItem1Object.setText(selectedItem.subItem1Name);
}
TextView txtSubItem2Object = (TextView) rowView.findViewById(R.id.tvSub2Item);
if (txtSubItem2Object != null) {
txtSubItem2Object.setText(selectedItem.subItem2Name);
}
ViewGroup.LayoutParams params = rowView.getLayoutParams();
return rowView;
} catch (Exception e) {
Log.e("/eEmp","/Convert View Exception"+e.toString());
e.printStackTrace();
}
return rowView;
}
private static class ViewHolder{
TextView Header;
TextView SubItem1;
TextView SubItem2;
}
#NonNull
#Override
public Filter getFilter() {
return new Filter() {
#Override
public CharSequence convertResultToString(Object resultValue) {
return ((TextItem) resultValue).headItemName;
}
#Override
protected FilterResults performFiltering(CharSequence constraint) {FilterResults filterResults = new FilterResults();
try {
if ((constraint == null) || (constraint.length() == 0)) {
synchronized (this) {
filterResults.values = textObjects_All;
filterResults.count = textObjects_All.size();
}
} else {
ArrayList<TextItem> textObjectsFiltered = new ArrayList<TextItem>();
for (TextItem obj : textObjects_All) {
TextItem itemObj = obj;
if (itemObj != null) {
if ((itemObj.headItemName != null) && (itemObj.headItemName.length() != 0)
&& (itemObj.headItemName.toLowerCase().startsWith(constraint.toString().toLowerCase()))) {
textObjectsFiltered.add(obj);
}
}
}
filterResults.values = textObjectsFiltered;
filterResults.count = textObjectsFiltered.size();
}
} catch (Exception expt) {
Log.d("eEmp/FilterResults", "Exception Occurred due to " + expt.toString());
}
return filterResults;
}
#SuppressWarnings("SingleStatementInBlock")
#Override
protected void publishResults(CharSequence constraint, FilterResults results) {
try{
textObjects.clear();
if (results != null && results.count > 0) {
ArrayList<?> result = (ArrayList<?>) results.values;
for (Object object : result) {
if (object instanceof TextItem) {
textObjects.add((TextItem) object);
}
}
}
notifyDataSetChanged();
}catch (Exception expt) {
Log.d("eEmp/publishResults", "Exception Occurred due to " + expt.toString());
}
}
};
}
}
AutoCompleteTextWatcher.java
public class AutoCompleteTextWatcher implements TextWatcher {
private CustomAutoCompleteTextView currATV;
public AutoCompleteTextWatcher(CustomAutoCompleteTextView tv)
{
currATV = tv;
}
#Override
public void beforeTextChanged(CharSequence s, int start, int count, int after) {
}
#Override
public void onTextChanged(CharSequence s, int start, int before, int count) {
}
#Override
public void afterTextChanged(Editable s) {
if(currATV != null)
{
currATV.setTextItemTag(null);
}
}
}
atcvDivName is my AutoCompleteTextView
Activity
public View onCreateView(LayoutInflater inflater, #Nullable ViewGroup container, #Nullable Bundle savedInstanceState) {
rootView = inflater.inflate(R.layout.entry_fab_activity, container, false);
try {
Inst_Act_List_works_entry = new ArrayList<>();//added by pavani
status_pojo = new Status_POJO();
edtFromDate = (EditText) rootView.findViewById(R.id.edtFromDate);
edtFromDate.setText(getTodayDates()); // Added in V 1.3 by Shamili
// Get Available WorkTypes
WorkTypes = new ArrayList<String>(Arrays.asList(getResources().getStringArray(R.array.WorkTypes)));
actvDivName.addTextChangedListener(textWatcher());
//set event for clear button
btnClear_stn.setOnClickListener(onClickListener());
actvEntryCategory.addTextChangedListener(textWatcher_Entry());
btn_clear_EntryType.setOnClickListener(onClickListener());
btn_clear_Product.setOnClickListener(onClickListener());
actvPType.addTextChangedListener(textWatcher_Product());
cd_leaves.setVisibility(View.GONE);
if (stn_fal_falg == 1) {
btnClear_stn.setVisibility(View.GONE);
btn_clear_EntryType.setVisibility(View.GONE);
btn_clear_Product.setVisibility(View.GONE);
} else {
btnClear_stn.setVisibility(View.VISIBLE);
btn_clear_EntryType.setVisibility(View.VISIBLE);
btn_clear_Product.setVisibility(View.VISIBLE);
}
try {
WorksList = dbHandler.getWorkTypes();
for (String newWorkType : WorksList) {
if (!WorkTypes.contains(newWorkType)) {
WorkTypes.add(newWorkType);
}
}
} catch (Exception getWorkExp) {
}
EntryTypeAdapter = new CustomArrayAdapter(getActivity(), R.layout.autocomplete_text_layout, WorkTypes);
actvEntryCategory.setAdapter(EntryTypeAdapter);
actvEntryCategory.setThreshold(0);
Rlys = new ArrayList<Rly>();
try {
DivStnList = mContext.StnsPlacesList;
for (int i = 0; i < DivStnList.size(); i++) {
QRDivTextItemList = mContext.StnsPlacesList;
DivIDsList.add(DivStnList.get(i).did);
StnIDsList.add(DivStnList.get(i).id);
DivList.add(DivStnList.get(i).subItem2Name);
StnsList.add(DivStnList.get(i).headItemName);
}
} catch (Exception getDivExp) {
}
actvDivName.setThreshold(0);
actvDivName.addTextChangedListener(new AutoCompleteTextWatcher(actvDivName));
actvDivName.setOnItemClickListener(new AutoCompleteItemClickListener<TextItem>(QRDivTextItemList, actvDivName));
QRDivArrayAdapter = new CustomAdapter(mContext, R.layout.autocomplete_text_view, QRDivTextItemList);
actvDivName.setAdapter(QRDivArrayAdapter);
actvDivName.setCustomAutoCompleteTextViewListener(new CustomAutoCompleteTextView.CustomAutoCompleteTextViewListener() {
#Override
public void onItemSelected() {
try {
TextItem selectedItem = (TextItem) actvDivName.getTag();
InstRecyclerclear();
FailureRecyclerclear();
GeneralRecyclerclear();
actvPType.setText("");
ProdsItemList.clear();
actvDivName.setVisibility(View.VISIBLE);
actvPType.setVisibility(View.INVISIBLE);
cdAmc_entry.setVisibility(View.GONE);
trAMC.setVisibility(View.GONE);
if (selectedItem != null) {
instProd = (List<InstProd>) selectedItem.childObject;
for (int i = 0; i < instProd.size(); i++) {
TextItem item = new TextItem();
stn_pla_id = selectedItem.id;
item.headItemName = instProd.get(i).IName;
item.subItem1Name = instProd.get(i).MName;//String.valueOf(instProd.get(i).PID);
item.subItem2Name = instProd.get(i).NAME;//String.valueOf(instProd.get(i).IID);
item.id = instProd.get(i).PID;
item.did = instProd.get(i).IID;
prod_ID = instProd.get(i).PID;
ProdsItemList.add(item);
actvPType.setVisibility(View.VISIBLE);
actvPType.setEnabled(true);
}
}
QRProdArrayAdapter.setTextObjects(ProdsItemList);
} catch (Exception e) {
}
}
});
QRProdArrayAdapter = new CustomAdapter(mContext, R.layout.autocomplete_text_view, ProdsItemList);//added by pavani
actvPType.setAdapter(QRProdArrayAdapter);//added by pavani
actvPType.setThreshold(0);
actvPType.addTextChangedListener(new AutoCompleteTextWatcher(actvPType));
actvPType.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
try {
InstRecyclerclear();
FailureRecyclerclear();
GeneralRecyclerclear();
cdAmc_entry.setVisibility(View.GONE);
trAMC.setVisibility(View.GONE);
val = position;
iid = ProdsItemList.get(position).did;//Integer.parseInt(ProdsItemList.get(position).subItem2Name);
pid = ProdsItemList.get(position).id;//Integer.parseInt(ProdsItemList.get(position).subItem1Name);
station = ProdsItemList.get(position).headItemName;
product = ProdsItemList.get(position).subItem1Name;
} catch (Exception e) {
Log.d("eEmp/OnProdClick", "Exception Occurred due to " + e.toString());
}
}
});
actvDivName.setCustomSelectionActionModeCallback(new ActionMode.Callback() {
public boolean onPrepareActionMode(ActionMode mode, Menu menu) {
return false;
}
public void onDestroyActionMode(ActionMode mode) {
}
public boolean onCreateActionMode(ActionMode mode, Menu menu) {
return false;
}
public boolean onActionItemClicked(ActionMode mode, MenuItem item) {
return false;
}
});
entryFragment = (Entry_Fragment)
getFragmentManager().findFragmentByTag(EmpConstants.Entry_Info_Tag);
//set Station Name
if (StnIDFromAdapter != null) {
try {
long id = Long.parseLong(StnIDFromAdapter);
stn_pla_id = id;
for (int i = 0; i < DivStnList.size(); i++) {
if (id == DivStnList.get(i).id) {
actvDivName.setText(DivStnList.get(i).headItemName);
actvDivName.setEnabled(false);
}
}
} catch (Exception expt) {
}
}
//setting Product Name
if (ProdFromAdapter != null) {
try {
pid = ProdIdFromAdapter;
iid = ProdSno;
actvPType.setVisibility(View.VISIBLE);
actvPType.setText(ProdFromAdapter);
actvPType.setEnabled(false);
} catch (Exception expt) {
}
}
} catch (Exception expt) {
Log.d("eEmp/EntryCreate", "Exception Occurred due to " + expt.toString());
}
return rootView;
}
private TextWatcher textWatcher() {
return new TextWatcher() {
#Override
public void onTextChanged(CharSequence s, int start, int before, int count) {
try {
if (!actvDivName.getText().toString().equals("")) {
btnClear_stn.setVisibility(View.VISIBLE);
} else {
}
} catch (Exception e) {
}
}
#Override
public void beforeTextChanged(CharSequence s, int start, int count, int after) {
}
#Override
public void afterTextChanged(Editable s) {
}
};
}
}

error at notifyDataSetChanged

I am getting an error at notifydataset changed,i have added notify dataset changed even i am getting an error
public SelectUserAdapter(List<SelectUser> selectUsers, Context context) {
_data = selectUsers;
_c = context;
this.arraylist = new ArrayList<>();
this.arraylist.addAll(_data);
}
#Override
public int getCount() {
return _data.size();
}
#Override
public Object getItem(int i) {
return _data.get(i);
}
#Override
public long getItemId(int i) {
return i;
}
#SuppressLint("InflateParams")
#TargetApi(Build.VERSION_CODES.LOLLIPOP)
#Override
public View getView(int i, View convertView, ViewGroup viewGroup) {
View view = convertView;
if (view == null) {
LayoutInflater li = (LayoutInflater) _c.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
view = li.inflate(com.jamol.contacts.R.layout.contact_info, null);
} else {
view = convertView;
}
ViewHolder v = new ViewHolder();
v.title = (TextView) view.findViewById(com.jamol.contacts.R.id.name);
v.check = (CheckBox) view.findViewById(com.jamol.contacts.R.id.check);
v.setPhone((TextView) view.findViewById(com.jamol.contacts.R.id.no));
v.imageView = (ImageView) view.findViewById(com.jamol.contacts.R.id.pic);
final SelectUser data = _data.get(i);
v.title.setText(data.getName());
v.check.setChecked(data.getCheckedBox());
v.getPhone().setText(data.getPhone());
try {
if (data.getThumb() != null) {
v.imageView.setImageBitmap(data.getThumb());
} else {
v.imageView.setImageResource(com.jamol.contacts.R.drawable.ic_user);
}
} catch (OutOfMemoryError e) {
v.imageView.setImageDrawable(this._c.getDrawable(com.jamol.contacts.R.drawable.ic_user));
e.printStackTrace();
}
view.setTag(data);
return view;
}
public void filter(String charText) {
if (charText != null) {
charText = charText.toLowerCase(Locale.getDefault());
_data.clear();
if (charText.length() == 0) {
_data.addAll(arraylist);
} else {
for (SelectUser wp : arraylist)
if (wp.getName().toLowerCase(Locale.getDefault())
.contains(charText)) {
_data.add(wp);
}
}
}
notifyDataSetChanged();
}
static class ViewHolder {
ImageView imageView;
TextView title;
CheckBox check;
private TextView phone;
public TextView getPhone() {
return phone;
}
public void setPhone(TextView phone) {
this.phone = phone;
}
}
}
error is
FATAL EXCEPTION: main
Process: com.jamol.contacts, PID: 20086
java.lang.IllegalStateException: 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. Make sure your adapter calls
notifyDataSetChanged() when its content changes. [in
ListView(2131492978, class android.widget.ListView) with Adapter(class
com.jamol.contacts.SelectUserAdapter)]
at android.widget.ListView.layoutChildren(ListView.java:1584)
at android.widget.AbsListView.onLayout(AbsListView.java:2645)
at android.view.View.layout(View.java:16939)
at android.view.ViewGroup.layout(ViewGroup.java:5409)
at android.widget.RelativeLayout.onLayout(RelativeLayout.java:1077)
at android.view.View.layout(View.java:16939)
at android.view.ViewGroup.layout(ViewGroup.java:5409)
at android.widget.FrameLayout.layoutChildren(FrameLayout.java:579)
at android.widget.FrameLayout.onLayout(FrameLayout.java:514)
at android.view.View.layout(View.java:16939)
at android.view.ViewGroup.layout(ViewGroup.java:5409)
at android.widget.LinearLayout.setChildFrame(LinearLayout.java:1702)
at android.widget.LinearLayout.layoutVertical(LinearLayout.java:1556)
at android.widget.LinearLayout.onLayout(LinearLayout.java:1465)
at android.view.View.layout(View.java:16939)
at android.view.ViewGroup.layout(ViewGroup.java:5409)
at android.widget.FrameLayout.layoutChildren(FrameLayout.java:579)
at android.widget.FrameLayout.onLayout(FrameLayout.java:514)
at android.view.View.layout(View.java:16939)
at android.view.ViewGroup.layout(ViewGroup.java:5409)
at android.view.ViewRootImpl.performLayout(ViewRootImpl.java:2464)
at android.view.ViewRootImpl.performTraversals(ViewRootImpl.java:2167)
at android.view.ViewRootImpl.doTraversal(ViewRootImpl.java:1301)
at
android.view.ViewRootImpl$TraversalRunnable.run(ViewRootImpl.java:7016)
at
android.view.Choreographer$CallbackRecord.run(Choreographer.java:777)
at android.view.Choreographer.doCallbacks(Choreographer.java:590)
at android.view.Choreographer.doFrame(Choreographer.java:560)
at
android.view.Choreographer$FrameDisplayEventReceiver.run(Choreographer.java:763)
at android.os.Handler.handleCallback(Handler.java:739)
at android.os.Handler.dispatchMessage(Handler.java:95)
at android.os.Looper.loop(Looper.java:145)
at android.app.ActivityThread.main(ActivityThread.java:6946)
at java.lang.reflect.Method.invoke(Native Method)
at java.lang.reflect.Method.invoke(Method.java:372)
at
com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1404)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1199) 02-04
16:52:56.033 20086-20086/com.jamol.contacts I/Process: Sending signal.
PID: 20086 SIG: 9
MainActivity is
private class LoadContact extends AsyncTask<Void, Void, Void> {
#Override
protected void onPreExecute() {
super.onPreExecute();
}
#Nullable
#Override
protected Void doInBackground(Void... voids) {
if (phones != null) {
Log.e("count", "" + phones.getCount());
if (phones.getCount() == 0) {
Log.d("No Contacts", "No Contacts");
}
while (phones.moveToNext()) {
AtomicReference<Bitmap> bit_thumb = new AtomicReference<>(null);
String name = phones.getString(phones.getColumnIndex(ContactsContract.CommonDataKinds.Phone.DISPLAY_NAME));
String phoneNumber = phones.getString(phones.getColumnIndex(ContactsContract.CommonDataKinds.Phone.NUMBER));
String image_thumb = phones.getString(phones.getColumnIndex(ContactsContract.CommonDataKinds.Phone.PHOTO_URI));
try {
if (image_thumb != null) {
bit_thumb.set(MediaStore.Images.Media.getBitmap(resolver, Uri.parse(image_thumb)));
} else {
Log.d("dont show any images", "dont show any images");
//bit_thumb = MediaStore.Images.Media.getBitmap(resolver, Uri.parse(image_thumb));
}
} catch (IOException e) {
e.printStackTrace();
}
SelectUser selectUser = new SelectUser();
selectUser.setThumb(bit_thumb.get());
selectUser.setName(name);
selectUser.setPhone(phoneNumber);
selectUser.setCheckedBox();
if (selectUsers == null) throw new AssertionError();
selectUsers.add(selectUser);
}
} else {
Log.e("Cursor close 1", "----------------");
}
//phones.close();
return null;
}
#Override
protected void onPostExecute(Void aVoid) {
super.onPostExecute(aVoid);
adapter = new SelectUserAdapter(selectUsers, MainActivity.this);
listView.setAdapter(adapter);
listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#TargetApi(Build.VERSION_CODES.LOLLIPOP)
#Override
public void onItemClick(AdapterView<?> adapterView, View view, int position, long l) {
synchronized (MainActivity.this) {
if (firstClickTime == 0) {
firstClickTime = SystemClock.elapsedRealtime();
nonDoubleClick = true;
} else {
long deltaTime = SystemClock.elapsedRealtime() - firstClickTime;
firstClickTime = 0;
if (deltaTime < DOUBLE_CLICK_TIMEOUT) {
nonDoubleClick = false;
this.onItemDoubleClick(adapterView, view, position, l);
return;
}
}
view.postDelayed(new Runnable() {
#Override
public void run() {
if (nonDoubleClick) {
Log.d("Single click", "single click");
}
}
}, DOUBLE_CLICK_TIMEOUT);
}
}
public void onItemDoubleClick(AdapterView<?> parent, View view, int position, long id) {
String selected = ((TextView) view.findViewById(com.jamol.contacts.R.id.no)).getText().toString();
try {
mediaPlayer = MediaPlayer.create(MainActivity.this, R.raw.call);
mediaPlayer.setVolume(1.0f, 1.0f);
mediaPlayer.setLooping(false);
mediaPlayer.start();
Vibrator v = (Vibrator) MainActivity.this.getSystemService(Context.VIBRATOR_SERVICE);
v.vibrate(500);
Intent in = new Intent(Intent.ACTION_CALL, Uri.parse("tel:" + selected));
startActivity(in);
} catch (SecurityException e) {
Log.e("PERMISSION_EXCEPTION", "PERMISSION_NOT_GRANTED");
}
}
}
);
listView.setFastScrollEnabled(true);
}
}
Try adding notifyDataSetChanged() after listView.setAdapter(adapter); in your onPostExecute() method
You are calling filter(String str) from a background thread which is calling notifyDataSetChanged(). Make sure notifyDataSetChanged() is called on Main UI thread.
You are calling "notifyDataSetChanged();" inside the SelectUserAdapter, Remove that. you can use "notifyDataSetChanged()" after List selectUsers get changed/modified. Call "notifyDataSetChanged();" like this
adapter.notifyDataSetChanged();
Note: You should call this "adapter.notifyDataSetChanged();" after setting adapter to the listView (listView.setAdapter(adapter);)

java.lang.IndexOutOfBoundsException on ArrayList

I am having trouble when I open activity from one activity, and when I press back button of the phone the app crashes. Here I have described all details of activity and fragment.
FeedFragment.java
public class FeedFragment extends BaseFragment {
ListView lvFeeds;
TextView tvNoRecord;
public static Handler[] handler;
public static Runnable[] animateViewPager;
static Handler bannerHandler;
static Runnable bannerRunnable;
boolean stopSliding = false;
boolean isLastItemLoaded = false;
FeedAdapter feedAdapter;
ArrayList<FeedBean> feedList = new ArrayList<>();
int[] bannerImages = new int[]{
R.drawable.ic_feed_one,
R.drawable.ic_feed_two,
R.drawable.ic_feed_three,
R.drawable.ic_feed_four,
R.drawable.ic_feed_five
};
String articleId;
static int position = 0;
#SuppressLint("NewApi")
#Nullable
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_feed, container, false);
lvFeeds = (ListView) view.findViewById(R.id.lvFeeds);
tvNoRecord = (TextView) view.findViewById(R.id.tvNoRecord);
LayoutInflater mInflater = (LayoutInflater) getActivity()
.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
final View headerView = mInflater.inflate(R.layout.feed_banner_view, null);
CirclePageIndicator cpiBanner = (CirclePageIndicator) headerView.findViewById(R.id.indicators);
final JazzyViewPager vpFeedBanner = (JazzyViewPager) headerView.findViewById(R.id.vpFeeds);
vpFeedBanner.setTransitionEffect(JazzyViewPager.TransitionEffect.Accordion);
BannerAdapter pagerAdapter = new BannerAdapter(vpFeedBanner);
vpFeedBanner.setAdapter(pagerAdapter);
cpiBanner.setViewPager(vpFeedBanner);
cpiBanner.setCurrentItem(vpFeedBanner.getCurrentItem());
lvFeeds.addHeaderView(headerView);
listFeed();
bannerHandler = new Handler();
bannerRunnable = new Runnable() {
public void run() {
try {
if (position >= bannerImages.length - 1) {
vpFeedBanner.setCurrentItem(0);
} else {
vpFeedBanner.setCurrentItem(
vpFeedBanner.getCurrentItem() + 1, true);
}
bannerHandler.postDelayed(bannerRunnable, Constant.VP_ANIMATION_TIME);
} catch (Exception e) {
e.printStackTrace();
}
}
};
return view;
}
#Override
public void onResume() {
super.onResume();
try {
if (!feedList.isEmpty())
setAllSlidingAnimation(feedList.size());
bannerHandler.postDelayed(bannerRunnable, Constant.VP_ANIMATION_TIME);
} catch (Exception e) {
e.printStackTrace();
}
}
#Override
public void onPause() {
super.onPause();
try {
if (bannerHandler != null) {
bannerHandler.removeCallbacks(bannerRunnable);
}
if (!feedList.isEmpty())
removeAllSlidingAnimation(feedList.size());
} catch (Exception e) {
e.printStackTrace();
}
}
class BannerAdapter extends PagerAdapter {
JazzyViewPager vpFloor;
LayoutInflater mInflater;
public BannerAdapter(JazzyViewPager viewPager) {
this.vpFloor = viewPager;
mInflater = (LayoutInflater) getActivity()
.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
}
class ViewHolder {
RoundedImageView ivFeed;
}
#Override
public void destroyItem(ViewGroup container, int position, Object object) {
container.removeView(vpFloor.findViewFromObject(position));
}
#Override
public Object instantiateItem(ViewGroup container, final int position) {
final ViewHolder viewHolder = new ViewHolder();
View layout = mInflater.inflate(R.layout.row_feed_view_pager_banner, null);
viewHolder.ivFeed = (RoundedImageView) layout.findViewById(R.id.ivFeed);
try {
BaseActivity.setImageToBanner(getActivity(), bannerImages[position], viewHolder.ivFeed);
viewHolder.ivFeed.setImageDrawable(getResources().getDrawable(bannerImages[position]));
vpFloor.setObjectForPosition(layout, position);
container.addView(layout);
} catch (Exception e) {
e.printStackTrace();
}
return layout;
}
#Override
public int getCount() {
return bannerImages.length;
}
#Override
public boolean isViewFromObject(View view, Object object) {
if (view instanceof OutlineContainer) {
return ((OutlineContainer) view).getChildAt(0) == object;
} else {
return view == object;
}
}
}
void listFeed() {
BaseActivity.showLoader(getActivity());
JSONObject feedObj = null;
RequestQueue queue = Volley.newRequestQueue(getActivity());
final String serverRequest = Constant.WEB_SERVICE_LIST_FEED;
Log.e("", "ListFeed URL : " + serverRequest);
JsonObjectRequest jsObjRequest = new JsonObjectRequest(
com.android.volley.Request.Method.POST, serverRequest,
null, new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject response) {
try {
Log.e("",
"ListFeed Response : " + response.toString());
JSONObject serverResponse = response
.getJSONObject(Constant.LIST_FEED_ACTION);
String Ws_Status = serverResponse.getString(Constant.TAG_STATUS);
String Ws_Message = serverResponse.getString(Constant.TAG_MESSAGE);
BaseActivity.hideLoader();
if (serverResponse.getString(Constant.TAG_STATUS)
.equalsIgnoreCase(Constant.TAG_STATUS_FAILURE)) {
} else {
feedList.clear();
JSONArray categoriesArray = serverResponse.getJSONArray(Constant.TAG_CATEGORIES);
int categoryLength = categoriesArray.length();
handler = new Handler[categoryLength + 1];
animateViewPager = new Runnable[categoryLength + 1];
for (int i = 0; i < categoriesArray.length(); i++) {
JSONObject categoriesObject = categoriesArray.getJSONObject(i);
FeedBean feedBean = new FeedBean();
feedBean.setId(categoriesObject.getString(Constant.TAG_ID));
feedBean.setName(categoriesObject.getString(Constant.TAG_NAME));
JSONArray articles = categoriesObject.getJSONArray(Constant.TAG_ARTICLES);
ArrayList<ArticleBean> articleList = new ArrayList<>();
for (int j = 0; j < articles.length(); j++) {
JSONObject articlesObject = articles.getJSONObject(j);
ArticleBean articleBean = new ArticleBean();
articleBean.setId(articlesObject.getString(Constant.TAG_ID));
articleBean.setTitle(articlesObject.getString(Constant.TAG_TITLE));
articleBean.setTimeLapsed(articlesObject.getString(Constant.TAG_TIME_LAPSED));
articleBean.setBody(articlesObject.getString(Constant.TAG_BODY));
articleBean.setArticleUrl(articlesObject.getString(Constant.TAG_ARTICLE_URL));
articleBean.setTags(articlesObject.getString(Constant.TAG_TAGS));
articleBean.setUserId(articlesObject.getString(Constant.TAG_USER_ID));
articleBean.setFeaturedImage(articlesObject.getString(Constant.TAG_FEATURED_IMAGE));
articleBean.setLikeCounter(articlesObject.getString(Constant.TAG_LIKE_COUNTER));
articleBean.setLocation(articlesObject.getString(Constant.TAG_LOCATION));
articleList.add(articleBean);
}
feedBean.articleBeanList = articleList;
int articleLength = articles.length();
feedBean.setArticleLength(articleLength);
feedList.add(feedBean);
}
feedAdapter = new FeedAdapter();
lvFeeds.setAdapter(feedAdapter);
removeAllSlidingAnimation(feedList.size());
setAllSlidingAnimation(feedList.size());
}
} catch (Exception e) {
BaseActivity.hideLoader();
e.printStackTrace();
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError e) {
BaseActivity.hideLoader();
e.printStackTrace();
}
});
jsObjRequest.setRetryPolicy(new DefaultRetryPolicy(Constant.WEB_SERVICE_TIME_OUT,
DefaultRetryPolicy.DEFAULT_MAX_RETRIES,
DefaultRetryPolicy.DEFAULT_BACKOFF_MULT));
queue.add(jsObjRequest);
}
void removeAllSlidingAnimation(int length) {
try {
for (int i = 0; i < length; i++) {
if (handler[i] != null) {
handler[i].removeCallbacks(animateViewPager[i]);
}
}
} catch (Exception e) {
e.printStackTrace();
}
}
void setAllSlidingAnimation(int length) {
try {
for (int i = 0; i < length; i++) {
if (handler[i] != null) {
handler[i].postDelayed(animateViewPager[i], Constant.VP_ANIMATION_TIME);
}
}
} catch (Exception e) {
e.printStackTrace();
}
}
public void runnable(final int size, final JazzyViewPager mViewPager, final int position) {
try {
handler[position] = new Handler();
animateViewPager[position] = new Runnable() {
public void run() {
if (!stopSliding) {
if (mViewPager.getCurrentItem() == size - 1) {
mViewPager.setCurrentItem(0);
} else {
mViewPager.setCurrentItem(
mViewPager.getCurrentItem() + 1, true);
}
try {
handler[position].postDelayed(animateViewPager[position], Constant.VP_ANIMATION_TIME);
} catch (NullPointerException e) {
e.printStackTrace();
}
}
}
};
} catch (Exception e) {
e.printStackTrace();
}
}
class FeedAdapter extends BaseAdapter {
private LayoutInflater inflater = null;
public FeedAdapter() {
inflater = (LayoutInflater) getActivity()
.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
}
#Override
public int getCount() {
return feedList.size();
}
#Override
public Object getItem(int position) {
return feedList.get(position);
}
#Override
public long getItemId(int position) {
return position;
}
#Override
public View getView(int i, View convertView, ViewGroup parent) {
View itemView = convertView;
ViewHolder viewHolder = null;
if (convertView == null) {
itemView = inflater.inflate(R.layout.row_feed, null);
viewHolder = new ViewHolder();
viewHolder.llFeed = (LinearLayout) itemView.findViewById(R.id.llFeed);
viewHolder.vpFeeds = (JazzyViewPager) itemView.findViewById(R.id.vpFeeds);
viewHolder.indicators = (CirclePageIndicator) itemView.findViewById(R.id.indicators);
viewHolder.tvFeedTitle = (TextView) itemView.findViewById(R.id.tvFeedTitle);
viewHolder.tvFeedSubTitle = (TextView) itemView.findViewById(R.id.tvFeedSubTitle);
viewHolder.tvFeedTime = (TextView) itemView.findViewById(R.id.tvFeedTime);
viewHolder.tvCategoryName = (TextView) itemView.findViewById(R.id.tvCategoryName);
viewHolder.vpFeeds.setTransitionEffect(JazzyViewPager.TransitionEffect.Accordion);
itemView.setTag(viewHolder);
} else {
viewHolder = (ViewHolder) itemView.getTag();
}
try {
FeedBean bean = feedList.get(i);
FeedPagerAdapter pagerAdapter = new FeedPagerAdapter(viewHolder.vpFeeds, viewHolder.tvFeedTitle, viewHolder.tvFeedSubTitle, viewHolder.tvFeedTime, bean, viewHolder.llFeed, viewHolder.indicators);
viewHolder.vpFeeds.setAdapter(pagerAdapter);
viewHolder.indicators.setViewPager(viewHolder.vpFeeds);
viewHolder.indicators.setCurrentItem(viewHolder.vpFeeds.getCurrentItem());
viewHolder.tvCategoryName.setText(bean.getName().toUpperCase().trim());
if (viewHolder.tvCategoryName.getText().toString().equalsIgnoreCase(Constant.CAT_FEATURED)) {
viewHolder.tvCategoryName.setBackgroundColor(getResources().getColor(R.color.color_feed_yellow));
} else if (viewHolder.tvCategoryName.getText().toString().equalsIgnoreCase(Constant.CAT_ORIGINAL)) {
viewHolder.tvCategoryName.setBackgroundColor(getResources().getColor(R.color.color_feed_purple));
} else if (viewHolder.tvCategoryName.getText().toString().equalsIgnoreCase(Constant.CAT_MUSIC)) {
viewHolder.tvCategoryName.setBackgroundColor(getResources().getColor(R.color.color_feed_pink));
} else if (viewHolder.tvCategoryName.getText().toString().equalsIgnoreCase(Constant.CAT_GIVE)) {
viewHolder.tvCategoryName.setBackgroundColor(getResources().getColor(R.color.color_feed_lightGreen));
} else if (viewHolder.tvCategoryName.getText().toString().equalsIgnoreCase(Constant.CAT_LIFESTYLE)) {
viewHolder.tvCategoryName.setBackgroundColor(getResources().getColor(R.color.color_feed_parrot));
} else if (viewHolder.tvCategoryName.getText().toString().equalsIgnoreCase(Constant.CAT_INSPIRATION)) {
viewHolder.tvCategoryName.setBackgroundColor(getResources().getColor(R.color.color_feed_lightRed));
} else if (viewHolder.tvCategoryName.getText().toString().equalsIgnoreCase(Constant.CAT_TECH)) {
viewHolder.tvCategoryName.setBackgroundColor(getResources().getColor(R.color.color_lightBlack));
} else if (viewHolder.tvCategoryName.getText().toString().equalsIgnoreCase(Constant.CAT_FASHION)) {
viewHolder.tvCategoryName.setBackgroundColor(getResources().getColor(R.color.color_feed_lightBlue));
} else {
viewHolder.tvCategoryName.setBackgroundColor(getResources().getColor(R.color.color_feed_pink));
}
runnable(bean.getArticleLength(), viewHolder.vpFeeds, i);
if (i != 0)
if ((i + 1) % 2 == 0) {
if (!isLastItemLoaded) {
removeAllSlidingAnimation(i);
setAllSlidingAnimation(i);
}
}
} catch (Exception e) {
e.printStackTrace();
}
return itemView;
}
class ViewHolder {
JazzyViewPager vpFeeds;
TextView tvFeedTitle, tvFeedSubTitle, tvFeedTime, tvCategoryName;
CirclePageIndicator indicators;
LinearLayout llFeed;
}
}
class FeedPagerAdapter extends PagerAdapter {
JazzyViewPager vpFloor;
private LayoutInflater mInflater;
TextView tvFeedTitle, tvFeedSubTitle, tvFeedTime;
FeedBean bean;
LinearLayout llFeed;
CirclePageIndicator indicators;
public FeedPagerAdapter(JazzyViewPager vpFloor, TextView tvFeedTitle, TextView tvFeedSubTitle, TextView tvFeedTime, FeedBean bean, LinearLayout llFeed, CirclePageIndicator indicators) {
this.vpFloor = vpFloor;
mInflater = (LayoutInflater) getActivity()
.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
this.tvFeedTitle = tvFeedTitle;
this.tvFeedTime = tvFeedTime;
this.tvFeedSubTitle = tvFeedSubTitle;
this.bean = bean;
this.llFeed = llFeed;
this.indicators = indicators;
}
#Override
public void destroyItem(ViewGroup container, int position, Object object) {
container.removeView(vpFloor.findViewFromObject(position));
}
#Override
public Object instantiateItem(ViewGroup container, final int position) {
final ViewHolder viewHolder = new ViewHolder();
View layout = mInflater.inflate(R.layout.row_feed_view_pager, null);
viewHolder.ivFeed = (RoundedImageView) layout.findViewById(R.id.ivFeed);
try {
BaseActivity.setImageToView(getActivity(), bean.articleBeanList.get(position).getFeaturedImage(), viewHolder.ivFeed);
} catch (Exception e) {
e.printStackTrace();
}
llFeed.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
try {
if (bean.articleBeanList.size() == 1) {
openDetailActivity(bean.articleBeanList.get(position).getId());
} else {
openDetailActivity(bean.articleBeanList.get(position).getId());
}
} catch (Exception e) {
e.printStackTrace();
}
}
});
vpFloor.setOnPageChangeListener(new ViewPager.OnPageChangeListener() {
#Override
public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {
}
#Override
public void onPageSelected(int position) {
try {
tvFeedTitle.setText(bean.articleBeanList.get(position).getTitle().toUpperCase());
tvFeedSubTitle.setText(bean.articleBeanList.get(position).getBody().toUpperCase());
tvFeedTime.setText(bean.articleBeanList.get(position).getTimeLapsed().toUpperCase());
articleId = bean.articleBeanList.get(position).getId();
indicators.setCurrentItem(position);
} catch (Exception e) {
e.printStackTrace();
}
}
#Override
public void onPageScrollStateChanged(int state) {
}
});
layout.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
try {
if (bean.articleBeanList.size() == 1) {
openDetailActivity(bean.articleBeanList.get(position).getId());
} else {
openDetailActivity(bean.articleBeanList.get(position).getId());
}
} catch (Exception e) {
}
}
});
try {
vpFloor.setObjectForPosition(layout, position);
tvFeedTitle.setText(bean.articleBeanList.get(vpFloor.getCurrentItem()).getTitle().toUpperCase());
tvFeedTitle.setText(bean.articleBeanList.get(vpFloor.getCurrentItem()).getTitle().toUpperCase());
tvFeedSubTitle.setText(bean.articleBeanList.get(vpFloor.getCurrentItem()).getBody().toUpperCase());
tvFeedTime.setText(bean.articleBeanList.get(vpFloor.getCurrentItem()).getTimeLapsed().toUpperCase());
articleId = bean.articleBeanList.get(vpFloor.getCurrentItem()).getId();
} catch (Exception e) {
e.printStackTrace();
}
container.addView(layout);
return layout;
}
class ViewHolder {
RoundedImageView ivFeed;
}
#Override
public int getCount() {
return bean.getArticleLength();
}
#Override
public boolean isViewFromObject(View view, Object obj) {
if (view instanceof OutlineContainer) {
return ((OutlineContainer) view).getChildAt(0) == obj;
} else {
return view == obj;
}
}
}
void openDetailActivity(String articleId) {
startActivity(new Intent(DashboardActivity.context, StoriesDetailsActivity.class).putExtra(Constant.TAG_ID, articleId));
}
}
Logcat
FATAL EXCEPTION: main
01-19 19:27:29.134 19925-19925/com.cultureapp E/AndroidRuntime: Process: com.cultureapp, PID: 19925
01-19 19:27:29.134 19925-19925/com.cultureapp E/AndroidRuntime: java.lang.IndexOutOfBoundsException: Invalid index 1, size is 1
01-19 19:27:29.134 19925-19925/com.cultureapp E/AndroidRuntime: at java.util.ArrayList.throwIndexOutOfBoundsException(ArrayList.java:255)
01-19 19:27:29.134 19925-19925/com.cultureapp E/AndroidRuntime: at java.util.ArrayList.get(ArrayList.java:308)
01-19 19:27:29.134 19925-19925/com.cultureapp E/AndroidRuntime: at android.widget.HeaderViewListAdapter.isEnabled(HeaderViewListAdapter.java:164)
In your code, your are calling something like list.get(1) but list size is 1. So, you can only call list.get(0). You are trying to reach to the non-existence objects.
The java.lang.IndexOutOfBoundsException means:
You have an ArrayList which has 1 element so you can only get the element at position 0.
But here, you're trying to access to the element at position 1 which is impossible because it does not exists.
The problem is probably here:
#Override
public void onResume() {
super.onResume();
try {
if (!feedList.isEmpty())
setAllSlidingAnimation(feedList.size());
...
}
If the size of feedList is 1, you will try to access to the SECOND element (first is at position 0, second is at position 1 == feedList.size()).

App is keep crashing while accessing the listview

In my app I'm showing data in listview. While scrolling through listview my app is crashing. What changes should I make?
as given in the error my RecipeListFragment.java file is:
public class RecipeListFragment extends Fragment {
MyDatabase db;
boolean isfav = false;
Context context;
ListView lvrecipe;
ArrayList<RecipePojo> recipelist = new ArrayList<RecipePojo>();
LinearLayout ll;
DisplayImageOptions options;
private ProgressDialog progress;
int position;
String recipeid;
int checkcounter = 0;
private Custom_Adapter adapter;
public RecipeListFragment() {
}
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.activity_recipe_list_actvity, container, false);
context = getActivity();
lvrecipe = (ListView) rootView.findViewById(R.id.lvrecipe);
// adView = (MoPubView)rootView. findViewById(R.id.mopub_sample_ad);
new getrecipe().execute();
db = new MyDatabase(getActivity());
// recipelist = DataManager.recipelist;
position = DataManager.selectedposition;
adapter = new Custom_Adapter(getActivity());
adapter.notifyDataSetChanged();
lvrecipe.setAdapter(adapter);
/* if(recipeid!=null){
checkcounter = db.checkrecipefav(recipeid);
}
if (checkcounter > 0) {
isfav = true;
} else {
isfav = false;
}
db.close();*/
lvrecipe.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
DataManager.selectedposition = position;
Intent i = new Intent(getActivity(), RecipeDescription.class);
i.putExtra("cusinename", DataManager.cusinename);
startActivity(i);
getActivity().finish();
}
});
// adddisplay();
return rootView;
}
#Override
public void onResume() {
super.onResume();
}
public class Custom_Adapter extends BaseAdapter {
private LayoutInflater mInflater;
public Custom_Adapter(Context c) {
mInflater = LayoutInflater.from(c);
}
#Override
public int getCount() {
if (recipelist != null) {
return recipelist.size();
} else {
return 0;
}
}
#Override
public Object getItem(int position) {
if (recipelist != null) {
return recipelist.get(position);
} else {
return 0;
}
}
#Override
public long getItemId(int position) {
if (recipelist != null) {
return position;
} else {
return 0;
}
}
#SuppressWarnings("deprecation")
#Override
public View getView(int position, View convertView, ViewGroup parent) {
ViewHolder holder;
if (convertView == null) {
convertView = mInflater.inflate(R.layout.recipelist, null);
holder = new ViewHolder();
holder.txttile = (TextView) convertView.findViewById(R.id.txttile);
holder.imgrecipe = (ImageView) convertView.findViewById(R.id.imgrecipe);
holder.fav_unfav = (ImageView) convertView.findViewById(R.id.fav_unfav);
holder.ratingbar = (RatingBar) convertView.findViewById(R.id.ratingbar);
holder.txtduration = (TextView) convertView.findViewById(R.id.txtduration);
convertView.setTag(holder);
} else {
holder = (ViewHolder) convertView.getTag();
}
if (recipelist != null) {
recipeid = recipelist.get(position).getRecipeid();
checkcounter = db.checkrecipefav(recipeid);
}
if (checkcounter > 0) {
isfav = true;
} else {
isfav = false;
}
db.close();
if (isfav) {
holder.fav_unfav.setImageResource(R.drawable.favourite);
} else {
holder.fav_unfav.setImageResource(R.drawable.favourites);
}
Typeface face1 = Typeface.createFromAsset(getActivity().getAssets(), "sinkin_sans_300_light.ttf");
Typeface face2 = Typeface.createFromAsset(getActivity().getAssets(), "sinkin_sans_400_regular.ttf");
holder.txttile.setTypeface(face2);
holder.txtduration.setTypeface(face1);
holder.txttile.setText(recipelist.get(position).getRecipename());
try {
String[] prep = recipelist.get(position).getPrep_time().split(" ");
String[] cook = recipelist.get(position).getCooking_time().split(" ");
int totalTime = Integer.parseInt(prep[0]) + Integer.parseInt(cook[0]);
holder.txtduration.setText(""+totalTime+" min");
} catch (NumberFormatException e) {
e.printStackTrace();
} catch (Exception e) {
e.printStackTrace();
}
String url = DataManager.photourl + "recipe/" + recipelist.get(position).getRecipeid() + ".jpg";
try {
url = URLDecoder.decode(url, "UTF-8");
url = url.replaceAll(" ", "%20");
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
} catch (Exception e) {
e.printStackTrace();
}
if (recipelist.get(position).getVideo_link().equals("none")) {
// holder.imgvideo.setVisibility(View.GONE);
}
String rating = recipelist.get(position).getRatings();
if (rating != null && rating.trim().length() > 0) {
holder.ratingbar.setRating(Float.valueOf(rating));
}
//holder.imgrecipe.setImage(url,getResources().getDrawable(R.drawable.cusine));
if (holder.imgrecipe != null) {
if (url != null && url.trim().length() > 0) {
//final ProgressBar pbar = holder.pbar;
final ImageView imageView = holder.imgrecipe;
//final RelativeLayout imgRL = holder.imageRL;
ImageLoader.getInstance().displayImage(url, holder.imgrecipe, options, new SimpleImageLoadingListener() {
#Override
public void onLoadingComplete(String imageUri,
View view, Bitmap loadedImage) {
super.onLoadingComplete(imageUri, view, loadedImage);
imageView.setAdjustViewBounds(true);
}
#Override
public void onLoadingFailed(String imageUri, View view, FailReason failReason) {
super.onLoadingFailed(imageUri, view, failReason);
}
#Override
public void onLoadingStarted(String imageUri, View view) {
super.onLoadingStarted(imageUri, view);
}
});
} else {
}
}
return convertView;
}
class ViewHolder {
TextView txttile, txtduration;
ImageView imgrecipe;
ImageView fav_unfav;
RatingBar ratingbar;
}
}
public class getrecipe extends AsyncTask<String, Void, String> {
boolean response = false;
#Override
protected void onPreExecute() {
//progress = ProgressDialog.show(context, "Getting Data...","Please wait....");
progress = new ProgressDialog(getActivity());
progress.setMessage("Please wait....");
progress.show();
}
#Override
protected String doInBackground(String... params) {
response = APIManager.getrecipebycusine(DataManager.CUISINE_ID);
return "";
}
#Override
protected void onPostExecute(String result) {
progress.cancel();
if (response) {
if (DataManager.status.equalsIgnoreCase("1")) {
recipelist = DataManager.recipelist;
adapter.notifyDataSetChanged();
//Intent i = new Intent(getActivity(),RecipeListActvity.class);
//startActivity(i);
} else {
connectionerror();
}
} else {
connectionerror();
}
}
#Override
protected void onProgressUpdate(Void... values) {
}
}
public void alert() {
AlertDialog.Builder alertDialog = new AlertDialog.Builder(getActivity());
alertDialog.setTitle("No Recipe!");
alertDialog.setMessage("No Recipe for this Cusine");
alertDialog.setPositiveButton("OK",
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
}
});
alertDialog.show();
}
private static class AnimateFirstDisplayListener extends SimpleImageLoadingListener {
static final List<String> displayedImages = Collections.synchronizedList(new LinkedList<String>());
#Override
public void onLoadingComplete(String imageUri, View view, Bitmap loadedImage) {
if (loadedImage != null) {
ImageView imageView = (ImageView) view;
boolean firstDisplay = !displayedImages.contains(imageUri);
if (firstDisplay) {
FadeInBitmapDisplayer.animate(imageView, 500);
displayedImages.add(imageUri);
}
}
}
}
public void connectionerror() {
AlertDialog.Builder alertDialog = new AlertDialog.Builder(getActivity());
alertDialog.setTitle("Error!");
alertDialog.setMessage("Connection Lost ! Try Again");
alertDialog.setPositiveButton("Retry",
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
new getrecipe().execute();
}
});
alertDialog.show();
}}
The errors that are showing in Crashlytics is:
Fatal Exception: java.lang.NullPointerException: Attempt to invoke virtual method 'android.content.res.Resources$Theme android.content.Context.getTheme()' on a null object reference
at android.app.AlertDialog.resolveDialogTheme(AlertDialog.java:154)
at android.app.AlertDialog$Builder.<init>(AlertDialog.java:379)
at com.raccoonfinger.salad.RecipeListFragment.connectionerror(RecipeListFragment.java:381)
at com.raccoonfinger.salad.RecipeListFragment$getrecipe.onPostExecute(RecipeListFragment.java:335)
at com.raccoonfinger.salad.RecipeListFragment$getrecipe.onPostExecute(RecipeListFragment.java:296)
at android.os.AsyncTask.finish(AsyncTask.java:632)
at android.os.AsyncTask.access$600(AsyncTask.java:177)
at android.os.AsyncTask$InternalHandler.handleMessage(AsyncTask.java:645)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:135)
at android.app.ActivityThread.main(ActivityThread.java:5312)
at java.lang.reflect.Method.invoke(Method.java)
at java.lang.reflect.Method.invoke(Method.java:372)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:901)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:696)
Please do not use getActivity() directly in Fragment because sometimes it returns null..
Always pass activity as a parameter in constructor..!!
Please use below method to create your Fragment and use activity reference instead of getActivity()..
public static AboutFragment newInstance(Activity activity) {
AboutFragment aboutFragment = new AboutFragment();
aboutFragment.mActivity = activity;
return aboutFragment;
}
Hope it will help.
Thanks ..!!

Remaining item positions in ListView is incorrect after deleting items

I'm having trouble with getting the correct items after deleting an item in my ListView.
The position should fit to the index of the item in an ArrayList, but after deleting an item in the ListView, the positions are incorrect (and might even give an indexoutofbounds exception.
I bet it has something to do with the Views position, but I just can't find the error.
I have this ListActivity class with an inner BaseAdapter class:
public class MSMobilMyStocksActivity extends ListActivity {
static MyStocksCtr myStocksCtr;
static ListView listview;
static EfficientAdapter adap;
boolean downloadSuccess;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.mystockslist);
mContext = this;
listview = getListView();
myStocksCtr = MyStocksCtr.getInstance(mContext);
adap = new EfficientAdapter(this);
setListAdapter(adap);
if (isOnline())
new InsertDataTask().execute();
else {
startTimer();
Toast.makeText(mContext, "Du har ingen internetforbindelse", 1000)
.show();
}
}
public static boolean updateData() {
return myStocksCtr.downloadJson();
}
private class InsertDataTask extends AsyncTask<Void, Void, Void> {
#Override
protected void onPreExecute() {
try {
listview.setEnabled(false);
} catch (Exception e) {
}
}
// can use UI thread here
#Override
protected void onPostExecute(final Void unused) {
if (isOnline()) {
if (downloadSuccess) {
try {
if (myStocksCtr.getArray().size() == 0) {
Toast.makeText(mContext, "Ingen data hentet", 2000)
.show();
} else if (myStocksCtr.getArray().size() == 1
&& myStocksCtr.getArray().get(0)
.getString("FH_FULLNAME").equals("-")) {
Toast.makeText(mContext, "Ingen data hentet", 2000)
.show();
} else {
adap.notifyDataSetChanged();
}
} catch (JSONException e) {
Toast.makeText(mContext, "JSONException", 2000).show();
}
}
} else
Toast.makeText(mContext, "Du har ingen internetforbindelse",
1000).show();
startTimer();
try {
listview.setEnabled(true);
} catch (Exception e) {
}
}
#Override
protected Void doInBackground(Void... arg0) {
downloadSuccess = false;
if (isOnline()) {
try {
if (updateData())
downloadSuccess = true;
} catch (Exception e) {
Toast.makeText(mContext, "Fejl under download af data",
2000).show();
downloadSuccess = false;
}
} else
Toast.makeText(mContext, "Du har ingen internetforbindelse",
1000).show();
return null;
}
}
}
public static class EfficientAdapter extends BaseAdapter implements
Filterable {
private LayoutInflater mInflater;
private Context context;
public EfficientAdapter(Context context) {
mInflater = LayoutInflater.from(context);
this.context = context;
}
#Override
public View getView(final int position, View convertView,
ViewGroup parent) {
final ViewHolder holder;
if (convertView == null) {
convertView = mInflater.inflate(R.layout.mylistitem, null);
holder = new ViewHolder();
holder.stockName = (TextView) convertView
.findViewById(R.id.stockName1);
holder.stockPrice = (TextView) convertView
.findViewById(R.id.stockValue1);
holder.stockChange = (TextView) convertView
.findViewById(R.id.stockChange1);
holder.stockPctChange = (TextView) convertView
.findViewById(R.id.stockPctChange1);
convertView.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
try {
Intent i = new Intent(mContext, MSStockDetailActivity.class);
Bundle b = new Bundle();
b.putInt("position", position); //Your id
b.putBoolean("isMyStocks", true);
i.putExtras(b); //Put your id to your next Intent
mContext.startActivity(i);
} catch (Exception e) {
Toast.makeText(mContext, "OnClick error ", 2000)
.show();
}
}
});
convertView.setOnLongClickListener(new OnLongClickListener() {
#Override
public boolean onLongClick(View arg0) {
final CharSequence[] items = {
"See stock details",
"Delete the stock \"" + holder.stockName.getText()
+ "\" from the list", "Cancel" };
AlertDialog.Builder builder = new AlertDialog.Builder(
mContext);
builder.setTitle("Configure list");
builder.setItems(items,
new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog,
int item) {
if (item == 1) {
myStocksCtr.removeStock(holder.ric);
adap.notifyDataSetChanged();
} else if (item == 2) {
}
Toast.makeText(mContext, items[item],
Toast.LENGTH_SHORT).show();
}
});
AlertDialog alert = builder.create();
alert.show();
return true;
}
});
convertView.setTag(holder);
} else {
holder = (ViewHolder) convertView.getTag();
}
try {
String result = myStocksCtr.getArray().get(position)
.getString("FH_FULLNAME");
holder.stockName.setText(result);
} catch (JSONException e) {
e.printStackTrace();
}
try {
String result = myStocksCtr.getArray().get(position)
.getString("FH_RIC");
holder.ric = result;
} catch (JSONException e) {
e.printStackTrace();
}
// + String.valueOf(position));
try {
String result = myStocksCtr.getArray().get(position)
.getString("FH_PRC");
if (String.valueOf(result.charAt(result.length() - 2)).equals(
".")) {
result += "0";
}
;
holder.stockPrice.setText(result);
} catch (JSONException e) {
e.printStackTrace();
}
holder.position = position;
return convertView;
}
static class ViewHolder {
String ric;
TextView stockName;
TextView stockPrice;
TextView stockPctChange;
TextView stockChange;
int position;
}
#Override
public Filter getFilter() {
return null;
}
#Override
public long getItemId(int position) {
return 0;
}
#Override
public int getCount() {
return myStocksCtr.getArray().size();
}
#Override
public JSONObject getItem(int position) {
return myStocksCtr.getArray().get(position);
}
}
This is some of the things in my stocks controller (where the array is):
public class MyStocksCtr {
private static MyStocksCtr INSTANCE = null;
ArrayList<String> myStocksArray;
JSONCtr jsonCtr;
static Context mContext;
boolean isRunning = false;
ArrayList<JSONObject> myArray;
MyStocksCtr(Context mContext) {
this.mContext = mContext;
jsonCtr = new JSONCtr(mContext);
myStocksArray = new ArrayList<String>();
myArray = new ArrayList<JSONObject>();
}
}
public static MyStocksCtr getInstance(Context context){
mContext = context;
if(INSTANCE == null) {
INSTANCE = new MyStocksCtr(mContext);
}
return INSTANCE;
}
public ArrayList<JSONObject> getArray() {
return myArray;
}
public boolean downloadJson() {
if (!myStocksArray.isEmpty()) {
String myStocksString = "";
for (String s : myStocksArray)
myStocksString += (s + "%2C");
myStocksString = myStocksString.substring(0,
myStocksString.length() - 3);
jsonCtr.getJSON(preStocksUrl + myStocksString + postStocksUrl);
myArray.clear();
myArray.addAll(jsonCtr.getArray());
return true;
} else {
return false;
}
}
public void removeStock(String newStock) {
JSONObject toRemove = null;
for (JSONObject obj : myArray) {
try {
if (obj.getString("FH_RIC").equals(newStock)) {
toRemove = obj;
}
} catch (JSONException e) {
Toast.makeText(mContext, "Kunne ikke fjerne objekt", 1000)
.show();
}
}
if (toRemove != null){
myStocksArray.remove(newStock);
jsonCtr.removeRic(toRemove);
myArray = jsonCtr.getArray();
saveMyStocks();
}
}
}
In my jsonCtr I remove and get the array:
public ArrayList<JSONObject> getArray() {
return rics1;
}
public void removeRic(Object o){
rics1.remove(o);
}
When i have removed an object from the list, the list is updated, so the item is no longer there. But the positions of the views are all messed up, and some of them are outofbounds.
I'm guessing it has something to do with the position in GetView is final, but I'm not sure? And if that is the problem, how do I correct it?
Hmm, I didn't looked at every detail of your code but i think you're missing to call myAdaper.notifyDataSetChanged() after changing your array.
Edit
That*s really tough to look trough because it's a lot of code you post here. So here is what I got. I can't see what's going on in here (on stock remove) but there must be something wrong I think:
jsonCtr.removeRic(toRemove);
myArray = jsonCtr.getArray();
Please don't post the whole code of that too, try to reduce it to the actual problem. I wont check the whole code again...

Categories

Resources