On Click Of Tabs(Radio Button) My Memory Getting Double - android

My layout is very complex. I have to make full page scrollable so what i did is - i have a gridView adapter for my gridview items and one custom adapter which has four tabs and then i set my gridview in that custom adapter. Then this whole view is set on my main activity which has a listview so its now scrolling with full page but issue is with memory.
I have 4 tab click events on custom adapter from which i am sending those click events through put extra to main activity where i have four web service and a condition that if 1st tab is selected then 1st web service call will occur and new adapter will set on main activity.
problem: when i click on 1st tab my memory size is 130 MB and on click of 2nd tab it raises to double so and same thing is happen when i click on 3rd tab. I am using lazy loading for loading my images which also maintains my caching, i have tried clear(), notifyDataSetChanged() but doesn't make any change. My memory is increasing on each click of tabs.
Here is my code:
GallaryLoginMainActivity:
public class GallaryLoginMainActivity<T> extends BaseClass {
/**
* Description:Declare the UI components.
*/
private List<ArrayList<HashMap<String, String>>> data = null;
private ListView lstGallaryMain = null;
public ArrayList<HashMap<String, String>> userDataActivity;
public ArrayList<HashMap<String, String>> userDataSecondActivity;
private ProgressDialog loadingDialog = null;
LinkedHashMap<String, String> linkedMap;
ArrayList<Assignment> assignmentArrayList;
private String selectedTab = "popular";
private ImageLoader imageloader;
// public static ArrayAdapter mAdapter;
public ArrayAdapter mAdapter;
/**
* Description:This method use for prepare the request to get the response
* from API
*
*/
public void MediaGetFiles() {
final GallerySaxParserForGetFiles gsp = new GallerySaxParserForGetFiles();
final RestService restService = new RestService();
try {
linkedMap = new LinkedHashMap<String, String>();
gsp.parseXML(restService.getResponse());
// userDataActivity = new ArrayList<HashMap<String, String>>();
userDataActivity = gsp.userData;
System.out.println("RR : userDataActivity from LoginMainAct :" + userDataActivity.size());
System.out.println("RR : from userdataactivty for item:" + userDataActivity.get(0).toString());
data.add(userDataActivity);
} catch (Exception e) {
e.printStackTrace();
}
}
/**
* Description:This method use for prepare the request to get the response
* from API
*
*/
public void MediaGetFilesInfo() {
// new Thread(new Runnable() {
// public void run() {
GallerySaxParserForGetFileInfo gisp = new GallerySaxParserForGetFileInfo();
try {
RestService restService = new RestService();
linkedMap = new LinkedHashMap<String, String>();
System.out.println("From GallaryUserLoginMainActivity1 : " + restService.getResponse());
gisp.parseXML(restService.getResponse());
userDataSecondActivity = new ArrayList<HashMap<String, String>>();
userDataSecondActivity = gisp.userSecondData;
data.add(userDataSecondActivity);
} catch (Exception e) {
e.printStackTrace();
}
// }
// }).start();
}
/**
* Description:This method use for prepare the request to get the response
* from API
*
*/
public void MediaGetShortedFilesByPopuler() {
final GallerySaxParserForGetFiles gsp = new GallerySaxParserForGetFiles();
final RestService restService = new RestService();
try {
linkedMap = new LinkedHashMap<String, String>();
gsp.parseXML(restService.getResponse());
userDataActivity = new ArrayList<HashMap<String, String>>();
userDataActivity = gsp.userData;
data.add(userDataActivity);
data.add(userDataSecondActivity);
// };
// }.execute();
} catch (Exception e) {
e.printStackTrace();
}
}
/**
* Description:This method use for prepare the request to get the response
* from API
*
*/
public void MediaGetShortedFilesByRecent() {
final GallerySaxParserForGetFiles gsp = new GallerySaxParserForGetFiles();
final RestService restService = new RestService();
try {
linkedMap = new LinkedHashMap<String, String>();
gsp.parseXML(restService.getResponse());
userDataActivity = new ArrayList<HashMap<String, String>>();
userDataActivity = gsp.userData;
data.add(userDataActivity);
data.add(userDataSecondActivity);
} catch (Exception e) {
e.printStackTrace();
}
}
/**
* Description:This method use for prepare the request to get the response
* from API
*
*/
public void MediaGetShortedFilesByComment() {
final GallerySaxParserForGetFiles gsp = new GallerySaxParserForGetFiles();
final RestService restService = new RestService();
try {
linkedMap = new LinkedHashMap<String, String>();
gsp.parseXML(restService.getResponse());
userDataActivity = new ArrayList<HashMap<String, String>>();
userDataActivity = gsp.userData;
data.add(userDataActivity);
data.add(userDataSecondActivity);
} catch (Exception e) {
e.printStackTrace();
}
}
/**
* Description:This method use for prepare the request to get the response
* from API
*
*/
public void MediaGetShortedFilesByNearBy() {
final GallerySaxParserForGetFiles gsp = new GallerySaxParserForGetFiles();
final RestService restService = new RestService();
try {
linkedMap = new LinkedHashMap<String, String>();
gsp.parseXML(restService.getResponse());
userDataActivity = new ArrayList<HashMap<String, String>>();
userDataActivity = gsp.userData;
data.add(userDataActivity);
data.add(userDataSecondActivity);
} catch (Exception e) {
e.printStackTrace();
}
}
/** Called when the activity is first created. */
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.gallary_login_main_page_list);
init(GallaryLoginMainActivity.this, R.id.main, getIntent());
data = new ArrayList<ArrayList<HashMap<String, String>>>();
imageloader = new ImageLoader(getApplicationContext());
Intent intent = getIntent();
if (intent.getExtras().getString("SELECTED_TAB") != null) {
selectedTab = intent.getExtras().getString("SELECTED_TAB");
}
/*
*
* This method is used to Show The loading dialog till the data
* loads for main page.
*/
new AsyncTask<Void, Void, Void>() {
protected void onPreExecute() {
loadingDialog = ProgressDialog.show(GallaryLoginMainActivity.this, "", "Loading. Please wait...", true);
}
#Override
protected Void doInBackground(Void... params) {
return null;
};
protected void onPostExecute(Void result) {
if (selectedTab.equalsIgnoreCase("popular")) {
MediaGetShortedFilesByPopuler();
} else if (selectedTab.equalsIgnoreCase("recent")) {
MediaGetShortedFilesByRecent();
} else if (selectedTab.equalsIgnoreCase("commented")) {
MediaGetShortedFilesByComment();
}
if (mAdapter != null) {
mAdapter = null;
mAdapter.clear();
}
if (mAdapter == null) {
lstGallaryMain = (ListView) findViewById(R.id.lstGallaryMain);
mAdapter = new GalleryCustomAdapterForMainPage<T>(GallaryLoginMainActivity.this, data);
// mAdapter.notifyDataSetChanged();
}
lstGallaryMain.setAdapter(mAdapter);
if (loadingDialog != null && loadingDialog.isShowing()) {
loadingDialog.dismiss();
}
};
}.execute();
}
}
#Override
protected void onResume() {
System.gc();
super.onResume();
}
#Override
protected void onPause() {
super.onPause();
System.gc();
}
#Override
public void onLowMemory() {
super.onLowMemory();
imageloader.clearCache();
}
#Override
protected void onDestroy() {
lstGallaryMain.setAdapter(null);
userDataActivity = null;
userDataSecondActivity = null;
System.gc();
super.onDestroy();
}
}
GalleryCustomAdapterForMainPage:
public class GalleryCustomAdapterForMainPage<T> extends ArrayAdapter<T> {
public static int gridviewHeight = 0;
private GridView refGridView;
/**
* Description:Declare the UI components.
*/
List<ArrayList<HashMap<String, String>>> data = null;
public ArrayList<HashMap<String, String>> userDataActivity;
public ArrayList<HashMap<String, String>> userDataSecondActivity;
private ProgressDialog loadingDialog = null;
// AQuery listAQ;
private Activity mContext = null;
private LayoutInflater inflater = null;
Bitmap galleryBitmapHadnling = null;
private PopupWindow mpopup;
LinkedHashMap<String, String> linkedMap;
Holder1 h1;
GalleryMainActivityGridViewAdapter gmaga = null;
private ImageLoader imageloader;
/**
* This method is use to set object that will control the listview
*
* #param activity
* that creates this thing
* #param data
* bind to this listview
*/
// This Class is used to Declare a CustomAdapter that we use to join the
// data set and the ListView
public GalleryCustomAdapterForMainPage(Activity activity, List data) {
super(activity, R.layout.gallery_main_page_content, data);
this.mContext = activity;
// listAQ = new AQuery(mContext);
this.data = data;
this.userDataActivity = this.data.get(0);
System.out.println("userDataActivity is : " + userDataActivity);
this.userDataSecondActivity = this.data.get(1);
// listAQ = new AQuery(mContext);
// Get a new instance of the layout view
inflater = (LayoutInflater) activity.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
imageloader = new ImageLoader(mContext);
}
// Total number of things contained within the adapter
#Override
public int getCount() {
return this.data.size() - 1;
}
// create View for each item referenced by the Adapter
#SuppressWarnings("deprecation")
#Override
public View getView(int position, View convertView, ViewGroup parent) {
if (convertView == null) {
/* create a new view of our layout and inflate it in the row */
// Inflate the layout
convertView = inflater.inflate(R.layout.gallery_main_page_content, null);
// System.gc();
h1 = new Holder1();
// Initialize the UI components
h1.imgView_Gallery_Main_Background = (ImageView) convertView.findViewById(R.id.imgView_Gallery_Main_Background);
h1.txtView_main_img_title = (TextView) convertView.findViewById(R.id.txtView_main_img_title);
Typeface typeForTitile = Typeface.createFromAsset(getContext().getAssets(), "fonts/helvetica_bold_neue.ttf");
h1.txtView_main_img_title.setTypeface(typeForTitile);
h1.texView_featured = (TextView) convertView.findViewById(R.id.texView_featured);
Typeface typeForFeatured = Typeface.createFromAsset(getContext().getAssets(), "fonts/gotham_black_1.ttf");
h1.texView_featured.setTypeface(typeForFeatured);
h1.txtView_assignment_detail = (TextView) convertView.findViewById(R.id.txtView_assignment_detail);
Typeface typeAssignmentDetail = Typeface.createFromAsset(getContext().getAssets(), "fonts/arial_bold_1.ttf");
h1.txtView_assignment_detail.setTypeface(typeAssignmentDetail);
h1.imgView_Main_TumbNail = (ImageView) convertView.findViewById(R.id.imgView_Main_TumbNail);
h1.txtView_gallery_main_person_name = (TextView) convertView.findViewById(R.id.txtView_gallery_main_person_name);
Typeface txtViewPersonName = Typeface.createFromAsset(getContext().getAssets(), "fonts/arial_bold.ttf");
h1.txtView_gallery_main_person_name.setTypeface(txtViewPersonName);
h1.txtView_gallery_main_views = (TextView) convertView.findViewById(R.id.txtView_gallery_main_views);
Typeface txtViewViews = Typeface.createFromAsset(getContext().getAssets(), "fonts/arial_bold.ttf");
h1.txtView_gallery_main_views.setTypeface(txtViewViews);
h1.texView_gallery_main_comment = (TextView) convertView.findViewById(R.id.texView_gallery_main_comment);
Typeface txtViewComments = Typeface.createFromAsset(getContext().getAssets(), "fonts/arial_bold.ttf");
h1.texView_gallery_main_comment.setTypeface(txtViewComments);
h1.texView_gallery_main_favorite = (TextView) convertView.findViewById(R.id.texView_gallery_main_favorite);
Typeface txtViewFavorite = Typeface.createFromAsset(getContext().getAssets(), "fonts/arial_bold.ttf");
h1.texView_gallery_main_favorite.setTypeface(txtViewFavorite);
h1.btn_Gallery_Main_ShowMe = (RadioButton) convertView.findViewById(R.id.btn_Gallery_Main_ShowMe);
h1.btn_Gallery_Tab_Popular = (RadioButton) convertView.findViewById(R.id.btn_Gallery_Tab_Popular);
Typeface TabPopular = Typeface.createFromAsset(getContext().getAssets(), "fonts/helvetica_ce_regular.ttf");
h1.btn_Gallery_Tab_Popular.setTypeface(TabPopular);
h1.btn_Gallery_Tab_Popular.setChecked(true);
h1.btn_Gallery_Tab_recent = (RadioButton) convertView.findViewById(R.id.btn_Gallery_Tab_recent);
Typeface TabRecent = Typeface.createFromAsset(getContext().getAssets(), "fonts/helvetica_ce_regular.ttf");
h1.texView_gallery_main_favorite.setTypeface(TabRecent);
h1.btn_Gallery_Tab_Commented = (RadioButton) convertView.findViewById(R.id.btn_Gallery_Tab_Commented);
Typeface TabCommented = Typeface.createFromAsset(getContext().getAssets(), "fonts/helvetica_ce_regular.ttf");
h1.texView_gallery_main_favorite.setTypeface(TabCommented);
h1.btn_Gallery_Tab_Nearby = (RadioButton) convertView.findViewById(R.id.btn_Gallery_Tab_Nearby);
Typeface TabNearby = Typeface.createFromAsset(getContext().getAssets(), "fonts/helvetica_ce_regular.ttf");
h1.texView_gallery_main_favorite.setTypeface(TabNearby);
h1.imgView_ForPlayVideo = (ImageView) convertView.findViewById(R.id.imgView_ForPlayVideo);
if (userDataActivity.get(position).get("filetype").toString().endsWith("1")) {
h1.imgView_ForPlayVideo.setVisibility(View.GONE);
} else {
h1.imgView_ForPlayVideo.setVisibility(View.VISIBLE);
} // set the content in grid view of gallery main page
h1.gridview_Gallery = (GridView) convertView.findViewById(R.id.gridview_Gallery);
int gridHeight = (int) ((userDataActivity.size() / 3) * 140 * 1.80);
System.out.println("gridHeigh is : " + gridHeight);
if (h1.btn_Gallery_Tab_Popular != null) {
h1.txtView_gallery_main_person_name.setText(" " + userDataActivity.get(position).get("user_name"));
h1.txtView_main_img_title.setText(userDataActivity.get(position).get("title"));
h1.txtView_gallery_main_views.setText(" | " + userDataActivity.get(position).get("hits") + " views");
h1.texView_gallery_main_comment.setText(" | " + userDataActivity.get(position).get("commentcount") + " ");
h1.texView_gallery_main_favorite.setText(" | " + userDataActivity.get(position).get("votecount") + " ");
imageloader.DisplayImage(userDataActivity.get(position).get("thumbUrl") + "/12", h1.imgView_Gallery_Main_Background);
// h1.imgView_Main_TumbNail.setImageBitmap(getBitmap(userDataActivity.get(position).get("thumbUrl")
// + "/12"));
if (userDataActivity.get(position).get("publicUrl") != null) {
imageloader.DisplayImage(userDataActivity.get(position).get("publicUrl") + "/14", h1.imgView_Gallery_Main_Background);
} else {
h1.imgView_Gallery_Main_Background.setBackgroundResource(R.drawable.loading);
}
}
userDataActivity.remove(0);
if (h1.gridview_Gallery != null) {
// clearAdapter();
// setting the adapter
// if (gmaga == null) {
gmaga = new GalleryMainActivityGridViewAdapter(mContext, userDataActivity);
// }
h1.gridview_Gallery.setAdapter(gmaga);
// Total number of things contained within the adapter
int gridHeight1 = (int) ((h1.gridview_Gallery.getAdapter().getCount() / 3) * 120 * 1.80);
h1.gridview_Gallery.setLayoutParams(new LinearLayout.LayoutParams(android.view.ViewGroup.LayoutParams.FILL_PARENT, gridHeight1));
h1.gridview_Gallery.setSelector(new ColorDrawable(color.transparent));
h1.gridview_Gallery.setOnItemClickListener(new OnItemClickListener() {
public void onItemClick(AdapterView<?> arg0, View arg1, int position, long arg3) {
Intent intent = new Intent(mContext, GalleryDetailPageActivity.class);
System.out.println("pos:" + userDataActivity.get(position).get("id"));
// This will send the items via intent to Gallery detail
// page to display data on that page.
intent.putExtra("tabId", R.id.tab_b01);
intent.putExtra("tabBackgroundId", R.drawable.tab_b01_on);
mContext.startActivity(intent);
}
});
}
if (h1.btn_Gallery_Tab_Popular != null) {
h1.btn_Gallery_Tab_Popular.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
Intent intent = new Intent(mContext, GallaryLoginMainActivity.class);
intent.putExtra("SELECTED_TAB", "popular");
intent.putExtra("tabId", R.id.tab_b01);
intent.putExtra("tabBackgroundId", R.drawable.tab_b01_on);
mContext.startActivity(intent);
mContext.finish();
// }
}
});
}
if (h1.btn_Gallery_Tab_recent != null) {
h1.btn_Gallery_Tab_recent.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent(mContext, GallaryLoginMainActivity.class);
intent.putExtra("SELECTED_TAB", "recent");
intent.putExtra("tabId", R.id.tab_b01);
intent.putExtra("tabBackgroundId", R.drawable.tab_b01_on);
mContext.startActivity(intent);
mContext.finish();
// }
}
});
}
if (h1.btn_Gallery_Tab_Commented != null) {
h1.btn_Gallery_Tab_Commented.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent(mContext, GallaryLoginMainActivity.class);
intent.putExtra("SELECTED_TAB", "commented");
intent.putExtra("tabId", R.id.tab_b01);
intent.putExtra("tabBackgroundId", R.drawable.tab_b01_on);
mContext.startActivity(intent);
mContext.finish();
// }
}
});
}
convertView.setTag(h1);
}
return convertView;
}
private class Holder1 {
ImageView imgView_Gallery_Main_Background;
TextView txtView_main_img_title;
TextView texView_featured;
RadioButton btn_Gallery_Tab_Popular;
RadioButton btn_Gallery_Tab_recent;
RadioButton btn_Gallery_Tab_Commented;
RadioButton btn_Gallery_Tab_Nearby;
ImageView imgView_Main_TumbNail;
TextView txtView_assignment_detail;
TextView txtView_assignment_name;
TextView txtView_gallery_main_person_name;
TextView txtView_gallery_main_views;
TextView texView_gallery_main_comment;
TextView texView_gallery_main_favorite;
RadioButton btn_Gallery_Main_ShowMe;
GridView gridview_Gallery;
ImageView imgView_ForPlayVideo;
}
}
GalleryMainActivityGridViewAdapter:
public class GalleryMainActivityGridViewAdapter extends BaseAdapter {
// AQuery listAQ;
private Context mContext;
int layoutResourceId;
ArrayList<HashMap<String, String>> dataArray;
ArrayList<Boolean> selected;
private GallerySmartLazyLoader lazyloader;
private ImageLoader imageloder;
public static String dataExtension = " Views";
public GalleryMainActivityGridViewAdapter(Context context, ArrayList<HashMap<String, String>> resultArray) {
this.mContext = context;
// this.layoutResourceId = layoutId;
this.dataArray = resultArray;
// listAQ = new AQuery(mContext);
lazyloader = new GallerySmartLazyLoader(mContext);
imageloder = new ImageLoader(mContext.getApplicationContext());
// aa = new ArrayAdapter<Photo>(mContext, layoutResourceId);
}
public int getCount() {
return dataArray.size();
}
public void clear() {
dataArray.clear();
}
public Object getItem(int position) {
return position;
}
public long getItemId(int position) {
return position;
}
// BitmapFactory.Options options = null;
// Bitmap cachedImage;
#SuppressWarnings("deprecation")
public View getView(int position, View convertView, ViewGroup parent) {
String url = null;
GalleryHolder holder = null;
if (convertView == null) {
convertView = ((LayoutInflater) mContext.getSystemService(Context.LAYOUT_INFLATER_SERVICE)).inflate(R.layout.gallery_main_page_grid_item, parent, false);
convertView.setTag(holder);
} else {
holder = (GalleryHolder) convertView.getTag();
}
holder = new GalleryHolder();
try {
String thumbnail = dataArray.get(position).get("thumbUrl") + "/11";
holder.imgView_Grid_Thumbnail_Gallery = (ImageView) convertView.findViewById(R.id.imgView_Grid_Thumbnail_Gallery);
if (holder.imgView_Grid_Thumbnail_Gallery != null) {
}
} catch (Exception e) {
e.printStackTrace();
}
holder.txtView_Grid_Name_Gallery = (TextView) convertView.findViewById(R.id.txtView_Grid_Name_Gallery);
Typeface TabGridname = Typeface.createFromAsset(convertView.getContext().getAssets(), "fonts/arial_bold.ttf");
holder.txtView_Grid_Name_Gallery.setTypeface(TabGridname);
if (holder.txtView_Grid_Name_Gallery != null) {
// holder.txtView_Grid_Name_Gallery.getId()).text(dataArray.get(position).get("user_name"));
holder.txtView_Grid_Name_Gallery.setText(dataArray.get(position).get("user_name"));
Typeface txtViewForName = Typeface.createFromAsset(convertView.getContext().getAssets(), "fonts/arial_bold.ttf");
holder.txtView_Grid_Name_Gallery.setTypeface(txtViewForName);
}
ImageView v = holder.imgView_GridItem_Gallery = (ImageView) convertView.findViewById(R.id.imgView_GridItem_Gallery);
if (holder.imgView_GridItem_Gallery != null) {
String publicUrl = dataArray.get(position).get("publicUrl") + "/14";
imageloder.DisplayImage(publicUrl, holder.imgView_GridItem_Gallery);
}
holder.txtView_Grid_Views_Gallery = (TextView) convertView.findViewById(R.id.txtView_Grid_Views_Gallery);
Typeface TabGriddetail = Typeface.createFromAsset(convertView.getContext().getAssets(), "fonts/helvetica_ce_regular.ttf");
holder.txtView_Grid_Name_Gallery.setTypeface(TabGriddetail);
if (holder.txtView_Grid_Views_Gallery != null) {
if (isPopuler) {
holder.txtView_Grid_Views_Gallery.setText(dataArray.get(position).get("hits") + dataExtension);
}
else if (isUpload) {
GalleryMainActivityGridViewAdapter.dataExtension = dataArray.get(position).get("upload");
holder.txtView_Grid_Views_Gallery.setText(dataArray.get(position).get("upload"));
}
else if (isComments) {
holder.txtView_Grid_Views_Gallery.setText(dataArray.get(position).get("commentcount") + dataExtension);
}
// else if (isNearby) {
// aq.id(holder.txtView_Grid_Views_Gallery.getId()).text(dataArray.get(position).get("commentcount")
// + dataExtension);
// }
Typeface txtViewForViews = Typeface.createFromAsset(convertView.getContext().getAssets(), "fonts/arial_bold.ttf");
holder.txtView_Grid_Views_Gallery.setTypeface(txtViewForViews);
}
holder.imgView_Grid_PlayVideo = (ImageView) convertView.findViewById(R.id.imgView_Grid_PlayVideo);
if (holder.imgView_Grid_PlayVideo != null) {
if (dataArray.get(position).get("filetype").toString().equals("1")) {
holder.imgView_Grid_PlayVideo.setVisibility(View.GONE);
} else {
holder.imgView_Grid_PlayVideo.setVisibility(View.VISIBLE);
}
}
return convertView;
}
class GalleryHolder {
ImageView imgView_Grid_PlayVideo;
ImageView imgView_Grid_Thumbnail_Gallery;
TextView txtView_Grid_Views_Gallery;
TextView txtView_Grid_Name_Gallery;
ImageView imgView_GridItem_Gallery;
}
}
pic

The description you showed is indicating a possible memory leak. Check my answer for this question. My guess is that you should use the Application context instead of the Activity context in your code. Use the video in the answer mentioned to know how to identify the leak.

Related

Remove an item from view inside an adapter

I am trying to remove an item from view when its flag become 4. I tried mObjects.remove(position) and then notifyDataSetChanged(). but it didn't worked.we tried all the following
if (getItem(position).getFlag().trim().equalsIgnoreCase("4")) {
remove(position);
adapter.notifyDataSetChanged();
matcheslistview.setAdapter(adapter);
also this one
// mObjects.remove(position)
// notifyDataSetChanged();
and this one
// mObjects.remove(position);
//remove(position);
//mainObjects.remove(position);
//notifyDataSetChanged();
and this one
// Object toRemove = adapter.getItem(position);
// mObjects.remove(toRemove);
// mObjects.clear();
and all the time we got java.lang.IndexOutOfBoundsException: Invalid index 1, size is 0.Here is the complete adapter class
private class MatchedDataAdapter extends BaseAdapter implements Filterable {
private AQuery aQuery;
private Activity mActivity;
private LayoutInflater mInflater;
private SessionManager sessionManager;
private int uflag;
MyFilter mfilter;
DatabaseHandler db;
ArrayList<LikeMatcheddataForListview> mObjects;
ArrayList<LikeMatcheddataForListview> mainObjects;
Context context;
public MatchedDataAdapter(Activity context,
ArrayList<LikeMatcheddataForListview> objects,
int imageHeigthAndWidth[]) {
this.mObjects = objects;
mainObjects = objects;
//Log.e("size", Integer.toString(mObjects.size()));
this.mActivity = context;
try {
mInflater = (LayoutInflater) mActivity
.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
}
catch (Exception e)
{
e.printStackTrace();
}
aQuery = new AQuery(context);
db = new DatabaseHandler(context);
}
#Override
public int getCount() {
return mObjects.size();
}
#Override
public LikeMatcheddataForListview getItem(int position) {
return mObjects.get(position);
}
#Override
public long getItemId(int i) {
return i;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
ViewHolder holder;
if (convertView == null) {
holder = new ViewHolder();
convertView = mInflater.inflate(R.layout.matchedlistviewitem,
null);
holder.imageview = (ImageView) convertView
.findViewById(R.id.userimage);
holder.textview = (TextView) convertView
.findViewById(R.id.userName);
holder.lastMasage = (TextView) convertView
.findViewById(R.id.lastmessage);
holder.imgStatus = (ImageView) convertView
.findViewById(R.id.imgStatus);
convertView.setTag(holder);
} else {
holder = (ViewHolder) convertView.getTag();
}
holder.textview.setText(getItem(position).getUserName());
if (getItem(position).getFlag().trim().equalsIgnoreCase("4")) {
mObjects.remove(position);
adapter.notifyDataSetChanged();
matcheslistview.setAdapter(adapter);
we want to remove Item with flag 4,we are reading this flag with a service from db and onrecive we call class DisplayContentTask as below
class GetLikeMatchedReceiver extends BroadcastReceiver {
#Override
public void onReceive(Context context, Intent intent) {
new DisplayContentTask(intent).execute();
}
}
how we can get Item position in order to remove the Item with flag 4...or My be another approach to remove Item with flag 4 we don't know but appreciate your help on this
class DisplayContentTask extends AsyncTask<Void, Void, Void> {
Intent intent;
private Ultilities mUltilities = new Ultilities();
private List<NameValuePair> getuserparameter;
private String likedmatchedata, Unmatchedata;
int match1;
private LikedMatcheData matcheData;
private ArrayList<com.appdupe.flamer.pojo.Likes> likesList;
private LikeMatcheddataForListview matcheddataForListview;
DatabaseHandler mDatabaseHandler = new DatabaseHandler(getActivity());
private boolean isResponseSuccess = true;
ArrayList<LikeMatcheddataForListview> tempArray = new ArrayList<LikeMatcheddataForListview>();
#Override
protected void onPreExecute() {
super.onPreExecute();
AppLog.Log(TAG, "BackgroundTaskForFindLikeMatched onPreExecute ");
}
DisplayContentTask(Intent intent) {
this.intent = intent;
}
#Override
protected Void doInBackground(Void... voids) {
try {
File appDirectory = mUltilities
.createAppDirectoy(getResources().getString(
R.string.appdirectory));
AppLog.Log(TAG,
"BackgroundTaskForFindLikeMatched doInBackground appDirectory "
+ appDirectory);
File _picDir = new File(appDirectory, getResources().getString(
R.string.imagedirematchuserdirectory));
AppLog.Log(TAG,
"BackgroundTaskForFindLikeMatched doInBackground ");
// getuserparameter = mUltilities.getUserLikedParameter(params);
likedmatchedata = intent.getStringExtra("GET_MATCHED_RESPONSE");
// Unmatchedata = intent.getStringExtra("GET_UNMATCHED_RESPONSE");//hadi
AppLog.Log(TAG,
"BackgroundTaskForFindLikeMatched doInBackground likedmatchedata "
+ likedmatchedata);
Gson gson = new Gson();
matcheData = gson.fromJson(likedmatchedata,
LikedMatcheData.class);
AppLog.Log(TAG,
"BackgroundTaskForFindLikeMatched doInBackground matcheData "
+ matcheData);
// "errNum": "51",
// "errFlag": "0",
// "errMsg": "Matches found!",
if (matcheData.getErrFlag() == 0) {
likesList = matcheData.getLikes();
AppLog.Log(TAG,
"BackgroundTaskForFindLikeMatched doInBackground likesList "
+ likesList);
if (tempArray != null) {
tempArray.clear();
}
AppLog.Log(TAG,
"BackgroundTaskForFindLikeMatched doInBackground likesList sized "
+ likesList.size());
Log.v("Matches", "" + likesList.size());
match1 = likesList.size();
for (int i = 0; i < likesList.size(); i++) {
Log.d("likelist", likesList.toString());
matcheddataForListview = new LikeMatcheddataForListview();
String userName = likesList.get(i).getfName();
String facebookid = likesList.get(i).getFbId();
// Log.i(TAG, "Background facebookid......"+facebookid);
String picturl = likesList.get(i).getpPic();
int falg = likesList.get(i).getFlag();
// if (likesList.get(i).getFlag()==4) {
// likesList.remove(getId());
// }
Log.i("komak10",""+likesList.get(i).getFlag());
String latd = likesList.get(i).getLadt();
matcheddataForListview.setFacebookid(facebookid);
matcheddataForListview.setUserName(userName);
matcheddataForListview.setImageUrl(picturl);
matcheddataForListview.setFlag("" + falg);
matcheddataForListview.setladt(latd);
// matcheddataForListview.setFilePath(filePath);
File imageFile = mUltilities.createFileInSideDirectory(
_picDir, userName + facebookid + ".jpg");
// logDebug("BackGroundTaskForUserProfile doInBackground imageFile is profile "+imageFile.isFile());
Utility.addBitmapToSdCardFromURL(likesList.get(i)
.getpPic().replaceAll(" ", "%20"), imageFile);
matcheddataForListview.setFilePath(imageFile
.getAbsolutePath());
if (!preferences.getString(Constant.FACEBOOK_ID, "")
.equals(facebookid)) {
tempArray.add(matcheddataForListview);
}
}
DatabaseHandler mDatabaseHandler = new DatabaseHandler(
getActivity());
// SessionManager mSessionManager = new SessionManager(
// MainActivity.this);
String userFacebookid = preferences.getString(
Constant.FACEBOOK_ID, "");
//
boolean isdataiserted = mDatabaseHandler.insertMatchList(
tempArray, userFacebookid);
} else if (matcheData.getErrFlag() == 1) {
if(tempArray!=null)
{
tempArray.clear();
}
} else {
// do nothing
}
} catch (Exception e) {
AppLog.handleException(
"BackgroundTaskForFindLikeMatched doInBackground Exception ",
e);
// some thing wrong happend
isResponseSuccess = false;
}
return null;
}
Don't remove the object in getview, if you have to filter it, filter it before sending out to adapter. May be possible that while creating the child view the 1st cell has tag "4" now the view didn't create(since return was not called) but you are trying to remove its position, so it will definitely give you IndexOutOfBoundsException.
My best solution would be, set the adapter with
new ArrayList<LikeMatcheddataForListview>()
whenever you start the screen. Once your AsyncTask completes filter out the child with tags "4"(better filter it out in the asynctask only, less task in ui thread) then refresh the adapter, like
public void refresh(ArrayList<LikeMatcheddataForListview>() arrObjects){
objects = arrObjects;
notifyDataSetChanged();
}
Check it out, it should do the trick
Please try following
Your code
if (getItem(position).getFlag().trim().equalsIgnoreCase("4")) {
mObjects.remove(position);
adapter.notifyDataSetChanged();
matcheslistview.setAdapter(adapter);
}
TO
do not set adapter again to list view
if (getItem(position).getFlag().trim().equalsIgnoreCase("4")) {
mObjects.remove(position);
notifyDataSetChanged();
}
This may not be correct approach to remove the item form listview.
Whenever your adapter data is getting changed then just check if that flag matches your string i.e. "4" in each item and remove the respective item from the list and just call notifyItemRemoved with position insted of notifyDataSetChanged

Android Listview Scroll position

I have a ListView and a list view adapter. The adapter populates the ListView from a List. The list view has a onScrollListener. The problem I have is when on scroll new data are loaded to the view but the scroll bar jumps to the top of the view.
What I want is to keep the scroll position where it was!
Any help?
Thanks
List View class:
private class GetItems extends AsyncTask<Void, Void, Void>
{
#Override
protected void onPreExecute() {
super.onPreExecute();
// Create a progressdialog
mProgressDialog = new ProgressDialog(AppList.this);
// Set progressdialog title
mProgressDialog.setTitle("Loading more");
mProgressDialog.setMessage("loading);
mProgressDialog.setIndeterminate(false);
// Show progressdialog
mProgressDialog.show();
}
#Override
protected Void doInBackground(Void... params)
{
applicationList = new ArrayList();
try
{
GetDataAppList getDataAppList = new GetDataAppList();
JSONArray jsonData = getDataAppList.getJSONData(webfileName, limit, offset);
for (int i = 0; i <= jsonData.length() - 2; i++)
{
JSONObject c = jsonData.getJSONObject(i);
id = c.getString("id");
name = c.getString("name");
logo = c.getString("logo");
developer = c.getString("developer");
rate = c.getInt("rates");
category = c.getInt("category");
fileName = c.getString("filename");
path = c.getString("path");
appSize = c.getDouble("size");
if(category == 1001)
{
String gCat = c.getString("game_category");
applicationList.add(new ApplicationPojo(id,name,logo,developer,appSize,category,fileName,path,gCat));
}
else
{
applicationList.add(new ApplicationPojo(id,name,logo,developer,appSize,category,fileName,path));
}
}
JSONObject sizeObj = jsonData.getJSONObject(jsonData.length() - 1);
size = sizeObj.getInt("size");
}
catch (Exception ex)
{
Log.d("Thread:", ex.toString());
}
return null;
}
#Override
protected void onPostExecute(Void result)
{
// Locate the ListView in listview.xml
listview = (ListView) findViewById(R.id.listView);
// Pass the results into ListViewAdapter.java
adapter = new ListViewAdapter(AppList.this, applicationList,listview);
// Binds the Adapter to the ListView
listview.setAdapter(adapter);
// Close the progressdialog
mProgressDialog.dismiss();
// Create an OnScrollListener
listview.setOnScrollListener(new OnScrollListener() {
#Override
public void onScrollStateChanged(AbsListView view, int scrollState) {
int threshold = 1;
int count = listview.getCount();
if (scrollState == SCROLL_STATE_IDLE) {
if (listview.getLastVisiblePosition() >= count - threshold) {
if (size >= offset)
{
new LoadMoreDataTask().execute();
offset = offset + 15;
}
else
{
Toast.makeText(getApplicationContext(), "ختم لست!", Toast.LENGTH_LONG).show();
}
}
}
}
#Override
public void onScroll(AbsListView view, int firstVisibleItem, int visibleItemCount, int totalItemCount) {
// TODO Auto-generated method stub
}
});
RatingBar bar = (RatingBar) findViewById(R.id.ratingBarShow);
}
}
private class LoadMoreDataTask extends AsyncTask<Void, Void, Void> {
#Override
protected void onPreExecute() {
super.onPreExecute();
mProgressDialog = new ProgressDialog(AppList.this);
mProgressDialog.setTitle("Loading more");
mProgressDialog.setMessage("loading);
mProgressDialog.setIndeterminate(false);
mProgressDialog.show();
}
#Override
protected Void doInBackground(Void... params)
{
try
{
GetDataAppList getDataAppList = new GetDataAppList();
JSONArray jsonData = getDataAppList.getJSONData(webfileName, limit, offset);
for (int i = 0; i <= jsonData.length(); i++) {
JSONObject c = jsonData.getJSONObject(i);
id = c.getString("id");
name = c.getString("name");
logo = c.getString("logo");
developer = c.getString("developer");
rate = c.getInt("rates");
category = c.getInt("category");
fileName = c.getString("filename");
path = c.getString("path");
appSize = c.getDouble("size");
if(category == 1001)
{
String gCat = c.getString("game_category");
applicationList.add(new ApplicationPojo(id,name,logo,developer,appSize,category,fileName,path,gCat));
}
else
{
applicationList.add(new ApplicationPojo(id,name,logo,developer,appSize,category,fileName,path));
}
}
}
catch (Exception ex)
{
}
return null;
}
#Override
protected void onPostExecute(Void result)
{
int position = listview.getLastVisiblePosition();
adapter = new ListViewAdapter(AppList.this, applicationList,listview);
listview.setAdapter(adapter);
listview.setSelectionFromTop(position, 0);
mProgressDialog.dismiss();
}
}
The Adpater class:
public ListViewAdapter(Activity activity, ArrayList<ApplicationPojo> applicationList, ListView listView)
{
this.activity = activity;
this.applicationList = applicationList;
this.inflater = LayoutInflater.from(activity);
downloader = new ApkFileDownloader(activity);
this.listView = listView;
}
#Override
public int getCount() {
return applicationList.size();
}
#Override
public ApplicationPojo getItem(int position) {
return applicationList.get(position);
}
#Override
public long getItemId(int position) {
return position;
}
public View getView(final int position, View view, ViewGroup parent)
{
if (view == null)
{
holder = new ViewHolder();
view = inflater.inflate(R.layout.singleapp, null);
holder.openInstalledAppBtn = (ImageView) view.findViewById(R.id.openInstalledApp);
holder.downloadBtn = (ImageView) view.findViewById(R.id.updateApp);
holder.progressBar = (ProgressBar)view.findViewById(R.id.updateProgress);
holder.cancelBtn = (ImageView) view.findViewById(R.id.cancel);
holder.appName = (TextView) view.findViewById(R.id.appName);
holder.developer = (TextView) view.findViewById(R.id.developer);
holder.size = (TextView) view.findViewById(R.id.size);
holder.appCat = (TextView) view.findViewById((R.id.appCat));
holder.installBtn = (ImageView) view.findViewById(R.id.install);
holder.catlogo = (ImageView) view.findViewById(R.id.catlogo);
view.setTag(holder);
}
else
{
holder = (ViewHolder) view.getTag();
}
try
{
final View finalView = view;
holder.logo = (ImageView) finalView.findViewById(R.id.appLogo);
logoName = applicationList.get(position).getLogo();
Picasso.with(activity)
.load(IPClass.SERVERIP + logoName)
.into(holder.logo);
// holder.logo.setOnClickListener(new View.OnClickListener() {
// #Override
// public void onClick(View arg0) {
//
// }
// });
listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
String appid = applicationList.get(position).getId();
int category = applicationList.get(position).getCategory();
Intent rec1Intent = new Intent(activity, AppView.class);
activity.startActivity(rec1Intent);
AppView appView = new AppView();
appView.setParameters(appid, category);
AppList.adapter.notifyDataSetChanged();
}
});
final String id = applicationList.get(position).getId();
final String path = applicationList.get(position).getPath();
final String fileName = applicationList.get(position).getFileName();
final String name = applicationList.get(position).getName();
final String developer = applicationList.get(position).getDeveloper();
final double size = applicationList.get(position).getSize();
final String logo = applicationList.get(position).getLogo();
final int category = applicationList.get(position).getCategory();
final String appName = applicationList.get(position).getFileName();
String checkAppInstalled = appName.substring(0,appName.length() - 4);
//------------CHECK IF APPLICATION IS INSTALLED ----------------------------------------
if(appInstalled(checkAppInstalled))
{
holder.downloadBtn.setVisibility(View.GONE);
holder.cancelBtn.setVisibility(View.GONE);
holder.progressBar.setVisibility(View.GONE);
holder.installBtn.setVisibility(View.GONE);
holder.openInstalledAppBtn.setVisibility(View.VISIBLE);
holder.openInstalledAppBtn.setOnClickListener(new View.OnClickListener()
{
#Override
public void onClick(View v) {
String fileName = (applicationList.get(position).getFileName());
String appToOpen = fileName.substring(0,fileName.length() - 4);
Context ctx = activity.getApplicationContext();
Intent mIntent = ctx.getPackageManager().getLaunchIntentForPackage(appToOpen);
String mainActivity = mIntent.getComponent().getClassName();
Intent intent = new Intent("android.intent.category.LAUNCHER");
intent.setClassName(appToOpen, mainActivity);
activity.startActivity(intent);
}
});
}
//------------- IF APPLICATION IS NOT ALREADY INSTALLED --------------------------------
else
{
//------------------------ CHECK IF APK EXISTS -------------------------------------
String filePath = Environment.getExternalStorageDirectory().toString();
File file = new File(filePath + "/appsaraai/" + fileName);
if(file.exists())
{
holder.downloadBtn.setVisibility(View.GONE);
holder.cancelBtn.setVisibility(View.GONE);
holder.openInstalledAppBtn.setVisibility(View.GONE);
holder.progressBar.setVisibility(View.GONE);
holder.installBtn.setVisibility(View.VISIBLE);
holder.installBtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent(Intent.ACTION_VIEW);
intent.setDataAndType(Uri.fromFile(new File(Environment.getExternalStorageDirectory() + "/appsaraai/" + fileName)), "application/vnd.android.package-archive");
activity.startActivity(intent);
for (int i = 0; i < DownloadLists.list.size(); i++) {
if (DownloadLists.list.get(i).getName().equals(name)) {
DownloadLists.list.remove(i);
}
}
}
});
AppList.adapter.notifyDataSetChanged();
}
//------------------ IF APK DOES NOT EXIST -----------------------------------------
else
{
//-----CHECK IF DOWNLOAD IS IN PROGRESS ----------------------------------------
if (ApkFileDownloader.applicationList.containsKey(name))
{
holder.downloadBtn.setVisibility(View.GONE);
holder.installBtn.setVisibility(View.GONE);
holder.openInstalledAppBtn.setVisibility(View.GONE);
new ApkFileDownloader(activity).getDownloadStatus(holder.progressBar, name, holder.installBtn, holder.cancelBtn);
holder.progressBar.setVisibility(View.VISIBLE);
holder.cancelBtn.setVisibility(View.VISIBLE);
holder.cancelBtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
downloader.cancelDownload(name);
holder.cancelBtn.setVisibility(View.GONE);
holder.downloadBtn.setVisibility(View.VISIBLE);
DownloadLists dlist = new DownloadLists(activity);
dlist.deleteData(name);
try {
AppList.adapter.notifyDataSetChanged();
} catch (Exception ex) {
System.out.println(ex);
}
try
{
SearchResult.adapter.notifyDataSetChanged();
}
catch (Exception ex)
{
System.out.println(ex);
}
}
});
}
//-------------- IF DOWNLOAD IS NOT IN PROGRESS START NEW DOWNLOAD -------------
else
{
holder.progressBar.setVisibility(View.GONE);
holder.cancelBtn.setVisibility(View.GONE);
holder.installBtn.setVisibility(View.GONE);
holder.openInstalledAppBtn.setVisibility(View.GONE);
holder.downloadBtn.setVisibility(view.VISIBLE);
holder.downloadBtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View arg0) {
holder.downloadBtn.setVisibility(View.GONE);
holder.cancelBtn.setVisibility(View.VISIBLE);
holder.cancelBtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
downloader.cancelDownload(name);
holder.cancelBtn.setVisibility(View.GONE);
holder.downloadBtn.setVisibility(View.VISIBLE);
try {
AppList.adapter.notifyDataSetChanged();
} catch (Exception ex) {
System.out.println(ex);
}
try {
SearchResult.adapter.notifyDataSetChanged();
} catch (Exception ex) {
System.out.println(ex);
}
}
});
new Thread(new Runnable() {
#Override
public void run() {
try {
Bitmap logoImg = Picasso.with(activity).load(IPClass.SERVERIP + logo).get();
DownloadLists.list.add(new ApplicationPojo(id, name, developer, size, logoImg, holder.progressBar));
DownloadLists dlist = new DownloadLists(activity);
dlist.insertData(id, name, developer, size, fileName, logoImg);
UpdateServerDownload d = new UpdateServerDownload();
d.updateDownloadNo(id, category);
} catch (IOException e) {
e.printStackTrace();
}
}
}).start();
new ApkFileDownloader(activity).setParameters(path, fileName, name);
try {
AppList.adapter.notifyDataSetChanged();
} catch (Exception ex) {
System.out.println(ex);
}
try {
SearchResult.adapter.notifyDataSetChanged();
} catch (Exception ex) {
System.out.println(ex);
}
}
});
}
}
}
holder.appName.setText(applicationList.get(position).getName());
holder.developer.setText(applicationList.get(position).getDeveloper());
String sizeText = " میگابایت ";
String appSize =String.valueOf(applicationList.get(position).getSize()) + sizeText;
holder.size.setText(appSize);
if(category == 1001)
{
String cat = applicationList.get(position).getgCat();
holder.appCat.setText(" " + returnGameCat(cat));
holder.catlogo.setImageResource(R.drawable.gamecatlogo);
}
}
catch (Exception ex)
{
Log.d("Adapter Exception", ex.toString());
}
return view;
}
//--------------- A METHOD TO CHECK IF APPLICATION IS ALREADY INSTALLED ------------------------
public boolean appInstalled(String checkApp)
{
pm = activity.getPackageManager();
try
{
pm.getPackageInfo(checkApp, PackageManager.GET_ACTIVITIES);
isAppInstalled = true;
}
catch (PackageManager.NameNotFoundException e)
{
isAppInstalled = false;
}
return isAppInstalled;
}
You are doing wrong in your GetItems and LoadMoreDataTask AsyncTask. you are setting new adapter each time when you scroll down so when new data are loaded to the view the scroll bar jumps to the top of the view.
You need to call
adapter = new ListViewAdapter(AppList.this, applicationList,listview);
listview.setAdapter(adapter);
only first time then you have to only call
adapter.notifyDataSetChanged()
to update your ListView no need to set adapter each time when making new request and also you have to set OnScrollListener to ListView only one time currently new OnScrollListener is set each time when making new request.
You need to setAdapter first time when adapter is null or you are fetching data first time after it just call notifyDataSetChanged()
Save state of listview before updating and then restore:
// save index and top position
int index = mListView.getFirstVisiblePosition();
View v = mListView.getChildAt(0);
int top = (v == null) ? 0 : v.getTop();
// notify dataset changed or re-assign adapter here
// restore the position of listview
mListView.setSelectionFromTop(index, top);
The most Optimal Solution will be
// Save the ListView state (= includes scroll position) as a Parceble
Parcelable state = listView.onSaveInstanceState();
// e.g. set new items
listView.setAdapter(adapter);
// Restore previous state (including selected item index and scroll position)
listView.onRestoreInstanceState(state);
Reference : Retain Scroll Position Android ListView

Setting AppWidget's title using data encoded as JSON

I'm working with json. I parsed the JSON and I can show my JSON (images and text) on ListView. Now I want to show JSON's first item's title in my widget.
I successfully created the widget but I have a problem with the JSON's first item's title.
This is a my code:
public class AppWidget extends AppWidgetProvider {
public static String CLOCK_WIDGET_UPDATE = "CLOCK_WIDGET_UPDATE";
RemoteViews views;
int appWidgetId;
#Override
public void onReceive(Context context, Intent intent) {
super.onReceive(context, intent);
if (CLOCK_WIDGET_UPDATE.equals(intent.getAction())) {
Toast.makeText(context, "onReceiver()", Toast.LENGTH_LONG).show();
}
}
public void onUpdate(Context context, AppWidgetManager appWidgetManager,
int[] appWidgetIds) {
final int N = appWidgetIds.length;
for (int i = 0; i < N; i++) {
appWidgetId = appWidgetIds[i];
Intent intent = new Intent(context, MainActivity.class);
PendingIntent pendingIntent = PendingIntent.getActivity(context, 0,
intent, 0);
views = new RemoteViews(context.getPackageName(),
R.layout.widget_demo);
String aa = (MainActivity.itemList.get(0)
.get(MainActivity.KEY_title)).toString();
views.setOnClickPendingIntent(R.id.widgetPic, pendingIntent);
views.setOnClickPendingIntent(R.id.widgetTitle, pendingIntent);
views.setOnClickPendingIntent(R.id.widgetDesc, pendingIntent);
views.setTextViewText(R.id.widgetDesc, aa);
views.setImageViewBitmap(
R.id.widgetPic,
((BitmapDrawable) context.getResources().getDrawable(
R.drawable.background)).getBitmap());
appWidgetManager.updateAppWidget(appWidgetId, views);
}
}
public void updateAppWidget(Context context,
AppWidgetManager appWidgetManager, int appWidgetId) {
RemoteViews updateViews = new RemoteViews(context.getPackageName(),
R.layout.widget_demo);
try {
} catch (Exception e) {
}
appWidgetManager.updateAppWidget(appWidgetId, updateViews);
}
}
BaseAdapter.java code:
public class MyAdapter extends BaseAdapter {
Context mContext;
private ArrayList<HashMap<String, String>> data;
private static LayoutInflater inflater = null;
public ImageLoader imageLoader;
private int screenSize;
public MyAdapter(Context context, ArrayList<HashMap<String, String>> d,
int screenSize) {
this.mContext = context;
this.data = d;
this.screenSize = screenSize;
inflater = (LayoutInflater) mContext
.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
imageLoader = new ImageLoader(context.getApplicationContext());
}
public int getCount() {
return data.size();
}
public Object getItem(int position) {
return position;
}
public long getItemId(int position) {
return position;
}
public View getView(int position, View convertView, ViewGroup parent) {
View vi = convertView;
if (convertView == null)
vi = inflater.inflate(R.layout.list_row, null);
TextView journal = (TextView) vi.findViewById(R.id.smalljournal);
TextView title = (TextView) vi.findViewById(R.id.smalltitle);
TextView description = (TextView) vi
.findViewById(R.id.smallDescription);
ImageView thumb_image = (ImageView) vi.findViewById(R.id.smallthumb);
TextView statId = (TextView) vi.findViewById(R.id.smallstatID);
TextView DateTime = (TextView) vi.findViewById(R.id.smallDateTime);
HashMap<String, String> itemList = new HashMap<String, String>();
itemList = data.get(position);
journal.setText(itemList.get(MainActivity.KEY_journal));
statId.setText(itemList.get(MainActivity.KEY_statID));
journal.setTypeface(MainActivity.tf2);
String titleString = itemList.get(MainActivity.KEY_title);
SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd");
// coming date : 2014-02-03T18:45:00
String DateTimeTxt = itemList.get(MainActivity.KEY_pubDate).replace(
"T", " ");
// DateTimeTxt = date;
try {
Date _d = df.parse(DateTimeTxt);
SimpleDateFormat new_df = new SimpleDateFormat("dd.MM.yyyy");
String _s = new_df.format(_d);
DateTime.setText(_s);
} catch (ParseException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
if (screenSize == Configuration.SCREENLAYOUT_SIZE_NORMAL)
description.setVisibility(View.INVISIBLE);
else
description.setVisibility(View.VISIBLE);
title.setText(titleString);
title.setTypeface(MainActivity.tf2);
description.setText(itemList.get(MainActivity.KEY_description));
description.setTypeface(MainActivity.tf2);
String url = itemList.get(MainActivity.KEY_image);
// url = url.replace("-c.jpg", ".jpg");
imageLoader.DisplayImage(url, thumb_image);
return vi;
}
}
MainActivity.java code
public class MainActivity extends Activity {
public String URL = "********************";
public static String KEY_title = "title";
public static String KEY_description = "description";
public static String KEY_image = "image";
public static String KEY_journal = "journal";
public static String KEY_JournalID = "JournalID";
public static String KEY_pubDate = "pubDate";
public static String KEY_statID = "statID";
public JSONArray jsonarray;
public ListView list;
public JSONParser jsonparser;
static MyAdapter adapter;
ProgressDialog pDialog, pDialog1;
static String fontPath2 = "font.ttf";
public static Typeface tf2;
public static ArrayList<HashMap<String, String>> itemList = new ArrayList<HashMap<String, String>>();
public ImageLoader imageLoader;
static final int DIALOG_ERROR_CONNECTION = 1;
public static String dateTime;
private ArrayList<Content> contents = new ArrayList<Content>();
public ImageView image;
public EditText searchInput;
public LinearLayout mainLayout, SlideLayout;
public TransparentProgressDialog pd;
public Tools tools;
public static boolean CheckListview = true;
private int screenSize;
int windowWidth;
public LoadDataAllChanelsToServer loadData;
public TextView journal, tittle, description, smalllink, DateTime,
smallstatID;
private ConnectionDetector cd;
AlertDialogManager alert = new AlertDialogManager();
Writer writer;
public File yourFile;
View menu_Slide;
#SuppressLint("CutPasteId")
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
requestWindowFeature(Window.FEATURE_NO_TITLE);
setContentView(R.layout.main);
screenSize = getResources().getConfiguration().screenLayout
& Configuration.SCREENLAYOUT_SIZE_MASK;
SlideLayout = (LinearLayout) findViewById(R.id.SlideLayout);
list = (ListView) findViewById(R.id.listView1);
cd = new ConnectionDetector(getApplicationContext());
adapter = new MyAdapter(MainActivity.this, itemList, screenSize);
Thread.setDefaultUncaughtExceptionHandler(new UnCaughtException(this,
this));
loadData = new LoadDataAllChanelsToServer();
menu_Slide = (findViewById(R.id.menu_button));
image = (ImageView) findViewById(R.id.imageView1);
searchInput = (EditText) findViewById(R.id.input_search_query);
tf2 = Typeface.createFromAsset(getAssets(), fontPath2);
pd = new TransparentProgressDialog(this, R.drawable.loader);
list.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
journal = (TextView) view.findViewById(R.id.smalljournal);
tittle = (TextView) view.findViewById(R.id.smalltitle);
description = (TextView) view
.findViewById(R.id.smallDescription);
smalllink = (TextView) view.findViewById(R.id.smalllink);
DateTime = (TextView) view.findViewById(R.id.smallDateTime);
smallstatID = (TextView) view.findViewById(R.id.smallstatID);
String Stringjournal = journal.getText().toString();
String Stringtittle = tittle.getText().toString();
String Stringdescription = description.getText().toString();
String Stringlink = smalllink.getText().toString();
String StringdateTime = DateTime.getText().toString();
String StringstatID = smallstatID.getText().toString();
HideKeyBoadr();
Intent in = new Intent(MainActivity.this, Result.class);
in.putExtra("KEY_journal", Stringjournal);
in.putExtra("KEY_title", Stringtittle);
in.putExtra("KEY_description", Stringdescription);
in.putExtra("KEY_link", Stringlink);
in.putExtra("KEY_pubDate", StringdateTime);
in.putExtra("KEY_statID", StringstatID);
String url = itemList.get(position).get(MainActivity.KEY_image);
if (!cd.isConnectingToInternet()) {
in.putExtra("Bitmap", url);
}
else {
if (url.endsWith("-c.jpg"))
url = url.replace("-c.jpg", ".jpg");
in.putExtra("Bitmap", url);
}
in.putExtra("Bitmap", url);
startActivity(in);
overridePendingTransition(R.anim.trans_left_in,
R.anim.trans_left_out);
}
});
if (!cd.isConnectingToInternet()) {
return;
} else {
loadData.execute();
}
}
public void HideKeyBoadr() {
InputMethodManager imm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
imm.hideSoftInputFromWindow(searchInput.getWindowToken(), 0);
}
private class LoadDataAllChanelsToServer extends
AsyncTask<String, Integer, String> {
#Override
protected void onPreExecute() {
pd.show();
}
#Override
protected String doInBackground(String... urls) {
jsonparser = new JSONParser();
JSONObject jsonobject = jsonparser.getJSONfromURL(URL);
try {
jsonarray = jsonobject.getJSONArray("data");
for (int i = 0; i < jsonarray.length(); i++) {
jsonobject = jsonarray.getJSONObject(i);
HashMap<String, String> map = new HashMap<String, String>();
map.put("journal", jsonobject.getString(KEY_journal));
map.put("image", jsonobject.getString(KEY_image));
map.put("title", jsonobject.getString(KEY_title));
map.put("description",
jsonobject.getString(KEY_description));
map.put("JournalID", jsonobject.getString(KEY_JournalID));
map.put("pubDate", jsonobject.getString(KEY_pubDate));
map.put("statID", jsonobject.getString(KEY_statID));
Content cont = new Content(jsonobject.getString("journal"),
jsonobject.getString("image"),
jsonobject.getString("title"),
jsonobject.getString("pubDate"),
jsonobject.getString("description"),
jsonobject.getString("JournalID"),
jsonobject.getString("statID"));
contents.add(cont);
itemList.add(map);
dateTime = itemList.get(itemList.size() - 1).get(
KEY_pubDate);
}
} catch (JSONException e) {
Log.e("Error", e.getMessage());
e.printStackTrace();
}
return itemList.toString();
}
#Override
protected void onPostExecute(String result) {
try {
if (pd != null) {
pd.dismiss();
}
} catch (Exception e) {
}
try {
adapter = new MyAdapter(MainActivity.this, itemList, screenSize);
list.setAdapter(adapter);
} catch (NullPointerException e) {
e.printStackTrace();
}
}
}
#Override
public void onBackPressed() {
createDialog();
}
private void createDialog() {
AlertDialog.Builder alertDlg = new AlertDialog.Builder(this);
alertDlg.setMessage("Are you sure you want to exit?");
alertDlg.setCancelable(false);
alertDlg.setPositiveButton("Yes",
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
MainActivity.super.onBackPressed();
}
}
);
alertDlg.setNegativeButton("No", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
}
});
alertDlg.create().show();
}
}
My problem is: When I click the widget I get
indexofboundexception (invalid index 0,size 1)
What is the problem?
My problem is: When I click the widget I get
indexofboundexception (invalid index 0,size 1)
What is the problem?
That is too much code to look at. Please narrow your issue down and show the exact point the issue is occurring at.
Use your debugger to step through your code. 1st, identify the exact line at which the issue is occurring. Next, use your debugger to inspect the variables at that point. The error is an index out of bounds, so you're accessing a point in a list that is bigger than the size of the list.

listview does not updates

I am expirience wierd situation because my list view updates only once.
The idia is following, i want to download posts from web, which are located on page 3 and page 5 and show both of them on listview. However, List view shows posts only from page 3. MEanwhile, log shows that all poast are downloded and stored in addList.
So the problem - objects from second itteration are not shown in listview. Help me please to fix this issue.
public class MyAddActivateActivity extends ErrorActivity implements
AddActivateInterface {
// All static variables
// XML node keys
View footer;
public static final String KEY_ID = "not_id";
public static final String KEY_TITLE = "not_title";
Context context;
public static final String KEY_PHOTO = "not_photo";
public final static String KEY_PRICE = "not_price";
public final static String KEY_DATE = "not_date";
public final static String KEY_DATE_TILL = "not_date_till";
private int not_source = 3;
JSONObject test = null;
ListView list;
MyAddActivateAdapter adapter;
ArrayList<HashMap<String, String>> addList;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
context = this;
setContentView(R.layout.aadd_my_add_list_to_activate);
footer = getLayoutInflater().inflate(R.layout.loading_view, null);
addList = new ArrayList<HashMap<String, String>>();
ImageView back_button = (ImageView) findViewById(R.id.imageView3);
back_button.setOnClickListener(new OnClickListener() {
public void onClick(View arg0) {
Intent i = new Intent(getApplicationContext(),
ChooserActivity.class);
startActivity(i);
finish();
}
});
Intent intent = this.getIntent();
// if (intent != null) {
// not_source = intent.getExtras().getInt("not_source");
// }
GAdds g = new GAdds();
g.execute(1, not_source);
list = (ListView) findViewById(R.id.list);
// Getting adapter by passing xml data ArrayList
adapter = new MyAddActivateAdapter(this, addList);
list.addFooterView(footer);
list.setAdapter(adapter);
// Click event for single list row
list.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
String add_id = ((TextView) view
.findViewById(R.id.tv_my_add_id)).getText().toString();
add_id = add_id.substring(4);
Log.d("ADD_ID", add_id);
// Launching new Activity on selecting single List Item
Intent i = new Intent(getApplicationContext(),
AddToCheckActivity.class);
// sending data to new activity
UILApplication.advert.setId(add_id);
startActivity(i);
finish();
}
});
}
private void emptyAlertSender() {
AlertDialog alertDialog = new AlertDialog.Builder(this).create();
alertDialog.setTitle("Ничего не найдено");
alertDialog.setMessage("У вас нет неактивных объявлений.");
alertDialog.setButton("на главную",
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
Intent intent = new Intent(getApplicationContext(),
ChooserActivity.class);
startActivity(intent);
finish();
}
});
alertDialog.setIcon(R.drawable.ic_launcher);
alertDialog.show();
}
class GAdds extends AsyncTask<Integer, Void, JSONObject> {
#Override
protected JSONObject doInBackground(Integer... params) {
// addList.clear();
Log.d("backgraund", "backgraund");
UserFunctions u = new UserFunctions();
return u.getAdds(params[0] + "", params[1] + "");
}
#Override
protected void onPostExecute(JSONObject result) {
super.onPostExecute(result);
Log.d("postexecute", "postexecute");
footer.setVisibility(View.GONE);
JSONArray tArr = null;
if (result != null) {
try {
tArr = result.getJSONArray("notices");
for (int i = 0; i < tArr.length(); i++) {
JSONObject a = null;
HashMap<String, String> map = new HashMap<String, String>();
a = (JSONObject) tArr.get(i);
if (a.getInt("not_status") == 0) {
int premium = a.getInt("not_premium");
int up = a.getInt("not_up");
if (premium == 1 && up == 1) {
map.put("status", R.drawable.vip + "");
} else if (premium == 1) {
map.put("status", R.drawable.prem + "");
} else if (premium != 1 && up == 1) {
map.put("status", R.drawable.up + "");
} else {
map.put("status", 0 + "");
}
map.put(KEY_ID, "ID: " + a.getString(KEY_ID));
map.put(KEY_TITLE, a.getString(KEY_TITLE));
map.put(KEY_PRICE,
"Цена: " + a.getString(KEY_PRICE) + " грн.");
map.put(KEY_PHOTO, a.getString(KEY_PHOTO));
map.put(KEY_DATE,
"Создано: " + a.getString(KEY_DATE));
map.put(KEY_DATE_TILL,
"Действительно до: "
+ a.getString(KEY_DATE_TILL));
map.put("check", "false");
Log.d("MyAddList", "map was populated");
}
if (map.size() > 0)
{
addList.add(map);
Log.d("MyAddList", "addlist was populated");
}
}
} catch (JSONException e) {
e.printStackTrace();
}
} else {
if (UILApplication.login != 2) {
UILApplication.login = 3;
}
onCreateDialog(LOST_CONNECTION).show();
}
runOnUiThread(new Runnable() {
public void run() {
adapter.notifyDataSetChanged();
}
});
if (not_source == 3) {
not_source = 5;
GAdds task = new GAdds();
task.execute(1, 5);
}
if (not_source == 5) {
Log.d("ID", m.get(KEY_ID));
if (addList.size() == 0) {
emptyAlertSender();
}
}
}
}
#SuppressWarnings("unchecked")
public void addAct(View v) {
AddActivate aAct = new AddActivate(this);
aAct.execute(addList);
}
#Override
public void onAddActivate(JSONObject result) {
if (result != null) {
Intent intent = getIntent();
finish();
startActivity(intent);
}
}
}
adapter
public class MyAddActivateAdapter extends BaseAdapter {
private List<Row> rows;
private ArrayList<HashMap<String, String>> data;
private Activity activity;
public MyAddActivateAdapter(Activity activity,
ArrayList<HashMap<String, String>> data) {
Log.d("mediaadapter", "listcreation: " + data.size());
rows = new ArrayList<Row>();// member variable
this.data = data;
this.activity = activity;
}
#Override
public int getViewTypeCount() {
return RowType.values().length;
}
#Override
public void notifyDataSetChanged() {
rows.clear();
for (HashMap<String, String> addvert : data) {
rows.add(new MyAddActivateRow((LayoutInflater) activity
.getSystemService(Context.LAYOUT_INFLATER_SERVICE), addvert));
Log.d("MyActivateAdapter", "update " + data.size());
}
}
#Override
public int getItemViewType(int position) {
return rows.get(position).getViewType();
}
public int getCount() {
return rows.size();
}
public Object getItem(int position) {
return position;
}
public long getItemId(int position) {
return position;
}
public View getView(int position, View convertView, ViewGroup parent) {
return rows.get(position).getView(convertView);
}
}
I think the problem is you aren't calling the super class of notifyDataSetChanged(), maybe try
#Override
public void notifyDataSetChanged() {
rows.clear();
for (HashMap<String, String> addvert : data) {
rows.add(new MyAddActivateRow((LayoutInflater) activity
.getSystemService(Context.LAYOUT_INFLATER_SERVICE), addvert));
Log.d("MyActivateAdapter", "update " + data.size());
}
super.notifyDataSetChanged();
}

Android Not responding in loading images from Url

I am trying to parse the xml file and trying to load images and textviews and display it in a list view but whenever i try to load images in getView method in force closes the application even if try to scroll fast it also does the same. Iam tired of doing it in thread and asynctask for 5hours.please help if someone can solve it. Here are my two class files.
class NewsRowAdapter
public class NewsRowAdapter extends ArrayAdapter<Item>
{
LoadingImage loadingImage;
Bitmap bitmap = null;
private Activity activity;
private List<Item> items;
private Item objBean;
private int row;
public NewsRowAdapter(Activity act, int resource, List<Item> arrayList)
{
super(act, resource, arrayList);
this.activity = act;
this.row = resource;
this.items = arrayList;
}
#Override
public View getView(final int position, View convertView, ViewGroup parent)
{
View view = convertView;
final ViewHolder holder;
if (view == null)
{
LayoutInflater inflater = (LayoutInflater) activity.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
view = inflater.inflate(row, null);
holder = new ViewHolder();
view.setTag(holder);
} else
{
holder = (ViewHolder) view.getTag();
}
if ((items == null) || ((position + 1) > items.size()))
return view;
objBean = items.get(position);
holder.tvTitle = (TextView) view.findViewById(R.id.tvtitle);
holder.tvDesc = (TextView) view.findViewById(R.id.tvdesc);
holder.tvDate = (TextView) view.findViewById(R.id.tvdate);
holder.imgView = (ImageView) view.findViewById(R.id.image);
holder.pbar = (ProgressBar) view.findViewById(R.id.pbar);
if (holder.tvTitle != null && null != objBean.getTitle() && objBean.getTitle().trim().length() > 0)
{
holder.tvTitle.setText(Html.fromHtml(objBean.getTitle()));
}
if (holder.tvDesc != null && null != objBean.getDesc() && objBean.getDesc().trim().length() > 0)
{
holder.tvDesc.setText(Html.fromHtml(objBean.getDesc()));
}
if (holder.tvDate != null && null != objBean.getPubdate() && objBean.getPubdate().trim().length() > 0)
{
holder.tvDate.setText(Html.fromHtml(objBean.getPubdate()));
}
if (holder.imgView != null)
{
if (null != objBean.getLink() && objBean.getLink().trim().length() > 0)
{
final ProgressBar pbar = holder.pbar;
pbar.setVisibility(View.INVISIBLE);
//---------CHANGES MADE FOR LOADING IMAGE----------//
Log.d("IMAGE NULL----------", objBean.getLink());
//loadBitmap(objBean.getLink());
/*new Thread()
{
public void run()
{*/
try
{
URL linkurl = new URL(objBean.getLink());
bitmap = BitmapFactory.decodeStream(linkurl.openConnection().getInputStream());
holder.imgView.setImageBitmap(bitmap);
} catch (MalformedURLException e)
{
e.printStackTrace();
} catch (IOException e)
{
e.printStackTrace();
}
/*}
}.start();*/
} else
{
holder.imgView.setImageResource(R.drawable.ic_launcher);
}
}
return view;
}
//------LOADING IMAGE FROM URL------//
public static Bitmap loadBitmap(String url)
{
Bitmap bitmap = null;
final AndroidHttpClient client = AndroidHttpClient.newInstance("Android");
final HttpGet getRequest = new HttpGet(url);
try
{
HttpResponse response = client.execute(getRequest);
final int statusCode = response.getStatusLine().getStatusCode();
if (statusCode != HttpStatus.SC_OK)
{
Log.d("ImageDownloader", "Error " + statusCode + " while retrieving bitmap from " + url);
return null;
}
final HttpEntity entity = response.getEntity();
if (entity != null)
{
InputStream inputStream = null;
try
{
inputStream = entity.getContent();
bitmap = BitmapFactory.decodeStream(inputStream);
} finally
{
if (inputStream != null)
{
inputStream.close();
}
entity.consumeContent();
}
}
} catch (Exception e)
{
// Could provide a more explicit error message for IOException or IllegalStateException
getRequest.abort();
Log.d("Error while retrieving bitmap from " + url, e.toString());
} finally
{
if (client != null)
{
client.close();
}
}
return bitmap;
}
public class ViewHolder
{
public TextView tvTitle, tvDesc, tvDate;
private ImageView imgView;
private ProgressBar pbar;
}
}
and the main class is :
class MainActivity
public class MainActivity extends Activity implements OnItemClickListener
{
private static final String rssFeed = /*"https://www.dropbox.com/s/t4o5wo6gdcnhgj8/imagelistview.xml?dl=1"*/"http://78.46.34.27/kapapps/newparsedtransaction.xml";
List<Item> arrayOfList;
ListView listView;
#Override
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.mainnewtransaction);
listView = (ListView) findViewById(R.id.listview);
listView.setOnItemClickListener(this);
if (Utils.isNetworkAvailable(NewTransactionActivity.this))
{
new MyTask().execute(rssFeed);
} else
{
showToast("No Network Connection!!!");
}
}
// My AsyncTask start...
class MyTask extends AsyncTask<String, Void, Void>
{
ProgressDialog pDialog;
#Override
protected void onPreExecute()
{
super.onPreExecute();
pDialog = new ProgressDialog(NewTransactionActivity.this);
pDialog.setTitle("Latest Transaction");
pDialog.setMessage("Loading... Please wait");
pDialog.show();
}
#Override
protected Void doInBackground(String... params)
{
arrayOfList = new NamesParser().getData(params[0]);
return null;
}
#Override
protected void onPostExecute(Void result)
{
super.onPostExecute(result);
if (null == arrayOfList || arrayOfList.size() == 0)
{
showToast("No data found from web!!!");
NewTransactionActivity.this.finish();
} else
{
// check data...
/*
* for (int i = 0; i < arrayOfList.size(); i++)
* {
* Item item = arrayOfList.get(i); System.out.println(item.getId());
* System.out.println(item.getTitle());
* System.out.println(item.getDesc());
* System.out.println(item.getPubdate());
* System.out.println(item.getLink());
* }
*/
for(int i = 0 ; i < arrayOfList.size() ; i++)
{
Item item = arrayOfList.get(i);
Log.d("ID NEWTRANSACTION ACTIVITY ------>" , item.getId());
Log.d("TITLE NEWTRANSACTION ACTIVITY ------>" , item.getTitle());
Log.d("DESC NEWTRANSACTION ACTIVITY ------>", item.getDesc());
Log.d("LINK NEWTRANSACTION ACTIVITY ------>", item.getLink());
}
setAdapterToListview();
}
if (null != pDialog && pDialog.isShowing())
{
pDialog.dismiss();
}
}
}
#Override
public void onItemClick(AdapterView<?> parent , View view , int position , long id)
{
Item item = arrayOfList.get(position);
Intent intent = new Intent(NewTransactionActivity.this, DetailActivity.class);
intent.putExtra("url", item.getLink());
intent.putExtra("title", item.getTitle());
intent.putExtra("desc", item.getDesc());
Log.d("IMAGE_URL------>" , item.getLink());
startActivity(intent);
}
public void setAdapterToListview()
{
NewsRowAdapter objAdapter = new NewsRowAdapter(NewTransactionActivity.this , R.layout.row, arrayOfList);
listView.setAdapter(objAdapter);
}
public void showToast(String msg)
{
}
}
Do Image retrieving logic in another thread.It is taking too much time to load Images that's why you are getting ANR.
Use a single worker thread, and make it possible to stop in onPause() of activity.
Good way is to use a SingleThread Executor service to load images.
Here's an example https://stackoverflow.com/a/14579365/1366471
I recommend using the RemoteImageView from the Prime library. It reduces your work a lot.
In your layout, replace ImageView with com.handlerexploit.prime.widgets.RemoteImageView and in your code, change ImageView to RemoteImageView in your holder class.
In the getView method,
holder.imgView = (RemoteImageView) view.findViewById(R.id.image);
//...
holder.imgView.setImageURL(objBean.getLink());

Categories

Resources