this is gridview that get image from json. I successfully with it. But when I get it from server it has a lot of images, that mean all images from server. I want to once load is 12 images.
How can I limit number of images to load?
Please help me briefly because I blind with lazy loading. If the code below not not enough. here is full source http://pastie.org/5583485
in this url, 50 is a number of image to load, i can limit number of image by this value whatever i want. but i just can load once time, so i can't load it more. this url provide image path as json.
String url = "http://xxx.xxx.xxx/card/all/50/0/?token=57LzEsmBeykLbDCD04wTgK9WWV2XjJY0XBdqVU0HQvjIdu5EtTWOT1IQ1AYNwxt6Q5bG6FG73uvzLQSDGAIezwc8VcopEp0s63uzbdVgLSfts0TLmuVDOgyfn4lX";
doInBackground of asynctask
public class DownloadJSONFileAsync extends AsyncTask<String, Void, Void> {
protected void onPreExecute() {
super.onPreExecute();
showDialog(DIALOG_DOWNLOAD_JSON_PROGRESS);
}
#Override
protected Void doInBackground(String... params) {
String url = "http://rest.mcolle.com/card/all/50/0/?token=57LzEsmBeykLbDCD04wTgK9WWV2XjJY0XBdqVU0HQvjIdu5EtTWOT1IQ1AYNwxt6Q5bG6FG73uvzLQSDGAIezwc8VcopEp0s63uzbdVgLSfts0TLmuVDOgyfn4lX";
JSONArray data = null;
try {
JSONObject jsonObject = new JSONObject(getJSONUrl(url));
MyArrList = new ArrayList<HashMap<String, Object>>();
HashMap<String, Object> map;
data = jsonObject.getJSONArray("data");
for (int i = 0; i < data.length(); i++) {
JSONObject c = data.getJSONObject(i);
map = new HashMap<String, Object>();
// Thumbnail Get ImageBitmap To Object
map.put("cardimage", (String) c.getString("cardimage"));
map.put("ImageThumBitmap",(Bitmap) loadBitmap(c.getString("cardimage")));
map.put("categoryid", (String) c.getString("categoryid"));
MyArrList.add(map);
}
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return null;
}
protected void onPostExecute(Void unused) {
ShowAllContent(); // When Finish Show Content
dismissDialog(DIALOG_DOWNLOAD_JSON_PROGRESS);
removeDialog(DIALOG_DOWNLOAD_JSON_PROGRESS);
}
ImageAdpater where i show image
public class ImageAdapter extends BaseAdapter {
private Context context;
private ArrayList<HashMap<String, Object>> MyArr = new ArrayList<HashMap<String, Object>>();
public ImageAdapter(Context c, ArrayList<HashMap<String, Object>> myArrList) {
context = c;
MyArr = myArrList;
}
public int getCount() {
return MyArr.size();
}
public Object getItem(int position) {
return position;
}
public long getItemId(int position) {
return position;
}
public View getView(int position, View convertView, ViewGroup parent) {
ViewHolder viewHolder;
viewHolder = new ViewHolder();
LayoutInflater inflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
if (convertView == null) {
convertView = inflater.inflate(R.layout.grid_item, null);
}
viewHolder.categoryCard = (ImageView) convertView.findViewById(R.id.category_card);
viewHolder.categoryCard.setImageResource(R.drawable.card_etc);
viewHolder.imageView = (ImageView) convertView.findViewById(R.id.imageView1);
try {
viewHolder.imageView.setImageBitmap((Bitmap) MyArr.get(position).get("ImageThumBitmap"));
} catch (Exception e) {
viewHolder.imageView.setImageResource(android.R.drawable.ic_menu_report_image);
}
return convertView;
}
}
you can use universal image loader ,
https://github.com/nostra13/Android-Universal-Image-Loader
Related
Ok, here we go. I have provided full mockup to avoid question why you don't do this that way, or this way.. So blue box is just inflated header that works, below the blue header I have Activity with ListView (green) populated with a LazyAdapter. Each row (white) have buttons that on click opens dialog (yellow) with another ListView populated with LazyAdapterTwo(black).
Problem is that I have null exception while setting second adapter from first, so I don't know where the problem is: listStatusComments.setAdapter(adapterStatusComments);
LazyAdapterStatus class
public class LazyAdapterStatus extends BaseAdapter {
private Activity activity;
private ArrayList<HashMap<String, String>> data;
private static LayoutInflater inflater=null;
public ImageLoader imageLoader;
ProgressDialog progressDialog;
DatabaseHandler db = new DatabaseHandler(activity);
ListView listStatusComments;
LazyAdapterStatusComments adapterStatusComments;
public LazyAdapterStatus(Activity a, ArrayList<HashMap<String, String>> d) {
activity = a;
data=d;
inflater = (LayoutInflater)activity.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
}
public int getCount() {
return data.size();
}
public Object getItem(int position) {
return position;
}
public long getItemId(int position) {
return position;
}
public View getView(final int position, View convertView, ViewGroup parent) {
View vi=convertView;
if(convertView==null)
vi = inflater.inflate(R.layout.activity_main_list_row, null);
final Dialog dialog = new Dialog(activity);
TextView title = (TextView)vi.findViewById(R.id.activityStatus);
ImageButton comments = (ImageButton)vi.findViewById(R.id.comments_ico);
comments.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
HashMap<String, String> item = new HashMap<String, String>();
item = data.get(position);
dialog.setContentView(R.layout.dialog_status_comment);
dialog.setTitle("Comment");
String statusId = item.get(MainActivity.STATUS_ID);
new GetStatusCommentsTask().execute(statusId);
}
});
HashMap<String, String> item = new HashMap<String, String>();
item = data.get(position);
title.setText(item.get(MainActivity.STATUS_TEXT));
return vi;
}
public class GetStatusCommentsTask extends AsyncTask<String, Void, ArrayList<StatusComments>> {
protected void onPreExecute() {
progressDialog = new ProgressDialog(activity);
progressDialog.setMessage("Loading");
progressDialog.setCancelable(true);
progressDialog.show();
}
protected ArrayList<StatusComments> doInBackground(String... arg0) {
String response = null;
try {
try {
HttpParams httpParameters = new BasicHttpParams();
HttpConnectionParams.setConnectionTimeout(httpParameters, 15000);
HttpConnectionParams.setSoTimeout(httpParameters, 20000);
HttpClient client = new DefaultHttpClient(httpParameters);
HttpPost postReq = new HttpPost();
postReq.setURI(new URI(com.seventy.in.util.ClientUrls.GET_STATUS_COMMENTS_URL));
ArrayList<NameValuePair> postParameters = new ArrayList<NameValuePair>();
postParameters.add(new BasicNameValuePair(
"status_id", arg0[0]));
UrlEncodedFormEntity formEntity = new UrlEncodedFormEntity(
postParameters);
postReq.setEntity(formEntity);
HttpResponse httpResponse = client.execute(postReq);
if (httpResponse.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {
response = NetworkUtil
.convertStreamToString(httpResponse.getEntity()
.getContent());
Log.i("RESP", response);
}
} catch (URISyntaxException e) {
e.printStackTrace();
} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
if (response != null && response != "") {
JSONObject myAwway = new JSONObject(response);
JSONArray jsonArrComments = myAwway.getJSONArray("status_comments");
ArrayList<StatusComments> commentsList = new ArrayList<StatusComments>();
for (int i = 0; i < jsonArrComments.length(); i++) {
StatusComments comment = StatusComments.fromJson(jsonArrComments
.getJSONObject(i));
if (comment.getCommentUserId() != null) {
commentsList.add(comment);
}
}
return commentsList;
}
else {
return null;
}
} catch (Exception e) {
e.printStackTrace();
return null;
}
}
#Override
protected void onPostExecute(ArrayList<StatusComments> result) {
super.onPostExecute(result);
progressDialog.dismiss();
final Dialog dialog = new Dialog(activity);
dialog.setContentView(R.layout.dialog_status_comment);
dialog.setTitle("Patka");
final ArrayList<HashMap<String, String>> postList = new ArrayList<HashMap<String, String>>();
for (int i = 0; i < result.size(); i++) {
HashMap<String, String> map = new HashMap<String, String>();
StatusComments e = result.get(i);
map.put(MainActivity.COMMENT_USER_ID, e.getCommentUserId());
map.put(MainActivity.KEY_IMAGE_URL, e.getUserImageUrl());
map.put(MainActivity.STATUS_TEXT, e.getCommentText());
postList.add(map);
}
listStatusComments = (ListView)dialog.findViewById(R.id.list);
adapterStatusComments=new LazyAdapterStatusComments(activity, postList);
listStatusComments.setAdapter(adapterStatusComments);
}
}
}
LazyAdapterStatusComments
public class LazyAdapterStatusComments extends BaseAdapter {
private Activity activity;
private ArrayList<HashMap<String, String>> data;
private static LayoutInflater inflater=null;
public ImageLoader imageLoader;
public LazyAdapterStatusComments(Activity a, ArrayList<HashMap<String, String>> d) {
activity = a;
data=d;
inflater = (LayoutInflater)activity.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
imageLoader=new ImageLoader(activity.getApplicationContext());
}
public int getCount() {
return data.size();
}
public Object getItem(int position) {
return position;
}
public long getItemId(int position) {
return position;
}
public View getView(int position, View convertView, ViewGroup parent) {
View vi=convertView;
if(convertView==null)
vi = inflater.inflate(R.layout.friends_list_row, null);
TextView title = (TextView)vi.findViewById(R.id.name); // title
TextView about = (TextView)vi.findViewById(R.id.item_description); // artist name
ImageView thumb_image=(ImageView)vi.findViewById(R.id.image_url); // thumb image
HashMap<String, String> song = new HashMap<String, String>();
song = data.get(position);
// Setting all values in listview
title.setText(song.get(MainActivity.STATUS_TEXT));
imageLoader.DisplayImage(song.get(MainActivity.KEY_IMAGE_URL), thumb_image);
return vi;
}
}
I found the problem. Code works perfectly, only I forgot to enter list element into the xml layout so listStatusComments = (ListView)dialog.findViewById(R.id.list); was searching for a element that was not there
I have pictures from my online database in my GridView and I want it in reverse order.
So I want when I add a new picture to my database to be the first in the GridView.
I tried to find an answer but there is nothing about it at stackoverflow.
This is my ListViewAdapter:
public class GetMovieImagesListViewAdapter extends BaseAdapter {
private JSONArray dataArray;
private Activity activity;
private static final String baseUrlForImage = "http://google.com";
private static LayoutInflater inflater = null;
public GetMovieImagesListViewAdapter(JSONArray jsonArray, Activity a){
this.dataArray = jsonArray;
this.activity = a;
inflater = (LayoutInflater) this.activity.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
}
#Override
public int getCount() {
return this.dataArray.length();
}
#Override
public Object getItem(int position){
return position;
}
#Override
public long getItemId(int position){
return position;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
final ListCell cell;
if (convertView == null) {
convertView = inflater.inflate(R.layout.get_images_from_movies_list_cell, null);
cell = new ListCell();
cell.MovieImages = (ImageView) convertView.findViewById(R.id.movie_images_id);
convertView.setTag(cell);
} else {
cell = (ListCell) convertView.getTag();
}
try {
JSONObject jsonObject = this.dataArray.getJSONObject(position);
String nameOfImage = jsonObject.getString("image");
String urlForImageInServer = baseUrlForImage + nameOfImage;
new AsyncTask<String, Void, Bitmap>(){
#Override
protected Bitmap doInBackground(String... params)
{
String url = params[0];
Bitmap icon = null;
try
{
InputStream in = new URL(url).openStream();
icon = BitmapFactory.decodeStream(in);
} catch (IOException e) {
e.printStackTrace();
}
return icon;
}
#Override
protected void onPostExecute(Bitmap result)
{
cell.MovieImages.setImageBitmap(result);
}
}.execute(urlForImageInServer);
} catch (JSONException e) {
e.printStackTrace();
}
return convertView;
}
private class ListCell{
private ImageView MovieImages;
}}
You could fetch each JSONObject by starting from the end of the array and working backwards to the start:
JSONObject jsonObject = this.dataArray.getJSONObject(getCount() - position - 1);
The result that you have received try to iterate through it in the reverse order.
Your Bitmap result data seems to be a single data that you get. I am expecting an array, or arraylist of data that you get in onPostExecute() method parameter while you query your online database.
Say for example, if you get the data in the form of onPostExecute(ArrayList result), then you can simply iterate the 'result' data in reverse order in order to populate your grid view in reverse order.
Check out Iterate arraylist in reverse order
I have a gridview on my activity ,I get data via json and add them to my adapter .
this is the code:
gridView = (GridView) findViewById(R.id.gridView);
contactList = new ArrayList<HashMap<String, String>>();
new GetContacts().execute();
private class GetContacts extends AsyncTask<Void, Void,ArrayList<HashMap<String, String>>> {
#Override
protected void onPreExecute() {
super.onPreExecute();
}
#Override
protected ArrayList<HashMap<String, String>> doInBackground(Void... arg0) {
Spots_tab1_json sh = new Spots_tab1_json();
String jsonStr = sh.makeServiceCall(url+page, Spots_tab1_json.GET);
ArrayList<HashMap<String, String>> dataC = new ArrayList<HashMap<String, String>>();
if (jsonStr != null) {
try {
JSONObject jsonObj = new JSONObject(jsonStr);
contacts = jsonObj.getJSONArray(TAG_CONTACTS);
if(contacts.length()<20)
loadmore=false;
for (int i = 0; i < contacts.length(); i++) {
JSONObject c = contacts.getJSONObject(i);
HashMap<String, String> contact = new HashMap<String, String>();
contact.put("id", new String(c.getString("id").getBytes("ISO-8859-1"), "UTF-8"));
contact.put("url", new String(c.getString("url").getBytes("ISO-8859-1"), "UTF-8"));
contact.put("text", new String(c.getString("text").getBytes("ISO-8859-1"), "UTF-8"));
dataC.add(contact);
}
} catch (JSONException e) {
goterr=true;
} catch (UnsupportedEncodingException e) {
goterr=true;
}
} else {
Log.v("this","mi;;");
goterr=true;
}
return dataC;
}
#Override
protected void onPostExecute(ArrayList<HashMap<String, String>> result) {
super.onPostExecute(result);
if(!isCancelled() && goterr==false){
if(ladap==null){
ladap=new ListAdapter(FistActiivty.this,result);
gridView.setAdapter(ladap);
}else{
ladap.addAll(result);
}
}else{
MyToast.makeText(FistActiivty.this, DariGlyphUtils.reshapeText(getResources().getString(R.string.problemload)));
}
}
}
public class ListAdapter extends BaseAdapter {
Activity activity;
public ArrayList<HashMap<String,String>> list;
public ListAdapter(Activity activity, ArrayList<HashMap<String, String>>list ) {
super();
this.activity=FistActiivty.this;
this.list=list;
}
public HashMap<String, String> geting(int position) {
return list.get(position);
}
public void addAll(ArrayList<HashMap<String, String>> result) {
if(this.list==null){
//this.list = new ArrayList<HashMap<String, String>>();
this.list =result;
}else{
this.list.addAll(result);
}
//list.addAll(result);
notifyDataSetChanged();
}
public int getCount() {
return list.size();
}
public Object getItem(int position) {
return list.get(position);
}
public long getItemId(int arg0) {
return 0;
}
private class ViewHolder {
TextView Message;
ImageView img ;
}
public View getView(int position, View convertView, ViewGroup parent) {
ViewHolder holder;
LayoutInflater inflater = activity.getLayoutInflater();
if (convertView == null) {
convertView = inflater.inflate(R.layout.row_grid, null);
holder = new ViewHolder();
holder.Message = (TextView) convertView.findViewById(R.id.text);
holder.Message.setTypeface(typeface);
holder.img=(ImageView)convertView.findViewById(R.id.image);
convertView.setTag(holder);
} else {
holder = (ViewHolder) convertView.getTag();
}
item = list.get(position);
String text = item.get("text");
Log.v("this","11"+ text);
holder.Message.setText(text);
String imgurl = item.get("url");
if(imgurl.length()>5)
imageLoader.displayImage(imgurl, holder.img,options, imageListener);
else
holder.img.setImageDrawable(getResources().getDrawable(R.drawable.noimage));
return convertView;
}
ok , at this step, I get data from internet via json , post it to ListAdapter and add them to my gridview and no problem .
in listview ,we can add ask for more data when we reach at the bottom of listview , But how can I call function to add more items whwen I reach at the end of gridview ?
The best way to implement this is via using PullToRefreshLibrary here. Import that library to your workspace and implement setOnRefreshListener with onPullUpToRefresh. This will indicate the end of the list. You can set a request to the server to get more data to view when the end of the list is reached.
On the server, you can implement pagination to load the next set of data every time you reach the end of the list.
I hope this will help you.
i've a listview on my activity , when I reach the end of listview , it calls async and it getting new data using json .
this is the async and baseAdaper codes :
ListAdapter ladap;
private class GetContacts AsyncTask<Void, Void,ArrayList<HashMap<String, String>>> {
#Override
protected Void doInBackground(Void... arg0) {
Spots_tab1_json sh = new Spots_tab1_json();
String jsonStr = sh.makeServiceCall(url + page, Spots_tab1_json.GET);
ArrayList<HashMap<String, String>> dataC = new ArrayList<HashMap<String, String>>();
if (jsonStr != null) {
try {
JSONObject jsonObj = new JSONObject(jsonStr);
contacts = jsonObj.getJSONArray(TAG_CONTACTS);
for (int i = 0; i < contacts.length(); i++) {
JSONObject c = contacts.getJSONObject(i);
String id = new String(c.getString("id").getBytes("ISO-8859-1"), "UTF-8");
String dates = new String(c.getString("dates").getBytes("ISO-8859-1"), "UTF-8");
String price = new String(c.getString("gheymat").getBytes("ISO-8859-1"), "UTF-8");
HashMap<String, String> contact = new HashMap<String, String>();
contact.put("id", id);
contact.put("dates", dates);
contact.put("price", price);
dataC.add(contact);
}
}
} catch (JSONException e) {
goterr = true;
} catch (UnsupportedEncodingException e) {
goterr = true;
}
} else {
goterr = true;
}
return dataC;
}
#Override
protected void onPostExecute(ArrayList<HashMap<String, String>> result) {
super.onPostExecute(result);
if (!isCancelled() && goterr == false) {
if(ladap==null){
ladap=new ListAdapter(MainActivity.this,result);
lv.setAdapter(ladap);
}else{
ladap.addAll(result);
ladap.notifyDataSetChanged();
}
}
}
public class ListAdapter extends BaseAdapter {
Activity activity;
public ArrayList<HashMap<String, String>> list;
public ListAdapter(Activity activity,ArrayList<HashMap<String, String>> list) {
super();
this.activity = (Activity) activity;
this.list = list;
}
public void addAll(ArrayList<HashMap<String, String>> result) {
Log.v("this",result.size()+" resultsize");
this.list = result;
notifyDataSetChanged();
}
public int getCount() {
return contactList.size();
}
public Object getItem(int position) {
return contactList.get(position);
}
public long getItemId(int arg0) {
return 0;
}
private class ViewHolder {
TextView title,price;
ImageView img ;
//RelativeLayout rl;
}
public View getView(int position, View convertView, ViewGroup parent) {
ViewHolder holder;
LayoutInflater inflater = activity.getLayoutInflater();
if (convertView == null) {
convertView = inflater.inflate(R.layout.item, null);
holder = new ViewHolder();
holder.title = (TextView) convertView.findViewById(R.id.title);
holder.price = (TextView) convertView.findViewById(R.id.price);
convertView.setTag(holder);
} else {
holder = (ViewHolder) convertView.getTag();
}
item = contactList.get(position);
holder.price.setText(item.get("price"));
return convertView;
}
}
I logged here , when I reach the end of listView , it calls addAll and it returns new 30 items buy it doesn't added to listview , I don't know why .
First of all you have already notify your list view when you call addAll() so this code no longer required please remove from your code :
ladap.notifyDataSetChanged();
Add new data to list view data holder instead of assign new data to list view data holder :
public void addAll(ArrayList<HashMap<String, String>> result) {
Log.v("this",result.size()+" resultsize");
this.list = result;
notifyDataSetChanged();
}
Replace with :
public void addAll(ArrayList<HashMap<String, String>> result) {
Log.v("this",result.size()+" resultsize");
if(list==null){
list = new ArrayList<HashMap<String, String>>();
}
list.addAll(result)
notifyDataSetChanged();
}
Try to change this :
public void addAll(ArrayList<HashMap<String, String>> result) {
Log.v("this",result.size()+" resultsize");
this.list = result;
notifyDataSetChanged();
}
To :
public void addAll(ArrayList<HashMap<String, String>> result) {
Log.v("this",result.size()+" resultsize");
for(int i = 0;i < result.size(); i++)
list.add(result.get(i));
//notifyDataSetChanged(); //no need to call again here
}
The point is, i think this.list = result; will delete the old items before adding a new item.
I'm facing problem with setting up the items in ListView, I'm using an Async task for updating the items. Here is what I have done so far.
Async Task onPostExecute()
#Override
protected void onPostExecute(String result) {
notifyList = new ArrayList<HashMap<String, String>>();
try {
JSONObject rootObj = new JSONObject(result);
JSONObject jSearchData = rootObj.getJSONObject("notifications");
int maxlimit = 5;
for (int i = 0; i < maxlimit; i++) {
JSONObject jNotification0 = jSearchData.getJSONObject(""
+ i + "");
String text = jNotification0.getString("text");
String amount = jNotification0.getString("amount");
String state = jNotification0.getString("state");
System.out.println(text);
System.out.println(amount);
System.out.println(state);
HashMap<String, String> map = new HashMap<String, String>();
map.put("text", text);
map.put("amount", amount);
notifyList.add(map);
}
if (notification_adapter != null) {
notification_list.setAdapter(new CustomNotificationAdapter(
notifyList));
}
} catch (Exception e) {
e.printStackTrace();
}
}
Here is my CustomNotification class which extends BaseAdapter
public class CustomNotificationAdapter extends BaseAdapter {
public ArrayList<HashMap<String, String>> notificationData = new ArrayList<HashMap<String, String>>();
public CustomNotificationAdapter(
ArrayList<HashMap<String, String>> notificationData) {
this.notificationData = notificationData;
}
#Override
public int getCount() {
return notificationData.size();
}
#Override
public Object getItem(int position) {
return notificationData.get(position).get("text").toString();
}
#Override
public long getItemId(int position) {
return notificationData.get(position).get("text").hashCode();
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
View vi = convertView;
LayoutInflater inflater = getLayoutInflater();
vi = inflater.inflate(R.layout.custom_notification_list, null);
TextView notificationText = (TextView) findViewById(R.id.notificationText);
TextView notificationAmount = (TextView) findViewById(R.id.notificationPoint);
notificationText
.setText(notificationData.get(position).get("text"));
notificationAmount.setText(notificationData.get(position).get(
"amount"));
return vi;
}
}
NotificationAdapter class which extends SimpleAdapter
public class NotificationAdapter extends SimpleAdapter {
List<Map<String, String>> cur_list = new ArrayList<Map<String, String>>();
public NotificationAdapter(Context context,
List<? extends Map<String, ?>> data, int resource, String[] from,
int[] to) {
super(context, data, resource, from, to);
}
}
I'm able to get all the data from JSONResponse but I'm not able to show it on the list. What am I missing?
Any kind of help will be appreciated.
Try replacing this:
if (notification_adapter != null) {
notification_list.setAdapter(new CustomNotificationAdapter(
notifyList));
}
with this:
notification_adapter = new CustomNotificationAdapter(notifyList);
notification_list.setAdapter(notification_adapter);
This will set the adapter to the new JSON data even if notification_adapter was previously null.
Call notification_adapter.notifyDataSetChanged() after updating your adapter's data or remove the if (notification_adapter != null) {if you want it easy and bad.
to update your data:
public void updateData(ArrayList<HashMap<String, String> notificationData){
this.notificationData = notificationData;
this.notifyDataSetChanged();
}
Inside your adapter, and call it like: notification_adapter.updateData(notifyList);