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);)
Related
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();
}
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()).
My app is keep crashinng after the splash actvity. In the error section it is showing NullPointerException. How to resolve this?
as suggest in 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>();
// private MoPubView adView;
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);
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));
}
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() {
// if (getActivity() == null) {
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();
}
//}}
Error:
Fatal Exception: java.lang.NullPointerException: Attempt to invoke virtual method 'void android.widget.TextView.setTypeface(android.graphics.Typeface)' on a null object reference
at com.raccoonfinger.dessert.RecipeListFragment$Custom_Adapter.getView(RecipeListFragment.java:207)
at android.widget.AbsListView.obtainView(AbsListView.java:2344)
at android.widget.ListView.makeAndAddView(ListView.java:1864)
at android.widget.ListView.fillDown(ListView.java:698)
at android.widget.ListView.fillFromTop(ListView.java:759)
at android.widget.ListView.layoutChildren(ListView.java:1659)
at android.widget.AbsListView.onLayout(AbsListView.java:2148)
at android.view.View.layout(View.java:15614)
at android.view.ViewGroup.layout(ViewGroup.java:4968)
at android.widget.RelativeLayout.onLayout(RelativeLayout.java:1076)
at android.view.View.layout(View.java:15614)
at android.view.ViewGroup.layout(ViewGroup.java:4968)
at android.widget.FrameLayout.layoutChildren(FrameLayout.java:573)
at android.widget.FrameLayout.onLayout(FrameLayout.java:508)
at android.view.View.layout(View.java:15614)
at android.view.ViewGroup.layout(ViewGroup.java:4968)
at android.widget.LinearLayout.setChildFrame(LinearLayout.java:1703)
at android.widget.LinearLayout.layoutVertical(LinearLayout.java:1557)
at android.widget.LinearLayout.onLayout(LinearLayout.java:1466)
at android.view.View.layout(View.java:15614)
at android.view.ViewGroup.layout(ViewGroup.java:4968)
at android.support.v4.widget.DrawerLayout.onLayout(DrawerLayout.java:1043)
at android.view.View.layout(View.java:15614)
at android.view.ViewGroup.layout(ViewGroup.java:4968)
at android.widget.RelativeLayout.onLayout(RelativeLayout.java:1076)
at android.view.View.layout(View.java:15614)
at android.view.ViewGroup.layout(ViewGroup.java:4968)
at android.widget.FrameLayout.layoutChildren(FrameLayout.java:573)
at android.widget.FrameLayout.onLayout(FrameLayout.java:508)
at android.view.View.layout(View.java:15614)
at android.view.ViewGroup.layout(ViewGroup.java:4968)
at com.android.internal.widget.ActionBarOverlayLayout.onLayout(ActionBarOverlayLayout.java:494)
at android.view.View.layout(View.java:15614)
at android.view.ViewGroup.layout(ViewGroup.java:4968)
at android.widget.FrameLayout.layoutChildren(FrameLayout.java:573)
at android.widget.FrameLayout.onLayout(FrameLayout.java:508)
at android.view.View.layout(View.java:15614)
at android.view.ViewGroup.layout(ViewGroup.java:4968)
at android.view.ViewRootImpl.performLayout(ViewRootImpl.java:2102)
at android.view.ViewRootImpl.performTraversals(ViewRootImpl.java:1859)
at android.view.ViewRootImpl.doTraversal(ViewRootImpl.java:1077)
at android.view.ViewRootImpl$TraversalRunnable.run(ViewRootImpl.java:5884)
at android.view.Choreographer$CallbackRecord.run(Choreographer.java:767)
at android.view.Choreographer.doCallbacks(Choreographer.java:580)
at android.view.Choreographer.doFrame(Choreographer.java:550)
at android.view.Choreographer$FrameDisplayEventReceiver.run(Choreographer.java:753)
at android.os.Handler.handleCallback(Handler.java:739)
at android.os.Handler.dispatchMessage(Handler.java:95)
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)
Your layout recipelist.xml does not contain TextView with id txttile or txtduration.
I'm sure your problem are because of these
holder.txttile.setTypeface(face2);
holder.txtduration.setTypeface(face1);
You are calling setTypeface on null reference. You have to find what is null is this case holder OR txttile OR txtduration OR face1 OR face2.
Most of the chances is about holder, txttile, txtduration.
in getView() you need add three parameter to the method mInflater.inflate(R.layout.recipelist, null); just like this mInflater.inflate(R.layout.recipelist, parent, false); it will be working.
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;
ImageView fav_unfav;
DisplayImageOptions options;
private ProgressDialog progress;
ImageLoadingListener animateFirstListener = new AnimateFirstDisplayListener();
int counter=8;
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);
new getrecipe().execute();
db = new MyDatabase(getActivity());
position = DataManager.selectedposition;
adapter = new Custom_Adapter(getActivity());
adapter.notifyDataSetChanged();
lvrecipe.setAdapter(adapter);
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();
}
});
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);
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.setBackgroundDrawable(getResources().getDrawable(R.drawable.favourite));
}
else{
holder.fav_unfav.setBackgroundDrawable(getResources().getDrawable(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]);
}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"))
{
}
String rating = recipelist.get(position).getRatings();
if(rating!=null && rating.trim().length() > 0)
{
holder.ratingbar.setRating(Float.valueOf(rating));
}
if(holder.imgrecipe!=null){
if (url != null && url.trim().length() > 0)
{
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;
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 is showing in Crashlytics is:
Fatal Exception: java.lang.NumberFormatException: Invalid float: ""
at java.lang.StringToReal.invalidReal(StringToReal.java:63)
at java.lang.StringToReal.initialParse(StringToReal.java:176)
at java.lang.StringToReal.parseFloat(StringToReal.java:323)
at java.lang.Float.parseFloat(Float.java:306)
at java.lang.Float.valueOf(Float.java:343)
at com.raccoonfinger.glutenfree.RecipeListFragment$Custom_Adapter.getView(Unknown Source)
at android.widget.AbsListView.obtainView(AbsListView.java:2344)
at android.widget.ListView.makeAndAddView(ListView.java:1864)
at android.widget.ListView.fillDown(ListView.java:698)
at android.widget.ListView.fillGap(ListView.java:662)
at android.widget.AbsListView.trackMotionScroll(AbsListView.java:4968)
at android.widget.AbsListView$FlingRunnable.run(AbsListView.java:4512)
at android.view.Choreographer$CallbackRecord.run(Choreographer.java:767)
at android.view.Choreographer.doCallbacks(Choreographer.java:580)
at android.view.Choreographer.doFrame(Choreographer.java:549)
at android.view.Choreographer$FrameDisplayEventReceiver.run(Choreographer.java:753)
at android.os.Handler.handleCallback(Handler.java:739)
at android.os.Handler.dispatchMessage(Handler.java:95)
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)
I think you get error on below Line.
holder.ratingbar.setRating(Float.valueOf(rating));
This means the value inside "rating" is string, please check.
Setting Rating takes float value , in Case ur value is String :
holder.ratingbar.setRating(Float.parseFloat(rating));
use parseFloat()
holder.ratingbar.setRating(Float.parseFloat(rating));
inplace of
holder.ratingbar.setRating(Float.valueOf(rating));
I'm not sure where you are getting the value of rating. But it is attempting to parse that value of string to Float that is throwing your error.
String rating = recipelist.get(position).getRatings();
Also check that the string is not empty.
// if(rating!=null && rating.trim().length() > 0)
if(rating!=null && !rating.isEmpty() && rating.trim().length() > 0)
{
try{
holder.ratingbar.setRating(Float.valueOf(rating));
}
catch (NumberFormatException e){
// TO DO
}
}
Firstly examine the value of rating (log it) and if you are getting a float in there I suggest having a look at this answer:
float f = Float.valueOf("> 12.4N-m/kg.".replaceAll("[^\\d.]+|\\.(?!\\d)", ""));
response of this method should be float String rating = recipelist.get(position).getRatings();or to get it in String you have to convert it into String by using toString();thats why you are getting NumberFormatException
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 ..!!