Android Not responding in loading images from Url - android

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());

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

NPE getCount in Adapter when trying to get user albums using FB SDK

I am trying to get the users albums using the FB SDK. I have managed to log-in successfully and am able to retrieve the users profile picture and acquire an access token.
I am following this answer here and am trying to get it to work, but I am running into an issue where I get java.lang.NullPointerException in the adapter class on at com.myapp.myapp.PhotosAdapter.getCount(PhotosAdapter.java:37)
Here's the full set-up as to what I have:
Where am I going wrong? thanks
FBGRID activity:
public class FBGRID extends Activity {
private String URL;
// STORE THE PAGING URL
private String pagingURL;
// FLAG FOR CURRENT PAGE
int current_page = 1;
// BOOLEAN TO CHECK IF NEW FEEDS ARE LOADING
Boolean loadingMore = true;
Boolean stopLoadingData = false;
GridView grid;
ArrayList<getPhotos> arrPhotos;
PhotosAdapter adapter;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_fbgrid);
grid = (GridView) findViewById(R.id.gridView1);
grid.setOnScrollListener(new OnScrollListener() {
#Override
public void onScrollStateChanged(AbsListView view, int scrollState) {
}
#Override
public void onScroll(AbsListView view, int firstVisibleItem,
int visibleItemCount, int totalItemCount) {
int lastInScreen = firstVisibleItem + visibleItemCount;
if ((lastInScreen == totalItemCount) && !(loadingMore)) {
if (stopLoadingData == false) {
// FETCH THE NEXT BATCH OF FEEDS
new loadMorePhotos().execute();
}
}
}
});
new getPhotosData().execute();
}
private class getPhotosData extends AsyncTask<Void, Void, Void> {
#Override
protected Void doInBackground(Void... arg0) {
// CHANGE THE LOADING MORE STATUS TO PREVENT DUPLICATE CALLS FOR
// MORE DATA WHILE LOADING A BATCH
loadingMore = true;
Session s = Session.getActiveSession();
// SET THE INITIAL URL TO GET THE FIRST LOT OF ALBUMS
URL = "https://graph.facebook.com/" + "me/albums"
+ "/photos&access_token=" + s.getAccessToken()
+ "?limit=10";
try {
HttpClient hc = new DefaultHttpClient();
HttpGet get = new HttpGet(URL);
HttpResponse rp = hc.execute(get);
if (rp.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {
String queryAlbums = EntityUtils.toString(rp.getEntity());
JSONObject JOTemp = new JSONObject(queryAlbums);
JSONArray JAPhotos = JOTemp.getJSONArray("data");
// IN MY CODE, I GET THE NEXT PAGE LINK HERE
getPhotos photos;
for (int i = 0; i < JAPhotos.length(); i++) {
JSONObject JOPhotos = JAPhotos.getJSONObject(i);
// Log.e("INDIVIDUAL ALBUMS", JOPhotos.toString());
if (JOPhotos.has("link")) {
photos = new getPhotos();
// GET THE ALBUM ID
if (JOPhotos.has("id")) {
photos.setPhotoID(JOPhotos.getString("id"));
} else {
photos.setPhotoID(null);
}
// GET THE ALBUM NAME
if (JOPhotos.has("name")) {
photos.setPhotoName(JOPhotos.getString("name"));
} else {
photos.setPhotoName(null);
}
// GET THE ALBUM COVER PHOTO
if (JOPhotos.has("picture")) {
photos.setPhotoPicture(JOPhotos
.getString("picture"));
} else {
photos.setPhotoPicture(null);
}
// GET THE PHOTO'S SOURCE
if (JOPhotos.has("source")) {
photos.setPhotoSource(JOPhotos
.getString("source"));
} else {
photos.setPhotoSource(null);
}
arrPhotos.add(photos);
}
}
}
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
#Override
protected void onPostExecute(Void result) {
grid.setAdapter(new PhotosAdapter(FBGRID.this, arrPhotos));
loadingMore = false;
}
}
private class loadMorePhotos extends AsyncTask<Void, Void, Void> {
#Override
protected Void doInBackground(Void... arg0) {
// SET LOADING MORE "TRUE"
loadingMore = true;
// INCREMENT CURRENT PAGE
current_page += 1;
// Next page request
URL = pagingURL;
try {
HttpClient hc = new DefaultHttpClient();
HttpGet get = new HttpGet(URL);
HttpResponse rp = hc.execute(get);
if (rp.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {
String queryAlbums = EntityUtils.toString(rp.getEntity());
// Log.e("PAGED RESULT", queryAlbums);
JSONObject JOTemp = new JSONObject(queryAlbums);
JSONArray JAPhotos = JOTemp.getJSONArray("data");
// IN MY CODE, I GET THE NEXT PAGE LINK HERE
getPhotos photos;
for (int i = 0; i < JAPhotos.length(); i++) {
JSONObject JOPhotos = JAPhotos.getJSONObject(i);
// Log.e("INDIVIDUAL ALBUMS", JOPhotos.toString());
if (JOPhotos.has("link")) {
photos = new getPhotos();
// GET THE ALBUM ID
if (JOPhotos.has("id")) {
photos.setPhotoID(JOPhotos.getString("id"));
} else {
photos.setPhotoID(null);
}
// GET THE ALBUM NAME
if (JOPhotos.has("name")) {
photos.setPhotoName(JOPhotos.getString("name"));
} else {
photos.setPhotoName(null);
}
// GET THE ALBUM COVER PHOTO
if (JOPhotos.has("picture")) {
photos.setPhotoPicture(JOPhotos
.getString("picture"));
} else {
photos.setPhotoPicture(null);
}
// GET THE ALBUM'S PHOTO COUNT
if (JOPhotos.has("source")) {
photos.setPhotoSource(JOPhotos
.getString("source"));
} else {
photos.setPhotoSource(null);
}
arrPhotos.add(photos);
}
}
}
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
#Override
protected void onPostExecute(Void result) {
// get listview current position - used to maintain scroll position
int currentPosition = grid.getFirstVisiblePosition();
// APPEND NEW DATA TO THE ARRAYLIST AND SET THE ADAPTER TO THE
// LISTVIEW
adapter = new PhotosAdapter(FBGRID.this, arrPhotos);
grid.setAdapter(adapter);
// Setting new scroll position
grid.setSelection(currentPosition + 1);
// SET LOADINGMORE "FALSE" AFTER ADDING NEW FEEDS TO THE EXISTING
// LIST
loadingMore = false;
}
}
public class getPhotos {
String PhotoID;
String PhotoName;
String PhotoPicture;
String PhotoSource;
// SET THE PHOTO ID
public void setPhotoID(String PhotoID) {
this.PhotoID = PhotoID;
}
// GET THE PHOTO ID
public String getPhotoID() {
return PhotoID;
}
// SET THE PHOTO NAME
public void setPhotoName(String PhotoName) {
this.PhotoName = PhotoName;
}
// GET THE PHOTO NAME
public String getPhotoName() {
return PhotoName;
}
// SET THE PHOTO PICTURE
public void setPhotoPicture(String PhotoPicture) {
this.PhotoPicture = PhotoPicture;
}
// GET THE PHOTO PICTURE
public String getPhotoPicture() {
return PhotoPicture;
}
// SET THE PHOTO SOURCE
public void setPhotoSource(String PhotoSource) {
this.PhotoSource = PhotoSource;
}
// GET THE PHOTO SOURCE
public String getPhotoSource() {
return PhotoSource;
}
}
}
and for the Adapter class(it uses an image loading library):
final class PhotosAdapter extends BaseAdapter {
private Activity activity;
ArrayList<getPhotos> arrayPhotos;
private static LayoutInflater inflater = null;
ImageLoader imageLoader;
public PhotosAdapter(Activity a, ArrayList<getPhotos> arrPhotos) {
activity = a;
arrayPhotos = arrPhotos;
inflater = (LayoutInflater) activity
.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
imageLoader = new ImageLoader(activity.getApplicationContext());
}
public int getCount() {
return arrayPhotos.size();
}
public Object getItem(int position) {
return arrayPhotos.get(position);
}
public long getItemId(int position) {
return position;
}
public View getView(final int position, View convertView, ViewGroup parent) {
ViewHolder holder;
View vi = convertView;
if (convertView == null) {
vi = inflater.inflate(R.layout.photos_item, null);
holder = new ViewHolder();
holder.imgPhoto = (ImageView) vi.findViewById(R.id.grid_item_image);
vi.setTag(holder);
} else {
holder = (ViewHolder) vi.getTag();
}
if (arrayPhotos.get(position).getPhotoPicture() != null) {
imageLoader.DisplayImage(arrayPhotos.get(position)
.getPhotoPicture(), holder.imgPhoto);
}
return vi;
}
static class ViewHolder {
ImageView imgPhoto;
}
}
Here's logcat:
FATAL EXCEPTION: main
java.lang.NullPointerException
at com.myapp.myapp.PhotosAdapter.getCount(PhotosAdapter.java:37)
at android.widget.GridView.setAdapter(GridView.java:186)
at com.myapp.myapp.FBGRID$getPhotosData.onPostExecute(FBGRID.java:173)
at com.myapp.myapp.FBGRID$getPhotosData.onPostExecute(FBGRID.java:1)
at android.os.AsyncTask.finish(AsyncTask.java:631)
at android.os.AsyncTask.access$600(AsyncTask.java:177)
at android.os.AsyncTask$InternalHandler.handleMessage(AsyncTask.java:644)
at android.os.Handler.dispatchMessage(Handler.java:99)
at android.os.Looper.loop(Looper.java:213)
at android.app.ActivityThread.main(ActivityThread.java:5225)
at java.lang.reflect.Method.invokeNative(Native Method)
at java.lang.reflect.Method.invoke(Method.java:525)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:741)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:557)
at dalvik.system.NativeStart.main(Native Method)

Android ListView wrong images

I'm developing an Android app but I'm a newbie and I got stuck...
My ListView single element has an ImageView and some TextViews, but sometimes (when I scroll the page and there are more than 7-8 elements) it doesn't display the right image in the right row.
I'm using a custom Image Loader to manage the downloaded images.
Here's my Adapter:
public class AddVideogameActivityAdapter extends BaseAdapter {
private ArrayList<Videogame> videogames;
private Typeface typefaceMedium;
private Typeface typefaceLight;
private ImageLoader loader;
private LayoutInflater mInflater;
public AddVideogameActivityAdapter(Context context, ArrayList<Videogame> results) {
videogames = results;
mInflater = LayoutInflater.from(context);
typefaceMedium = Typeface.createFromAsset(context.getAssets(), "Roboto-Medium.ttf");
typefaceLight = Typeface.createFromAsset(context.getAssets(), "Roboto-Light.ttf");
loader = new ImageLoader(context);
}
public int getCount() {
return videogames.size();
}
public Object getItem(int position) {
return videogames.get(position);
}
public long getItemId(int position) {
return position;
}
public View getView(int position, View convertView, ViewGroup parent) {
ViewHolder holder;
if (convertView == null) {
convertView = mInflater.inflate(R.layout.list_element,null);
holder = new ViewHolder();
holder.imgView = (ImageView) convertView.findViewById(R.id.thumbView);
holder.txtName = (TextView) convertView.findViewById(R.id.elementView);
holder.txtPlatform = (TextView) convertView.findViewById(R.id.elementView2);
convertView.setTag(holder);
}
else {
holder = (ViewHolder) convertView.getTag();
}
try {
Videogame vgame = (Videogame) videogames.get(position);
holder.txtName.setText(vgame.getTitle());
holder.txtName.setTypeface(typefaceMedium);
holder.txtPlatform.setText(videogames.get(position).getPlatform());
holder.txtPlatform.setTypeface(typefaceLight);
holder.imgUrl = videogames.get(position).getImage();
loader.display(holder.imgUrl, holder.imgView, R.drawable.youtube_icon);
}
catch (Exception e) {
e.printStackTrace();
Log.e(com.example.ludos2_0.MainActivity.TAG,
"Exception: " + e.getLocalizedMessage());
}
return convertView;
}
static class ViewHolder {
TextView txtName;
TextView txtPlatform;
public String imgUrl;
ImageView imgView;
}
}
Sorry for my english and thank you for your help!
EDIT:
Here's also the Loader:
public class ImageLoader implements ComponentCallbacks2 {
private TCLruCache cache;
public ImageLoader(Context context) {
ActivityManager am = (ActivityManager) context.getSystemService(
Context.ACTIVITY_SERVICE);
int memoryClass = am.getMemoryClass() * 1024 * 1024;
cache = new TCLruCache(memoryClass);
}
public void display(String url, ImageView imageview, int defaultresource) {
imageview.setImageResource(defaultresource);
Bitmap image = cache.get(url);
if (image != null) {
imageview.setImageBitmap(image);
}
else {
new SetImageTask(imageview).execute(url);
}
}
private class TCLruCache extends LruCache<String, Bitmap> {
public TCLruCache(int maxSize) {
super(maxSize);
}
}
private class SetImageTask extends AsyncTask<String, Void, Integer> {
private ImageView imageview;
private Bitmap bmp;
public SetImageTask(ImageView imageview) {
this.imageview = imageview;
}
#Override
protected Integer doInBackground(String... params) {
String url = params[0];
try {
bmp = getBitmapFromURL(url);
if (bmp != null) {
cache.put(url, bmp);
}
else {
return 0;
}
} catch (Exception e) {
e.printStackTrace();
return 0;
}
return 1;
}
#Override
protected void onPostExecute(Integer result) {
if (result == 1) {
imageview.setImageBitmap(bmp);
}
super.onPostExecute(result);
}
private Bitmap getBitmapFromURL(String src) {
try {
URL url = new URL(src);
HttpURLConnection connection
= (HttpURLConnection) url.openConnection();
connection.setDoInput(true);
connection.connect();
InputStream input = connection.getInputStream();
Bitmap myBitmap = BitmapFactory.decodeStream(input);
return myBitmap;
} catch (IOException e) {
e.printStackTrace();
return null;
}
}
}
}
RE-EDIT
Activity code:
public class AddVideogameActivity extends ListActivity {
private TextView searchField = null;
private final Handler handler = new Handler();
private ArrayList<Videogame> videogamesList = null;
private static AddVideogameActivity mContext = null;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_add_book);
mContext = this;
searchField = (TextView) findViewById(R.id.searchField);
searchField.setMaxLines(1);
searchField.setOnFocusChangeListener(new OnFocusChangeListener() {
#Override
public void onFocusChange(View v, boolean hasFocus) {
searchField.setHint("");
}
});
// Setup the list view and its listener
getListView().setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
Log.d(MainActivity.TAG,
"AddBookActivity ---> AddButton:onClick()");
// Sets typefaces for TextView
String videogameId = videogamesList.get(position).getId();
String videogameName = videogamesList.get(position).getTitle();
String thumbnail = videogamesList.get(position).getThumbnail();
String description = videogamesList.get(position)
.getDescription();
String image = videogamesList.get(position).getImage();
String platform = videogamesList.get(position).getPlatform();
if (videogameName != null && videogameName.length() > 0
&& thumbnail != null && thumbnail.length() > 0
&& description != null && description.length() > 0
&& image != null && image.length() > 0
&& platform != null && platform.length() > 0) {
if (ListsManager.getInstance().addVideogame(
new Videogame(videogameId, videogameName,
thumbnail, image, description, platform)) == 0) {
Log.d(MainActivity.TAG,
"AddBookActivity --> Videogame:[" + videogameId
+ "#" + videogameName + "]");
Toast toast = Toast.makeText(mContext, "["
+ videogameName + "] Saved !",
Toast.LENGTH_LONG);
toast.show();
} else {
Log.e(MainActivity.TAG,
"AddBookActivity --> Error ! Videogame already in the list ! ");
Toast toast = Toast.makeText(mContext,
"Error! Videogame already in the list!",
Toast.LENGTH_LONG);
toast.show();
}
} else {
Log.e(MainActivity.TAG,
"AddBookActivity --> Error ! Invalid Videogame Name or Thumbnail or Id or Deck");
Toast toast = Toast
.makeText(
mContext,
"Error ! Invalid Videogame Name or Thumbnail or Id or Deck",
Toast.LENGTH_LONG);
toast.show();
}
Intent newIntent = new Intent(getApplicationContext(),
MainActivity.class);
startActivity(newIntent);
}
});
// Setup the search button and its listener
Button searchButton = (Button) findViewById(R.id.searchButton);
searchButton.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
Log.d(com.example.ludos2_0.MainActivity.TAG, "Search Game ...");
String searchInputString = searchField.getText().toString();
if (searchInputString != null && searchInputString.length() > 0) {
try {
String requestURL = ("http://www.giantbomb.com/api/search/?api_key=fcf60d6d67b98b0d17b3905d1a90b3fd31ed1e8e&format=json&query="
+ Uri.encode(searchInputString) + "&resources=game");
// String requestURL =
// String.format("https://gdata.youtube.com/feeds/api/videos?v=2&alt=jsonc&category=Music&orderby=relevance&q=%s",Uri.encode(searchInputString));
Log.d(com.example.ludos2_0.MainActivity.TAG, requestURL);
DownloadGiantBombJSONData giantbombAsyncTask = new DownloadGiantBombJSONData();
giantbombAsyncTask.execute(new String[] { requestURL });
} catch (Exception e) {
e.printStackTrace();
}
}
}
});
if (videogamesList == null)
videogamesList = new ArrayList<Videogame>();
else
updateVideogamesListView(videogamesList);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.add_book, menu);
return true;
}
#Override
protected void onResume() {
super.onResume();
}
#Override
protected void onPause() {
super.onPause();
}
public void updateVideogamesListView(ArrayList<Videogame> values) {
AddVideogameActivityAdapter adapter = new AddVideogameActivityAdapter(this, values);
setListAdapter(adapter);
}
#Override
protected void onDestroy() {
super.onDestroy();
}
}
The other classes involved in building the ListView are the REST classes and the AsyncTask class that downloads and parses the JSon files.
What does your ListView look like, does it look like this:
<ListView android:id="#id/android:list"
android:layout_weight="1"
android:layout_width="match_parent"
android:layout_height="0dip" ></ListView>
Especially the id of the ListView. Check your layout file, probably the bug exists there.

Android: Change image for a particular item in listview

In the above image, there is a list view which contains list of items that the user can download. This is the image which tells user that he can download the file. On completion of download, the image will change to . My problem is when I download a file, the status image(which denotes that download has completed) gets changed for another row, instead, it should change for the row that I had selected. At present, if I download first file in the list, the image gets changed for 4th or 5th item in the list. Also, when I try to download any other file from the list. it opens up last downloaded file(This is functionality of the app that if file is already downloaded, then open it in pdf reader),i.e., if I download 1st file in the list and then go for second item,then instead of downloading 2nd file, it opens up last downloaded file. More over, if I scroll the listview, the status of download gets changed for other items in the list also. Below,is my adapter code:
public class DownloadListAdapter extends BaseAdapter {
Context ctx;
public ArrayList<DownloadListDao> mDownloadList;
String readMoreLink;
public static final String TAG = "DownloadListAdapter";
ProgressDialog mProgressDialog;
private boolean isSDCardPresent;
File tieDir;
int downloadState[];
public DownloadListAdapter(Context ctx,
ArrayList<DownloadListDao> mDownloadList) {
this.ctx = ctx;
this.mDownloadList = mDownloadList;
downloadState = new int [mDownloadList.size()];
for(int i = 0; i < mDownloadList.size(); i++) {
downloadState[i] = 0;
}
tieDir = new File(Environment.getExternalStorageDirectory().toString()
+ "/tie");
}// Constructor
public int getCount() {
return this.mDownloadList.size();
}// getCount
public Object getItem(int position) {
return this.mDownloadList.get(position);
}// getItem
public long getItemId(int position) {
return 0;
}// getItemId
static class ViewHolder {
TextView txtTitle, txtTheme, txtDate;
ImageView imgDownload;
}// ViewHolder
ViewHolder holder;
public View getView(final int position, View convertView, ViewGroup parent) {
final String url = mDownloadList.get(position).getUrl();
if (convertView == null) {
convertView = LayoutInflater.from(parent.getContext()).inflate(
R.layout.downlist_adapter, null);
holder = new ViewHolder();
holder.txtTitle = (TextView) convertView
.findViewById(R.id.txtTitle);
holder.txtTheme = (TextView) convertView
.findViewById(R.id.txtTheme);
holder.txtDate = (TextView) convertView.findViewById(R.id.txtDate);
holder.imgDownload = (ImageView) convertView
.findViewById(R.id.imgDload);
holder.imgDownload.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
File mediaFile = null;
if (url != null && !url.equals("null") && !url.equals("")) {
String fileName = url.toString().substring(
url.toString().lastIndexOf("/") + 1,
url.toString().length());
mediaFile = new File(tieDir, fileName);
}
processFile(mediaFile, url, position);
int pos = (Integer)v.getTag();
downloadState[pos] = 1;
}
});
convertView.setTag(holder);
} else {
holder = (ViewHolder) convertView.getTag();
}
if (mDownloadList != null && mDownloadList.size() > 0) {
if (mDownloadList.get(position).getTitle() != null
&& !mDownloadList.get(position).getTitle().equals("null")
&& !mDownloadList.get(position).getTitle().equals("")) {
holder.txtTitle.setText(mDownloadList.get(position).getTitle());
}
if (mDownloadList.get(position).getTheme() != null
&& !mDownloadList.get(position).getTheme().equals("null")
&& !mDownloadList.get(position).getTheme().equals("")) {
holder.txtTheme.setText(mDownloadList.get(position).getTheme());
}
if (mDownloadList.get(position).getDate() != null
&& !mDownloadList.get(position).getDate().equals("null")
&& !mDownloadList.get(position).getDate().equals("")) {
holder.txtDate.setText(mDownloadList.get(position).getDate());
}
if (downloadState[position] == 1) {
holder.imgDownload.setImageDrawable(ctx.getResources()
.getDrawable(R.drawable.ic_dloaded));
} else {
holder.imgDownload.setImageDrawable(ctx.getResources()
.getDrawable(R.drawable.ic_dload));
}
}
holder.imgDownload.setTag(position);
return convertView;
}// getView
protected void downloadFile(String url, int position, String fileName) {
Log.v(TAG, "Preparing to download");
mProgressDialog = new ProgressDialog(ctx);
mProgressDialog.setMessage("Dowloading...");
mProgressDialog.setIndeterminate(false);
mProgressDialog.setMax(100);
mProgressDialog.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
isSDCardPresent = Environment.getExternalStorageState().equals(
Environment.MEDIA_MOUNTED);
if (!isSDCardPresent) {
noSDCardAlert(ctx);
} else {
if ((tieDir.exists()) && (tieDir != null)) {
if (NetworkConnection.isOnline(ctx)) {
if (tieDir.isDirectory()) {
Log.v(TAG, "if tie dir URL:::" + url);
new DownloadAudioAsync(ctx, position, fileName).execute(url);
}
} else {
((DownloadListActivity) ctx)
.OpenNetErrDialog("Please check your internet connection...");
}
} else {
boolean isDirectoryCreated = tieDir.mkdirs();
if (isDirectoryCreated) {
Log.v(TAG, "if tie not dir URL:::" + url);
if (NetworkConnection.isOnline(ctx)) {
new DownloadAudioAsync(ctx, position, fileName).execute(url);
} else {
((DownloadListActivity) ctx)
.OpenWiFiDialog("Please check your internet connection...");
}
}
}
}
}
private void noSDCardAlert(Context ctx) {
AlertDialog.Builder ad = new AlertDialog.Builder(ctx);
ad.setMessage("No sd card present..");
ad.setPositiveButton("OK", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
dialog.dismiss();
}
});
if (!((DownloadDetail) ctx).isFinishing()) {
ad.show();
}
}
public void OpenDialog(String messageID) {
final Dialog dialog = new Dialog(ctx,
android.R.style.Theme_Translucent_NoTitleBar);
dialog.setContentView(R.layout.dialog_base);
dialog.getWindow().getAttributes().windowAnimations = android.R.style.Animation_Dialog;
dialog.setCancelable(false);
TextView alertMessage = (TextView) dialog.findViewById(R.id.txtMessage);
Button btnOK = (Button) dialog.findViewById(R.id.btnOk);
btnOK.setText("Show");
alertMessage.setText(messageID);
dialog.show();
btnOK.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
dialog.dismiss();
}
});
}
protected void showPdf(File mediaFile) {
Intent intent = new Intent(Intent.ACTION_VIEW);
intent.setDataAndType(Uri.fromFile(mediaFile), "application/pdf");
intent.setFlags(Intent.FLAG_ACTIVITY_NO_HISTORY);
ctx.startActivity(intent);
}
public class DownloadAudioAsync extends AsyncTask<String, String, String> {
Context ctx;
int pos;
private ProgressDialog pd;
String fileName;
public DownloadAudioAsync(Context ctx, int pos, String fileName) {
this.ctx = ctx;
this.pos = pos;
this.fileName = fileName;
}
#Override
protected void onPreExecute() {
super.onPreExecute();
Log.v(TAG, "inside on pre execute");
pd = new ProgressDialog(ctx);
pd.setMessage("Downloading...\nPlease wait..");
pd.show();
}
#Override
protected String doInBackground(String... aurl) {
int count;
try {
Log.v(TAG,
"inside do in background with url::"
+ aurl[0].toString());
aurl[0] = aurl[0].replaceAll(" ", "%20");
URL url = new URL(aurl[0]);
URLConnection conexion = url.openConnection();
conexion.connect();
int lenghtOfFile = conexion.getContentLength();
fileName = URLDecoder.decode(fileName, "UTF-8");
InputStream input = new BufferedInputStream(url.openStream());
OutputStream output = new FileOutputStream(tieDir + "/"
+ fileName);
byte data[] = new byte[1024];
long total = 0;
while ((count = input.read(data)) != -1) {
total += count;
publishProgress("" + (int) ((total * 100) / lenghtOfFile));
output.write(data, 0, count);
}
output.flush();
output.close();
input.close();
} catch (Exception e) {
}
return null;
}
#Override
protected void onPostExecute(String unused) {
if (!((DownloadListActivity) ctx).isFinishing()) {
pd.dismiss();
updateView(pos);
}
}
private void updateView(int pos) {
View v = ((DownloadListActivity) ctx).menuListView.getChildAt(pos
- ((DownloadListActivity) ctx).menuListView
.getFirstVisiblePosition());
ImageView imgDloadBtn = (ImageView) v.findViewById(R.id.imgDload);
imgDloadBtn.setImageDrawable(ctx.getResources().getDrawable(
R.drawable.ic_dloaded));
notifyDataSetChanged();
}
}
private void processFile(File mediaFile, String url, int pos) {
if (url != null && !url.equals("null") && !url.equals("")) {
if (mediaFile != null) {
Log.v(TAG, "in processFile FileName " + mediaFile.getName());
Log.v(TAG, "in processFile Position " + pos);
if(!mediaFile.exists()) {
Log.v(TAG, "in processFile Media file doesn't exists");
downloadFile(url, pos, mediaFile.getName());
} else {
Log.v(TAG, "in processFile Media file exists");
try {
showPdf(mediaFile);
} catch (ActivityNotFoundException anfe) {
OpenDialog("PDF Reader is not installed on your device.");
}
}
}
}
}
}// DownloadAdapter
I had read this post for recycling the view(Thanks to Knickedi for in depth explaination). But, I can't figure out where is actual problem.
Issue with getview Method which keep recreating whenever you scroll your view, to handle exact position you have to play with setTag & getTag,check below few stackvoerflow answers to understand setTag & getTag:
Button in ListView using ArrayAdapter
Getting radio button value from custom list in android
and even store downloaded state into one booleanarray like below:
int boxState[];
within adapter constructor, set zero initially:
for (int i = 0; i < getData.size(); i++) {
boxState[i] = 0;
}
within adapter getview method:
holder.imgDownload.setTag(position);
Now you click on download button set value as 1 (Inside onclick of button):
pos = (Integer) v.getTag();
boxState[pos]=1;
At last when you scroll your view check condition into following way(put below code inside getview method):
if (boxState[position] == 0) {
holder.imgDownload.setImageDrawable(ctx.getResources()
.getDrawable(R.drawable.ic_dloaded)); //which aren't downloaded
} else {
holder.imgDownload.setImageDrawable(ctx.getResources()
.getDrawable(R.drawable.ic_dload)); // which are downloaded.
}

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

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.

Categories

Resources