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()).
Related
I had to move the adapter class for listview to the main activity so that I could access the viewpager and find it through view
But when I began to call this class from a fragment to me began to give an error:
error: an enclosing instance that contains MainActivity.Adapter is required
Because the class is not static
Here's the question, is There any way to work around the error or replace the findViewById () method?
Adapter
public static class Adapter extends BaseAdapter {
Context ctx;
LayoutInflater lInflater;
ArrayList<HelpAdapter> objects;
String url ;
private SharedPreferences settings;
Adapter(Context context, ArrayList<HelpAdapter> products) {
ctx = context;
objects = products;
lInflater = (LayoutInflater) ctx
.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
}
// кол-во элементов
#Override
public int getCount() {
return objects.size();
}
// элемент по позиции
#Override
public Object getItem(int position) {
return objects.get(position);
}
// id по позиции
#Override
public long getItemId(int position) {
return position;
}
// пункт списка
#Override
public View getView(int position, View convertView, ViewGroup parent) {
// используем созданные, но не используемые view
View view = convertView;
if (view == null) {
view = lInflater.inflate(R.layout.item, parent, false);
}
settings = ctx.getSharedPreferences("Settings", ctx.MODE_PRIVATE);
view.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(final View view) {
final TextView textView = view.findViewById(R.id.textView1_2);
AlertDialog.Builder deleted = new AlertDialog.Builder(ctx);
deleted.setMessage("Удалить урок?").setCancelable(true).setPositiveButton("Да", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialogInterface, int i) {
ViewPager viewPager2;
MainActivity.PagerAdapter pagerAdapter1;
viewPager2 = findViewById(R.id.rager);
url = settings.getString("Day","Monday.txt");
StringBuffer stringBuffer1 = new StringBuffer();
StringBuffer stringBuffer = new StringBuffer();
try {
FileInputStream read = ctx.openFileInput(url);
InputStreamReader reader = new InputStreamReader(read);
BufferedReader bufferedReader = new BufferedReader(reader);
String temp_read, temp;
while ((temp_read = bufferedReader.readLine()) != null) {
temp = stringBuffer1.append(temp_read).toString();
stringBuffer1.setLength(0);
if (!temp.equals(textView.getText()))
stringBuffer.append(temp_read).append("\n");
}
bufferedReader.close();
reader.close();
read.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
try {
FileOutputStream write = ctx.openFileOutput(url,ctx.MODE_PRIVATE);
write.write(stringBuffer.toString().getBytes());
write.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
switch (url) {
case "Wednesday.txt" :
classWednesday classWednesday = new classWednesday();
classWednesday.Start();
pagerAdapter1 = new MainActivity.PagerAdapter(new FragmentActivity().getSupportFragmentManager());
viewPager2.setAdapter(pagerAdapter1);
pagerAdapter1.notifyDataSetChanged();
break;
}
}
})
.setNegativeButton("Нет", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialogInterface, int i) {
dialogInterface.cancel();
}
});
AlertDialog alertDialog = deleted.create();
alertDialog.setTitle("Удаление урока");
alertDialog.show();
}
});
HelpAdapter p = getProduct(position);
((TextView) view.findViewById(R.id.textView1)).setText(p.pozic);
((TextView) view.findViewById(R.id.textView1_2)).setText(p.name);
return view;
}
HelpAdapter getProduct(int position) {
return ((HelpAdapter) getItem(position));
}
}
Fragment
import static android.content.Context.MODE_PRIVATE;
public class classWednesday extends Fragment {
private ListView lvMain;
private List<Fragment> list = new ArrayList<>();
ArrayList<HelpAdapter> products = new ArrayList<>();
Integer num = 0;
private SharedPreferences settings;
#Override
public void setUserVisibleHint(boolean isVisibleToUser) {
super.setUserVisibleHint(isVisibleToUser);
if (isVisibleToUser && (getActivity()!=null)) {
SharedPreferences.Editor editor = settings.edit();
editor.putString("Day","Wednesday.txt" );
editor.apply();
}
}
#Nullable
#Override
public View onCreateView(#NonNull LayoutInflater inflater, #Nullable ViewGroup container, #Nullable Bundle savedInstanceState) {
ViewGroup viewGroup = (ViewGroup) inflater.inflate(R.layout.wednesday, container,false);
Start();
lvMain = viewGroup.findViewById(R.id.lvWednesday);
MainActivity.Adapter adapter = new MainActivity.Adapter(getActivity(),products);
lvMain.setAdapter(adapter);
settings = getActivity().getSharedPreferences("Settings", MODE_PRIVATE);
if (settings.contains("Wednesday")) {
ImageButton imageButton = viewGroup.findViewById(R.id.imageButtonWednesday);
if (settings.getBoolean("Wednesday", true))
imageButton.setImageResource(R.drawable.on);
else
imageButton.setImageResource(R.drawable.off);
}
return viewGroup;
}
public void Start() {
products.clear();
try {
FileInputStream read = getActivity().openFileInput("Wednesday.txt");
InputStreamReader reader = new InputStreamReader(read);
BufferedReader bufferedReader = new BufferedReader(reader);
String temp_read;
while ((temp_read = bufferedReader.readLine()) != null) {
num ++;
products.add(new HelpAdapter(num + ")", temp_read));
}
bufferedReader.close();
reader.close();
read.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} catch (NullPointerException ignore) {
}
num = 0;
}
}
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) {
}
};
}
}
I am using on scroll to load more data and show them in list view but my ListView first shows already loaded data then adds the newly added data to ListView
I have used for reference this and many others but unable to solve the issue
Here is my activity class
protected void onCreate(#Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_view_all);
ButterKnife.bind(this);
Users = Users.getCurrentUser(this);
setSupportActionBar(toolbar);
ActionBar actionBar = getSupportActionBar();
if (actionBar != null) {
actionBar.setDisplayHomeAsUpEnabled(true);
}
UIUtility.setStatusColor(this);
Intent intent = getIntent();
try {
entityData = new JSONArray(intent.getStringExtra(EXTRA_DATA));
} catch (JSONException e) {
e.printStackTrace();
}
viewAllCategory = intent.getIntExtra(EXTRA_CATEGORY, 0);
viewAllEntityType = intent.getIntExtra(EXTRA_TYPE, 0);
latitude = intent.getDoubleExtra(EXTRA_LATITUDE, 0);
longitude = intent.getDoubleExtra(EXTRA_LONGITUDE, 0);
setTitle(TITLES[viewAllCategory]);
if (viewAllEntityType == Constants.SMBEntityType.TYPE_USER) {
List<Users> users = Utility.convertJsonArrayToUsers(entityData);
adapterUser = new ViewAllUserAdapter(this, users);
lvEntity.setAdapter(adapterUser);
} else {
List<Book> books = Utility.convertJsonArrayToBook(entityData);
adapterBook = new ViewAllBookAdapter(this, books);
lvEntity.setAdapter(adapterBook);
}
lvEntity.setOnScrollListener(new AbsListView.OnScrollListener() {
#Override
public void onScrollStateChanged(AbsListView view, int scrollState) {
}
#Override
public void onScroll(AbsListView view, int firstVisibleItem, int visibleItemCount, int totalItemCount) {
if (!stopLoadingMore) {
if (totalItemCount == firstVisibleItem + visibleItemCount && !isLoading) {
isLoading = true;
showLoading();
loadMoreData();
}
}
}
});
}
private void loadMoreData() {
String loadMoreUrl = buildLoadMoreUrl();
ShareMyBookHttpClient client = new ShareMyBookHttpClient();
client.get(loadMoreUrl, new AsyncHttpResponseHandler() {
#Override
public void onSuccess(int statusCode, Header[] headers, byte[] responseBody) {
hideLoading();
if (responseBody != null) {
start = start+20;
try {
JSONObject jo = new JSONObject(new String(responseBody));
if (!jo.getBoolean(Constants.JsonKeys.ERROR)) {
JSONArray data = jo.getJSONArray(Constants.JsonKeys.DATA);
if (data.length() == 0) {
stopLoadingMore = true;
return;
}
if (data.length() < 20) {
stopLoadingMore = true;
}
for (int i = 0; i < data.length(); i++) {
entityData.put(data.getJSONObject(i));
}
if (viewAllEntityType == Constants.SMBEntityType.TYPE_USER) {
List<Users> users = Utility.convertJsonArrayToUsers(entityData);
adapterUser.mergeArray(users);
} else {
List<Book> books = Utility.convertJsonArrayToBook(entityData);
adapterBook.mergeArray(books);
}
}
} catch (JSONException e) {
e.printStackTrace();
}
}
}
#Override
public void onFailure(int statusCode, Header[] headers, byte[] responseBody, Throwable error) {
hideLoading();
}
});
}
private String buildLoadMoreUrl() {
switch (viewAllCategory) {
default:
case ViewAllCategory.CATEGORY_USER:
return Constants.createUrlToGetViewAllUsers(Users.getId(), latitude, longitude, Users.getAuthToken(), start, LIMIT);
case ViewAllCategory.CATEGORY_MY_BOOKS:
return Constants.createUrlToGetViewAllMyBooks(Users.getId(), Users.getAuthToken(), start, LIMIT);
}
}
private void showLoading() {
sbLoading = Snackbar.make(coolMain, R.string.view_all_loading, Snackbar.LENGTH_INDEFINITE);
sbLoading.show();
}
private void hideLoading() {
isLoading = false;
if (sbLoading != null) {
sbLoading.dismiss();
}
}
and following is my AdapterClasss
public class ViewAllUserAdapter extends BaseAdapter {
private List<Users> users;
private Context context;
public ViewAllUserAdapter(Context context, List<Users> usersData) {
this.context = context;
users = usersData;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
View row=convertView;
UserVH holder=null;
if(row==null) {
LayoutInflater inflater = LayoutInflater.from(context);
row= inflater.inflate(R.layout.list_item_view_all_user, parent, false);
holder = new UserVH(row, position);
Users user = users.get(position);
UIUtility.setUserProfileUsingPicasso(context, user.getProfileImageUrlSmall(), holder.ivUserImage);
holder.tvName.setText(user.getName());
if (user.getDistance() == -1) {
holder.tvDistance.setText("");
} else {
holder.tvDistance.setText(context.getString(R.string.distance_notation, user.getDistance()));
}
row.setTag(holder);
}
else {
holder=(UserVH)row.getTag();Users user = users.get(position);
UIUtility.setUserProfileUsingPicasso(context, user.getProfileImageUrlSmall(), holder.ivUserImage);
holder.tvName.setText(user.getName());
if (user.getDistance() == -1) {
holder.tvDistance.setText("");
} else {
holder.tvDistance.setText(context.getString(R.string.distance_notation, user.getDistance()));
}
}
return row;
}
#Override
public int getCount() {
return users == null ? 0 : users.size();
}
#Override
public Object getItem(int position) {
return null;
}
#Override
public long getItemId(int position) {
return 0;
}
public void mergeArray(List<Users> additionalUsers) {
Log.e("users", String.valueOf(additionalUsers.size()));
if (additionalUsers != null) {
for (int i = 0; i < additionalUsers.size(); i++) {
if(!(users.contains(additionalUsers.get(i)))) {
users.add(additionalUsers.get(i));
}
}
}
notifyDataSetChanged();
}
public class UserVH extends View {
#Bind(R.id.item_vau_iv_user_image)
ImageView ivUserImage;
#Bind(R.id.item_vau_tv_name)
TextView tvName;
#Bind(R.id.item_vau_tv_distance)
TextView tvDistance;
private int position;
public UserVH(View view, final int position) {
super(context);
this.position = position;
ButterKnife.bind(this, view);
view.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
UIUtility.openUserDetailActivity(context, users.get(position));
}
});
}
}
}
As you already referred this link, Exactly the same issue is happening with you, You should have correct implementation for holder class in getView method.
Update your getView() method as per below :
#Override
public View getView(int position, View convertView, ViewGroup parent) {
View row=convertView;
UserVH holder=null;
if(row==null) {
LayoutInflater inflater = LayoutInflater.from(context);
row= inflater.inflate(R.layout.list_item_view_all_user, parent, false);
holder = new UserVH(row, position);
row.setTag(holder);
}
else {
holder=(UserVH)row.getTag();
}
Users user = users.get(position);
UIUtility.setUserProfileUsingPicasso(context, user.getProfileImageUrlSmall(), holder.ivUserImage);
holder.tvName.setText(user.getName());
if (user.getDistance() == -1) {
holder.tvDistance.setText("");
} else {
holder.tvDistance.setText(context.getString(R.string.distance_notation, user.getDistance()));
}
return row;
}
And update your getItemId and getItem methods as per below :
#Override
public Object getItem(int position) {
return users.get(position);
}
#Override
public long getItemId(int position) {
return position;
}
EDIT : clear the list additional users before adding the new objects
public void mergeArray(List<Users> additionalUsers) {
Log.e("users", String.valueOf(additionalUsers.size()));
if (additionalUsers != null) {
// Following line to be added
additonalusers.clear();
for (int i = 0; i < additionalUsers.size(); i++) {
if(!(users.contains(additionalUsers.get(i)))) {
users.add(additionalUsers.get(i));
}
}
}
notifyDataSetChanged();
}
Your implementation of following methods is incorrect.
#Override
public Object getItem(int position) {
return null;
}
#Override
public long getItemId(int position) {
return 0;
}
Change them as below
#Override
public Object getItem(int position) {
return users.get(position);
}
#Override
public long getItemId(int position) {
return position;
}
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();
}
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 ..!!