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
Related
this is my custom adapter i use it for first time its work without repeat
public class MessageAdapter extends BaseAdapter {
private Activity activity;
private LayoutInflater inflater;
private List<MessageList> MessageList;
private final Context context;
public MessageAdapter(Activity activity, List<MessageList> MessageList, Context c) {
this.activity = activity;
this.MessageList = MessageList;
this.context = c;
}
#Override
public int getCount() {
return MessageList.size();
}
#Override
public Object getItem(int location) {
return MessageList.get(location);
}
#Override
public long getItemId(int position) {
return position;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
final ViewHolder mHolder;
final MessageList m = MessageList.get(position);
if (inflater == null)
inflater = (LayoutInflater) activity
.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
if (convertView == null) {
if (m.getDir().equals("left")) {
convertView = inflater.inflate(R.layout.left_message, null);
} else if (m.getDir().equals("right")) {
convertView = inflater.inflate(R.layout.right_message, null);
}
mHolder = new ViewHolder();
mHolder.message = (LinearLayout) convertView.findViewById(R.id.messages);
convertView.setTag(mHolder);
for(String message : m.getMessageList()){
TextView text = new MyTextView(activity);
LinearLayout.LayoutParams p = new LinearLayout.LayoutParams(LinearLayout.LayoutParams.WRAP_CONTENT, LinearLayout.LayoutParams.WRAP_CONTENT);
p.setMargins(0, 0, 0, 2);
text.setLayoutParams(p);
text.setText(message);
text.setPadding(8,8,8,8);
text.setTextSize(14f);
}
}
else {
mHolder = (ViewHolder) convertView.getTag();
}
Log.d("ffffffffffffffffff",""+m.getMessageList().size());
return convertView;
}
private class ViewHolder {
private LinearLayout message;
}
}
this is the result
but when i receive new data and i want to add it after do
adapter.notifyDataSetChanged();
its repeat the first data and add it to listView see result
we can see its repeat the data it must add new data i add it to arrayList not repeat old item on it i am sure about my ArrayList its right
at the end just lets see ho9w i add new data
first when its work without problem
private List<MessageList> Message_List = new ArrayList<MessageList>();
adapter = new MessageAdapter(this, Message_List, getApplicationContext());
message_list.setAdapter(adapter);
now i will add data for the first time
try {
JSONArray jsonarray = new JSONArray(data);
for (int i = 0; i < jsonarray.length(); i++) {
try {
JSONObject jsonobject = jsonarray.getJSONObject(i);
MessageList messageList = new MessageList();
String fname = jsonobject.getString("Fname");
int user_id = jsonobject.getInt("user_id");
String message = jsonobject.getString("message");
String date = jsonobject.getString("date");
String direction = jsonobject.getString("direction");
JSONArray MessageArry = jsonobject.getJSONArray("message");
ArrayList<String> ListMessage = new ArrayList<String>();
for (int j = 0; j < MessageArry.length(); j++) {
ListMessage.add((String) MessageArry.get(j));
}
messageList.setUser_id(user_id);
messageList.setMessage(message);
messageList.setDate(date);
messageList.setFname(fname);
messageList.setDir(direction);
messageList.setMessageList(ListMessage);
Message_List.add(messageList);
} catch (JSONException e) {
// JSON error
e.printStackTrace();
Toast.makeText(getApplicationContext(), "Json error: " + e.getMessage(), Toast.LENGTH_LONG).show();
}
}
adapter.notifyDataSetChanged();
} catch (JSONException e) {
// JSON error
e.printStackTrace();
Toast.makeText(getApplicationContext(), "Json error: " + e.getMessage(), Toast.LENGTH_LONG).show();
}
data used its
String data = "[ { \"direction\": \"left\",\"user_id\": \"50\",\"Fname\": \"Mohamed Mohamed\", \"status\": \"online\" , \"m_status\": \"sent\", \"date\": \"9:20\", \"message\": [\"hello\",\"hahhahah ok ok say hello\",\"-_-\",\"where are \",\"u ?\"] }, { \"direction\": \"right\",\"user_id\": \"50\",\"Fname\": \"Mustafa Naser\", \"status\": \"online\" , \"m_status\": \"sent\", \"date\": \"10:20\", \"message\": [\"hello\",\"what u want :/\",\"xD\"] }]";
when i get new data and i want to append it i add data like this
try {
JSONObject jsonobject1 = new JSONObject(json);
MessageList messageList = new MessageList();
String fname = jsonobject1.getString("name");
int user_id = jsonobject1.getInt("id");
String message = jsonobject1.getString("message");
String date = jsonobject1.getString("date");
String direction = jsonobject1.getString("direction");
ArrayList<String> ListMessage = new ArrayList<String>();
for (int j = 0; j < 1; j++) {
ListMessage.add(message);
}
messageList.setUser_id(user_id);
messageList.setMessage(message);
messageList.setDate(date);
messageList.setFname(fname);
messageList.setDir(direction);
messageList.setMessageList(ListMessage);
Message_List.add(messageList);
} catch (JSONException e) {
e.printStackTrace();
Toast.makeText(getApplicationContext(), "Json error: " + e.getMessage(), Toast.LENGTH_LONG).show();
}
adapter.notifyDataSetChanged();
data used its
{"message":"qqqqqqqq","id":50,"date":"2016-06-24 04:44:06","name":"medo medo","direction":"left","mode":0}
Each time you create a view, you put all messages inside, regardless of whether you have already shown them.
The problem is with the following loop:
for(String message : m.getMessageList()) {
// add a text view for each message
}
You need to find a way to check if the message has already been shown and add it to the layout only if it's not there.
I suggest you to do as follow:
In your adapterclass add this method:
public void updateList(List<MessageList> ){
this.MessageList = l;
notifyDataSetChanged();
}
And, after you fetch the new List, call the adapter.updateList(newList) method! It will update itself with the notifyDataSetChanged(); inside of the method.
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
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.
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());
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.