We are working on a project where data is coming from webservice.I am dispalying that data in listview.The data icludes images as image path.I have displayed all the iformation but i couldt display the image.How to display the images from webservices.
my code is:
package com.example.doctreachapp;
import java.util.ArrayList;
import java.util.HashMap;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import com.example.doctreachapp.JSONParser;
import com.example.doctreachapp.R;
import android.app.ListActivity;
import android.app.ProgressDialog;
import android.content.Context;
import android.graphics.Bitmap;
import android.os.AsyncTask;
import android.os.Bundle;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.webkit.WebView;
import android.widget.BaseAdapter;
import android.widget.ImageView;
import android.widget.ListAdapter;
import android.widget.ListView;
import android.widget.SimpleAdapter;
import android.widget.TextView;
public class GeneralHospitals extends ListActivity {
private Context context;
private static String url = "my Url";
// private static final String ID = "ID";
String TAG_user_detail = "DentalHospitals";
private static final String Img = "Img";
private static final String Location = "Location";
private static final String URL = "URL";
private static final String Name = "Name";
private static final String Distance = "Distance";
String imagestack;
Bitmap image;
JSONArray user_detail_jsonarray = null;
ArrayList<HashMap<String, String>> jsonlist = new ArrayList<HashMap<String, String>>();
ListView lv;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main2);
lv = (ListView) findViewById(android.R.id.list);
new ProgressTask().execute();
}
private class ProgressTask extends AsyncTask<String, Void, Boolean> {
#Override
protected void onPostExecute(final Boolean success) {
setListView();
// select single ListView item
// lv = getListView();
}
protected Boolean doInBackground(final String... args) {
JSONParser jParser = new JSONParser();
// get JSON data from URL
// JSONObject jobject = new JSONObject(result);
JSONObject json = jParser.getJSONFromUrl(url);
Log.d("json", json.toString());
try {
user_detail_jsonarray = json.getJSONArray("DentalHospitals");
Log.d("jsonarray", user_detail_jsonarray.toString());
} catch (JSONException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
for (int i = 0; i < user_detail_jsonarray.length(); i++) {
try {
JSONObject c = user_detail_jsonarray.getJSONObject(i);
String img = c.getString(Img);
String name = c.getString(Name);
String loc = c.getString(Location);
String url = c.getString(URL);
String dis = c.getString(Distance);
HashMap<String, String> map = new HashMap<String, String>();
// Add child node to HashMap key & value
map.put(Img, img);
map.put(Name, name);
map.put(Location, loc);
map.put(URL, url);
map.put(Distance, dis);
jsonlist.add(map);
// Log.d("list",jsonlist);
} catch (JSONException e) {
e.printStackTrace();
}
Log.d("JSONList", jsonlist.toString());
}
return true;
}
}
public class CustomListAdapter extends BaseAdapter {
private ArrayList<HashMap<String, String>> listData;
private LayoutInflater layoutInflater;
public CustomListAdapter(Context context,
ArrayList<HashMap<String, String>> jsonlist) {
this.listData = jsonlist;
layoutInflater = LayoutInflater.from(context);
}
#Override
public int getCount() {
return listData.size();
}
#Override
public Object getItem(int position) {
return listData.get(position);
}
#Override
public long getItemId(int position) {
return position;
}
public View getView(int position, View convertView, ViewGroup parent) {
ViewHolder holder;
if (convertView == null) {
convertView = layoutInflater.inflate(R.layout.list_item, null);
holder = new ViewHolder();
holder.Name = (TextView) convertView
.findViewById(R.id.name);
holder.Location = (TextView) convertView
.findViewById(R.id.loc);
holder.URL = (TextView) convertView
.findViewById(R.id.url);
holder.Distance = (TextView) convertView
.findViewById(R.id.dis);
holder.Img = (ImageView) convertView
.findViewById(R.id.image);
convertView.setTag(holder);
} else {
holder = (ViewHolder) convertView.getTag();
}
//System.out.println(listData.get(position).get("Img"));
System.out.println(listData.get(position).get("Name"));
holder.Img.setImageURI(listData.get(position).get("Img"));
holder.Name.setText(listData.get(position).get("Name"));
holder.Location.setText(listData.get(position).get("Location"));
holder.URL.setText(listData.get(position).get("URL"));
holder.Distance.setText(listData.get(position).get("Distance"));
//WebView image = holder.Img;
//imagestack = listData.get(position).get("Img");
//image = BitmapFactory.decodeStream((listData.get(position).get("Img")).openStream());
Log.d("image",imagestack);
return convertView;
}
}
public static class ViewHolder {
ImageView Img;
TextView Location;
TextView Name;
TextView URL;
TextView Distance;
}
public void setListView() {
// TODO Auto-generated method stub
CustomListAdapter adapter = new CustomListAdapter(this, jsonlist);
Log.d("ABCD", "" + lv.getVisibility());
lv.setAdapter(adapter);
}
}
Please help me.
Write below code in your getView() where you have initialized holder.Img ImageView
new DownloadImageTask(holder.Img)
.execute(listData.get(position).get("Img"));
Below is the AsyncTask to download the image and to display it in the ImageView
private class DownloadImageTask extends AsyncTask<String, Void, Bitmap> {
ImageView bmImage;
public DownloadImageTask(ImageView bmImage) {
this.bmImage = bmImage;
}
#Override
protected void onPreExecute() {
super.onPreExecute();
}
protected Bitmap doInBackground(String... urls) {
String urldisplay = urls[0];
Bitmap mIcon11 = null;
try {
InputStream in = new java.net.URL(urldisplay).openStream();
mIcon11 = BitmapFactory.decodeStream(in);
} catch (Exception e) {
Log.e("Error", e.getMessage());
e.printStackTrace();
}
return mIcon11;
}
protected void onPostExecute(Bitmap result) {
bmImage.setImageBitmap(result);
}
}
If you have small number of items in the ListView then use the above code else it recommendable to use LazyList .
Related
i was tring to load image using url.a single url is working properly. but i need to add a few more images to this page.i need to add this image s to a list view.pls tell me how can i add a string array to this code.
import java.io.IOException;
import org.apache.http.HttpResponse;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.protocol.HTTP;
import org.apache.http.util.EntityUtils;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import android.app.Activity;
import android.content.Context;
import android.os.AsyncTask;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.TextView;
public class FareCrd extends Activity {
String image_url="http://movito.nervov.com/img/ace-hd.png";
String[] mString ={"http://movito.nervov.com/img/ace-hd.png",
"http://movito.nervov.com/img/Movito_Logo_M.png"};
JSONArray jsonary;
ListView list;
private Activity activity;
private String[] data;
private static View inflater=null;
//private String[] mStrings={"http://movito.nervov.com/img/ace-hd.png"};
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_fare_crd);
list=(ListView)findViewById(R.id.farelist);
new ServConn().execute();
}
private void parsedata(String data){
//System.out.println(data);
try {
JSONObject json = new JSONObject(data);
jsonary = json.getJSONArray("data");
ListView list = (ListView) findViewById(R.id.farelist);
list.setAdapter(new DriverOrderList(getApplicationContext(),
R.layout.farecrd, new JSONObject[jsonary.length()]));
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
private class DriverOrderList extends ArrayAdapter<JSONObject> {
int listViewResource;
public DriverOrderList(Context context, int resource, JSONObject[] s) {
super(context, resource, s);
listViewResource = resource;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
View row = ((LayoutInflater) getSystemService(Context.LAYOUT_INFLATER_SERVICE)).inflate(listViewResource, parent, false);
ImageLoader imgLoader = new ImageLoader(getApplicationContext());
JSONObject rowdata = new JSONObject();
int loader = R.drawable.stub;
try {
rowdata = jsonary.getJSONObject(position);
System.out.println(rowdata);
ImageLoader imgLoader1 = new ImageLoader(getApplicationContext());
ImageView img=(ImageView) row.findViewById(R.id.imgid);
imgLoader.DisplayImage(image_url, loader, img);
TextView nameTxt = (TextView) row.findViewById(R.id.truckname);
TextView idTxt = (TextView) row.findViewById(R.id.id);
TextView minrttv =(TextView) row.findViewById(R.id.minimumRate);
TextView kmrttxt =(TextView) row.findViewById(R.id.kilometerRate);
TextView mindurtv=(TextView) row.findViewById(R.id.minimumDuration);
TextView freewatintim = (TextView) row.findViewById(R.id.freeWaitingTime);
TextView minuterttxt =(TextView) row.findViewById(R.id.minuteRate);
TextView watingchrttv =(TextView)row.findViewById(R.id.waitingCharge);
double freewt=(Double) rowdata.get("freeWaitingTime");
double kmratetxt=(Double) rowdata.get("kilometerRate");
double mindurtxt=(Double) rowdata.get("minimumDuration");
double mindur= mindurtxt/60;
double minkmrttxt=(Double) rowdata.get("minimumKilometer");
double minrttxt=(Double) rowdata.get("minimumRate");
double mintrate=(Double) rowdata.get("minuteRate");
double minutrat=mintrate/60;
double watingchrtxt=(Double) rowdata.get("waitingCharge");
double waitchgunittxt=(Double) rowdata.get("waitingChargeUnit");
nameTxt.setText(rowdata.getString("truckModel"));
minrttv.setText("Rs."+minrttxt+" /-");
kmrttxt.setText("Rs."+kmratetxt+"/km after "+minkmrttxt+"km");
mindurtv.setText("first"+mindur+"hr and "+minkmrttxt+"km");
//minuterttxt.setText(minutrat+"/-");
freewatintim.setText("first "+freewt+"min free");
watingchrttv.setText("RS"+watingchrtxt+"after every "+waitchgunittxt+"min");
}
catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return row;
}
}
private class ServConn extends AsyncTask<String, Void, String> {
#Override
protected String doInBackground(String... params) {
// TODO Auto-generated method stub
System.out.println("do in backgrnd");
HttpClient httpclient = new DefaultHttpClient();
HttpGet httpget = new HttpGet("http://movito.nervov.com/v1/trucks/miniTruckCategories");
httpget.setHeader(HTTP.CONTENT_TYPE, "application/json");
String replyString = "";
try {
HttpResponse response = httpclient.execute(httpget);
replyString = EntityUtils.toString(response
.getEntity());
} catch (ClientProtocolException e) {
System.out.println("ex: " + e);
} catch (IOException e) {
System.out.println("e: " + e);
}
return replyString;
}
#Override
protected void onPostExecute(String result) {
// TODO Auto-generated method stub
super.onPostExecute(result);
System.out.println(result);
result = "{\"data\":"+result+"}";
parsedata(result);
}
#Override
protected void onPreExecute() {}
#Override
protected void onProgressUpdate(Void... values) {}
}
}
Try to use Glide libreries instead od picasso .It might help full for you.Please look at following link which might help you out.
http://inthecheesefactory.com/blog/get-to-know-glide-recommended-by-google/en
try this code I am using Picasso library to populate ImageView,
if you are using android studio add this library using following code into your gradle file
compile 'com.squareup.picasso:picasso:2.5.2'
use following code,
It is complete example of how you can make a custom ListView, I didn't include code where you have to get he JSON data from WebService as i didn't want to make the code complicated, I will write a separate code where i will show how to read the data you are interested in.
XML
<LinearLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical">
<ListView
android:id="#+id/CustomListViewActivity_listView"
android:layout_width="match_parent"
android:layout_height="wrap_content" />
</LinearLayout>
single_item.xml layout
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="50dp"
android:orientation="horizontal">
<TextView
android:id="#+id/single_item_textView"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_margin="4dp"
android:layout_weight="0.5"
android:text="New Text" />
<ImageView
android:id="#+id/single_item_imageView"
android:layout_width="0dp"
android:layout_height="match_parent"
android:layout_margin="4dp"
android:layout_weight="0.5" />
</LinearLayout>
Code
public class CustomListViewActivity extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_custom_list_view);
ArrayList<SingleItem> singleItems = new ArrayList<>();
singleItems.add(new SingleItem("http://movito.nervov.com/img/ace-hd.png","first Text"));
singleItems.add(new SingleItem("http://movito.nervov.com/img/Movito_Logo_M.png","Second Text"));
singleItems.add(new SingleItem("http://movito.nervov.com/img/ace-hd.png","third Text"));
singleItems.add(new SingleItem("http://movito.nervov.com/img/Movito_Logo_M.png","fourth Text"));
ListView listView = (ListView)findViewById(R.id.CustomListViewActivity_listView);
MyAdapter adapter = new MyAdapter(getApplicationContext(), R.layout.single_item,singleItems);
listView.setAdapter(adapter);
}
private class MyAdapter extends ArrayAdapter {
private ArrayList<SingleItem> singleItems;
private LayoutInflater layoutInflater;
private Context context;
private View single_View;
public MyAdapter(Context context, int resource, ArrayList<SingleItem> singleItems) {
super(context, resource, singleItems);
this.context = context;
this.singleItems = singleItems;
layoutInflater = LayoutInflater.from(this.context);
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
View row = convertView;
ViewHolder holder = null;
if (row == null) {
row = layoutInflater.inflate(R.layout.single_item, parent, false);
holder = new ViewHolder();
holder.textView = (TextView) row.findViewById(R.id.single_item_textView);
holder.imageView = (ImageView) row.findViewById(R.id.single_item_imageView);
row.setTag(holder);
} else {
holder = (ViewHolder) row.getTag();
}
final SingleItem singleItem = singleItems.get(position);
holder.textView.setText("" + singleItem.getText());
Picasso.with(context).load(""+singleItem.getUrl()).into(holder.imageView);
return row;
}
private class ViewHolder {
// Instance Variable (state or data)
TextView textView;
ImageView imageView;
}
}
public class SingleItem {
private String url;
private String text;
public SingleItem() {
}
public SingleItem(String url, String text) {
this.url = url;
this.text = text;
}
public String getUrl() {
return url;
}
public void setUrl(String url) {
this.url = url;
}
public String getText() {
return text;
}
public void setText(String text) {
this.text = text;
}
}
}
Output
As you will see the loading the images from the URL provided to the appropriate ImageView is taken care by Picasso, do make sure you add the permission for the internet in the AndroidManifest.xml
<uses-permission android:name="android.permission.INTERNET" />
I have a custom adapter set. When the Listview has more than 4-5 views, the app stops working and gives null object in the set textview. Whereas this code works fine when i have 2-3 views in the Listview.
I have commented the textview which gets the error. Please have a loook ! Thank you
Update: It seems that if i scroll fast, the error is thrown. !!
Update 2: As suggested by #Piotr, it works fine until , when i scroll down to the end and scroll up , it converts the view list_item_header to list_item. So all the view becomes list_item.
Error:
FATAL EXCEPTION: main
Process: edu.gannon.gannonknightnews, PID: 3083
java.lang.NullPointerException: Attempt to invoke virtual method 'java.lang.CharSequence android.widget.TextView.getText()' on a null object reference
at edu.gannon.gannonknightnews.MenuFragment$GetNews$CustomAdapter.getView(MenuFragment.java:197)
import android.annotation.TargetApi;
import android.app.ProgressDialog;
import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.AsyncTask;
import android.os.Build;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.TextView;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.HashMap;
public class MenuFragment extends Fragment {
private ProgressDialog pDialog;// Progress Dialog
ListView newsList;
String my_url;
ArrayList<HashMap<String, String>> postList; //Declare Array
private static String url = "http://wangeltmg.com/GKN_ADMIN/GET_POSTS/";
GetNews.CustomAdapter CA;
// JSON Node names
private static final String TAG_ID = "id";
private static final String POST_ALLPOSTS = "posts";
private static final String POST_ID = "ID";
private static final String POST_TITLE = "post_title";
private static final String POST_CONTENT = "post_content";
private static final String GUID = "guid";
#TargetApi(Build.VERSION_CODES.HONEYCOMB)
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
// Inflate the layout for this fragment
View view = inflater.inflate(R.layout.home, container, false);
newsList = (ListView) view.findViewById(R.id.homeListView);
TextView topic = (TextView) view.findViewById(R.id.topic);
postList = new ArrayList<HashMap<String, String>>();
//Get arguments
Bundle args = getArguments();
String mytopic = args.getString("Topic");
getActivity().getActionBar().setTitle("GannonKnightNews");
//Set topic
topic.setText(mytopic.toUpperCase());
//Execute getContacts
new GetNews().execute();
return view;
}
//Async Task
private class GetNews extends AsyncTask<Void, Void, Void> {
#Override
protected void onPreExecute() {
super.onPreExecute();
// Showing progress dialog
pDialog = new ProgressDialog(getActivity());
pDialog.setMessage("Please wait...");
pDialog.setCancelable(false);
pDialog.show();
}
#Override
protected Void doInBackground(Void... arg0) {
// Creating service handler class instance
ServiceHandler sh = new ServiceHandler();
// Making a request to url and getting response
String jsonStr = sh.makeServiceCall(url, ServiceHandler.GET);
Log.d("Strings", "Checking Json");
Log.d("Response: ", "> " + jsonStr);
if (jsonStr != null) {
try {
JSONObject jsonObj = new JSONObject(jsonStr);
// contacts JSONArray
JSONArray posts = null;
// Getting JSON Array node
posts = jsonObj.getJSONArray(POST_ALLPOSTS);
// looping through All Contacts
for (int i = 0; i < posts.length(); i++) {
JSONObject c = posts.getJSONObject(i);
Log.d("Post->",posts.getJSONObject(i).toString());
String id = c.getString(POST_ID);
Log.d("Post->ID",id);
String post_title = c.getString(POST_TITLE);
String post_content = c.getString(POST_CONTENT);
String guid = c.getString(GUID);
Log.d("GUID->",guid);
//String gender = c.getString(TAG_GENDER);
// tmp hashmap for single post
HashMap<String, String> post = new HashMap<String, String>();
// adding each child node to HashMap key => value
post.put(POST_ID, id);
post.put(POST_TITLE, post_title);
post.put(POST_CONTENT, post_content);
post.put(GUID, guid);
post.put("ListCount",String.valueOf(i));
// adding contact to contact list
postList.add(post);
}
} catch (JSONException e) {
e.printStackTrace();
}
} else {
Log.e("ServiceHandler", "Couldn't get any data from the url");
}
return null;
}
#Override
protected void onPostExecute(Void result) {
super.onPostExecute(result);
// Dismiss the progress dialog
if (pDialog.isShowing())
pDialog.dismiss();
// Updating parsed JSON data into ListView
/*
ListAdapter adapter = new SimpleAdapter(getActivity(), postList, R.layout.list_item,
new String[] { POST_TITLE,POST_CONTENT, GUID },
new int[] {R.id.email, R.id.mobile, R.id.guid });
newsList.setAdapter(adapter);
*/
CA = new CustomAdapter( getActivity(), R.layout.list_item, postList);
newsList.setAdapter(CA);
}
public class CustomAdapter extends ArrayAdapter<HashMap<String, String>> {
private final ArrayList<HashMap<String, String>> objects;
public CustomAdapter(Context context, int resource, ArrayList<HashMap<String, String>> objects) {
//something is wrong with super
super(context, resource, objects);
this.objects = objects;
}
public View getView(int position, View convertView, ViewGroup Parent){
//convertView = new ImageView();
if(convertView == null){
LayoutInflater inflater = (LayoutInflater) getContext().getSystemService(Context.LAYOUT_INFLATER_SERVICE);
convertView = inflater.inflate(R.layout.list_item,null);
}
android.widget.ImageView postImage = (android.widget.ImageView) convertView.findViewById(R.id.img);
int getListPos = newsList.getFirstVisiblePosition();
//i set the count starting 0 and saved in the hashmap array
//to compare the first result with the first position of listview
int count = Integer.parseInt(objects.get(position).get("ListCount"));
my_url = objects.get(position).get(GUID);
if(getListPos == count) {
LayoutInflater inflater = (LayoutInflater) getContext().getSystemService(Context.LAYOUT_INFLATER_SERVICE);
convertView = inflater.inflate(R.layout.list_item_header,null);
TextView HeaderText = (TextView) convertView.findViewById(R.id.headertext);
TextView HeaderContent = (TextView) convertView.findViewById(R.id.headercontent);
HeaderText.setText(objects.get(position).get(POST_TITLE).toUpperCase());
HeaderContent.setText(objects.get(position).get(POST_CONTENT));
if(objects.get(position).get(GUID).equals("NULL")) {
postImage.setImageResource(R.drawable.default_bg);
}else{
new DownloadImageTask((ImageView) convertView.findViewById(R.id.img)).execute(my_url);
}
}
else{
//CHoose list item
//************************************************
//THe problem is in this textview which gives null object reference error
TextView thisview = (TextView) convertView.findViewById(R.id.email);
Log.d("Title", String.valueOf(thisview.getText()));
TextView postContent = (TextView) convertView.findViewById(R.id.mobile);
thisview.setText(objects.get(position).get(POST_TITLE).toUpperCase());
postContent.setText(objects.get(position).get(POST_CONTENT));
if(objects.get(position).get(GUID).equals("NULL")) {
postImage.setImageResource(R.drawable.default_bg);
}else{
new DownloadImageTask((ImageView) convertView.findViewById(R.id.img)).execute(my_url);
}
}
return convertView;
}
}//Custom Adapter
}//END getnews Async Task
private class DownloadImageTask extends AsyncTask<String, Void, Bitmap> {
ImageView bmImage;
public DownloadImageTask(ImageView bmImage) {
this.bmImage = bmImage;
}
protected Bitmap doInBackground(String... urls) {
String urldisplay = urls[0];
Bitmap mIcon11 = null;
try {
InputStream in = new java.net.URL(urldisplay).openStream();
mIcon11 = BitmapFactory.decodeStream(in);
} catch (Exception e) {
Log.e("Error", e.getMessage());
e.printStackTrace();
}
return mIcon11;
}
protected void onPostExecute(Bitmap result) {
bmImage.setImageBitmap(result);
}
}//
}
try this:
public View getView(int position, View convertView, ViewGroup Parent)
{
int getListPos = newsList.getFirstVisiblePosition();
int count = Integer.parseInt(objects.get(position).get("ListCount"));
my_url = objects.get(position).get(GUID);
if (getListPos == count)
{
LayoutInflater inflater = (LayoutInflater) getContext().getSystemService(Context.LAYOUT_INFLATER_SERVICE);
convertView = inflater.inflate(R.layout.list_item_header, null);
TextView HeaderText = (TextView) convertView.findViewById(R.id.headertext);
TextView HeaderContent = (TextView) convertView.findViewById(R.id.headercontent);
HeaderText.setText(objects.get(position).get(POST_TITLE).toUpperCase());
HeaderContent.setText(objects.get(position).get(POST_CONTENT));
if (objects.get(position).get(GUID).equals("NULL"))
{
postImage.setImageResource(R.drawable.default_bg);
}
else
{
new DownloadImageTask((ImageView) convertView.findViewById(R.id.img)).execute(my_url);
}
}
else
{
LayoutInflater inflater = (LayoutInflater) getContext().getSystemService(Context.LAYOUT_INFLATER_SERVICE);
convertView = inflater.inflate(R.layout.list_item, null);
TextView thisview = (TextView) convertView.findViewById(R.id.email);
Log.d("Title", String.valueOf(thisview.getText()));
TextView postContent = (TextView) convertView.findViewById(R.id.mobile);
thisview.setText(objects.get(position).get(POST_TITLE).toUpperCase());
postContent.setText(objects.get(position).get(POST_CONTENT));
if (objects.get(position).get(GUID).equals("NULL"))
{
postImage.setImageResource(R.drawable.default_bg);
}
else
{
new DownloadImageTask((ImageView) convertView.findViewById(R.id.img)).execute(my_url);
}
}
return convertView;
}
I am trying to parse the images and text from url to list view.
I succesfully parse names but unable to parse Images. I follow these links....
I am getting bit map value null in image loader class..
I copied the MemoryCache and File Cache classes from the below links... Is there any mistake in my code?
My Json is: http://192.185.159.159/~charmmar/raj_spice/webservices/index.php?action=products
Is any problem for image parsing if json is large?
http://www.androidbegin.com/tutorial/android-json-parse-images-and-texts-tutorial/
http://luchfilip.wordpress.com/2014/02/25/android-how-to-parse-json-and-show-images-and-texts-in-a-listview/comment-page-1/
http://www.androidhive.info/2014/07/android-custom-listview-with-image-and-text-using-volley/
in these links all contained ImageLoader, FileCache, MemoryCache classes but I am unable to parse images... is any special library needed for this?
My class:
package com.example.dellizia;
import java.util.ArrayList;
import java.util.HashMap;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import android.app.Activity;
import android.app.ProgressDialog;
import android.content.SharedPreferences;
import android.os.AsyncTask;
import android.os.Bundle;
import android.preference.PreferenceManager;
import android.util.Log;
import android.widget.ListView;
public class RecipesJson extends Helper {
private String url = com.example.dellizia.Utility.urlpath + "products";
ArrayList<HashMap<String, String>> productList;
ProgressDialog pdialog;
final String TAG_DATA = "data";
final String TAG_ID = "id";
final static String TAG_NAME = "name";
final static String TAG_IMAGE = "images";
ListView listview;
RecipeJsonAdapter adapter;
SharedPreferences preferences;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.menu);
preferences = PreferenceManager.getDefaultSharedPreferences(this);
PrefEdit("pref__footer", "img_recipe");
footerBlock();
new DownloadJSON().execute();
}
private class DownloadJSON extends AsyncTask<Void, Void, Void> {
#Override
protected void onPreExecute() {
super.onPreExecute();
// Create a progressdialog
pdialog = new ProgressDialog(RecipesJson.this);
// Set progressdialog title
// pdialog.setTitle("Android JSON Parse Tutorial");
// Set progressdialog message
pdialog.setMessage("Loading...");
pdialog.setIndeterminate(false);
// Show progressdialog
pdialog.show();
}
#Override
protected Void doInBackground(Void... arg0) {
// TODO Auto-generated method stub
productList = new ArrayList<HashMap<String, String>>();
try {
String res = JsonFunction.getJSONfromURL(url);
Log.e("","resvalue--------"+res);
JSONObject jsonobj = new JSONObject(res);
String id = jsonobj.getString("status");
Log.e("","id value in parse json--------"+id);
if (id.equals("1")) {
JSONArray userdata = jsonobj.getJSONArray("data");
for (int i = 0; i < userdata.length(); i++) {
HashMap<String, String> pdata = new HashMap<String, String>();
JSONObject obj = userdata.getJSONObject(i);
String catid = userdata.getJSONObject(i).getString("id");
String name = userdata.getJSONObject(i).getString("name");
String image = userdata.getJSONObject(i).getString("images");
pdata.put(TAG_ID, catid);
Log.e("", "TAG_ID---" + TAG_ID);
pdata.put(TAG_NAME, name);
Log.e("", "TAG_NAME---" + TAG_NAME);
Log.e("", "name---" + name);
pdata.put(TAG_IMAGE, image);
Log.e("", "TAG_IMAGE---" + TAG_IMAGE);
Log.e("", "image-----------" + image);
productList.add(pdata);
Log.e("", "product list----" + productList);
}
}
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return null;
}
#Override
protected void onPostExecute(Void args) {
// Locate the listview in listview_main.xml
listview = (ListView) findViewById(R.id.recipeslist);
// Pass the results into ListViewAdapter.java
adapter = new RecipeJsonAdapter(RecipesJson.this, productList);
// Set the adapter to the ListView
listview.setAdapter(adapter);
// Close the progressdialog
pdialog.dismiss();
}
}
}
My adapter class:
package com.example.dellizia;
import java.util.ArrayList;
import java.util.HashMap;
import com.example.androidhive.ImageLoader;
import android.app.Activity;
import android.content.Context;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.ImageView;
import android.widget.TextView;
public class RecipeJsonAdapter extends BaseAdapter {
private Activity activity;
private ArrayList<HashMap<String, String>> data;
private static LayoutInflater inflater=null;
public ImageLoader imageLoader;
public RecipeJsonAdapter(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.recipeitems, null);
TextView title = (TextView)vi.findViewById(R.id.title); // title
//TextView artist = (TextView)vi.findViewById(R.id.artist); // artist name
//TextView duration = (TextView)vi.findViewById(R.id.duration); // duration
ImageView thumb_image=(ImageView)vi.findViewById(R.id.recipeimage); // thumb image
HashMap<String, String> song = new HashMap<String, String>();
song = data.get(position);
// Setting all values in listview
Log.e("","names values ------------"+song.get(RecipesJson.TAG_NAME));
title.setText(song.get(RecipesJson.TAG_NAME));
//artist.setText(song.get(CustomizedListView.KEY_ARTIST));
// duration.setText(song.get(CustomizedListView.KEY_DURATION));
Log.e("","images values ------------"+song.get(RecipesJson.TAG_IMAGE));
imageLoader.DisplayImage(song.get(RecipesJson.TAG_IMAGE), thumb_image);
return vi;
}
}
This is my link for all classes.. http://ge.tt/8keNUh62?c. In this link all my used classes are available.
Please help!
I want to retrieve all the images and populate GridView from PHP MySql Database. I'm using JSON parsing.But in my grid view is nothing display images from PHP and also nothing any error.So then why not show the images in Gridview in my application.What is wrong with the code. Thanks to appreciate.
Here is my Adapter code.
import java.util.ArrayList;
import java.util.HashMap;
import android.content.Context;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.GridView;
import android.widget.ImageView;
public class GridViewAdapter extends BaseAdapter
{
private Context context;
public ArrayList<HashMap<String, String>> mThumbIds;
public GridViewAdapter (Context context,ArrayList<HashMap<String, String>> data )
{
this.context= context;
mThumbIds= data;
}
#Override
public int getCount() {
// TODO Auto-generated method stub
return 0;
}
#Override
public Object getItem(int position) {
// TODO Auto-generated method stub
return position ;
}
#Override
public long getItemId(int position) {
// TODO Auto-generated method stub
return 0;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
// TODO Auto-generated method stub
ImageView imageView = new ImageView(context);
imageView.setImageResource(mThumbIds.get(position).get("image"));
imageView.setScaleType(ImageView.ScaleType.CENTER_CROP);
imageView.setLayoutParams(new GridView.LayoutParams(70, 70));
return imageView;
}
}
Here is Activity code.
package com.photo_app;
import java.util.ArrayList;
import java.util.HashMap;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import android.app.Activity;
import android.app.ProgressDialog;
import android.os.AsyncTask;
import android.os.Bundle;
import android.util.Log;
import android.widget.GridView;
public class Photo_Gallery extends Activity
{
JSONObject jsonobject;
JSONArray jsonarray;
GridView gridview;
GridViewAdapter adapter;
ProgressDialog mProgressDialog;
ArrayList<HashMap<String, String>> arraylist;
JSONParser jsonParser = new JSONParser();
ProgressDialog pDialog;
private String URL_PHOTO_GALLERY = "http://192.168.1.102/timesofindia/admin/photo_gallery.php";
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.photo_gallery);
new DownloadJSON().execute();
}
private class DownloadJSON extends AsyncTask<Void, Void, Void> {
#Override
protected void onPreExecute() {
super.onPreExecute();
mProgressDialog = new ProgressDialog(Photo_Gallery.this);
mProgressDialog.setTitle("Wait");
mProgressDialog.setMessage("Loading...");
mProgressDialog.setIndeterminate(false);
mProgressDialog.show();
}
#Override
protected Void doInBackground(Void... params)
{
arraylist = new ArrayList<HashMap<String, String>>();
jsonobject = JSONfunctions.getJSONfromURL(URL_PHOTO_GALLERY);
System.out.println("Json String = " + jsonobject.toString());
try
{
jsonarray = jsonobject.getJSONArray("photo_gallary");
for (int i = 0; i < jsonarray.length(); i++)
{
HashMap<String, String> map = new HashMap<String, String>();
jsonobject = jsonarray.getJSONObject(i);
map.put("flag", jsonobject.getString("image"));
arraylist.add(map);
Log.e("arraylist","=");
}
}
catch (JSONException e)
{
Log.e("Error", e.getMessage());
e.printStackTrace();
}
return null;
}
#Override
protected void onPostExecute(Void args) {
gridview = (GridView) findViewById(R.id.photoGallery);
adapter = new GridViewAdapter();
gridview.setAdapter(adapter);
mProgressDialog.dismiss();
}
}
}
You need to pass the data to the adapter. So, create a constructor which accepts the data and use it as you want in getView..
Pass the required data from the Activity to Adapter(it can be of any type. I have just given example to pass Integer[])
public GridViewAdapter (Context context,ArrayList<HashMap<String, Integer>> data )
{
this.context= context;
mThumbIds= data;
}
and pass it in you activity as :
GridViewAdapter adapter = new GridViewAdapter(this,your_data_array);
Update :
#Override
public View getView(int position, View convertView, ViewGroup parent) {
// TODO Auto-generated method stub
ImageView imageView = new ImageView(context);
imageView.setImageResource(mThumbIds.get(position).get("key")); // assuming key contains the resource id
imageView.setScaleType(ImageView.ScaleType.CENTER_CROP);
imageView.setLayoutParams(new GridView.LayoutParams(70, 70));
return imageView;
}
Try with below code:
package com.photo_app;
import java.util.ArrayList;
import java.util.HashMap;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import android.app.Activity;
import android.app.ProgressDialog;
import android.os.AsyncTask;
import android.os.Bundle;
import android.util.Log;
import android.widget.GridView;
public class Photo_Gallery extends Activity
{
JSONObject jsonobject;
JSONArray jsonarray;
GridView gridview;
GridViewAdapter adapter;
ProgressDialog mProgressDialog;
ArrayList<HashMap<String, String>> arraylist;
JSONParser jsonParser = new JSONParser();
ProgressDialog pDialog;
private String URL_PHOTO_GALLERY = "http://192.168.1.102/timesofindia/admin/photo_gallery.php";
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.photo_gallery);
new DownloadJSON().execute();
}
private class DownloadJSON extends AsyncTask<Void, Void, Void> {
#Override
protected void onPreExecute() {
super.onPreExecute();
mProgressDialog = new ProgressDialog(Photo_Gallery.this);
mProgressDialog.setTitle("Wait");
mProgressDialog.setMessage("Loading...");
mProgressDialog.setIndeterminate(false);
mProgressDialog.show();
}
#Override
protected Void doInBackground(Void... params)
{
arraylist = new ArrayList<HashMap<String, String>>();
jsonobject = JSONfunctions.getJSONfromURL(URL_PHOTO_GALLERY);
System.out.println("Json String = " + jsonobject.toString());
try
{
jsonarray = jsonobject.getJSONArray("photo_gallary");
for (int i = 0; i < jsonarray.length(); i++)
{
HashMap<String, String> map = new HashMap<String, String>();
jsonobject = jsonarray.getJSONObject(i);
map.put("flag", jsonobject.getString("image"));
arraylist.add(map);
Log.e("arraylist","=" + arraylist.add(map) );
}
}
catch (JSONException e)
{
Log.e("Error", e.getMessage());
e.printStackTrace();
}
return null;
}
#Override
protected void onPostExecute(Void args) {
gridview = (GridView) findViewById(R.id.photoGallery);
adapter = new GridViewAdapter(Photo_Gallery.this,arraylist);
gridview.setAdapter(adapter);
mProgressDialog.dismiss();
}
}
}
//Adapter Code:
package com.photo_app;
import java.util.ArrayList;
import java.util.HashMap;
import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.GridView;
import android.widget.ImageView;
import com.androidquery.AQuery;
public class GridViewAdapter extends BaseAdapter
{
private Context context;
public ArrayList<HashMap<String,String>> mThumbIds=new ArrayList<HashMap<String, String>>();
AQuery aQuery;
private LayoutInflater mInflater;
public GridViewAdapter (Context context,ArrayList<HashMap<String,String>> data )
{
this.context= context;
mThumbIds= data;
aQuery=new AQuery(context);
}
#Override
public int getCount() {
// TODO Auto-generated method stub
return mThumbIds.size();
}
#Override
public Object getItem(int position) {
// TODO Auto-generated method stub
return 0;
}
#Override
public long getItemId(int position) {
// TODO Auto-generated method stub
return 0;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
// TODO Auto-generated method stub
final ViewHolder holder;
if (convertView == null) {
convertView = mInflater.inflate(R.layout.photo_gallery_list_item, null);
holder = new ViewHolder();
holder.imageView = (ImageView) convertView.findViewById(R.id.imageView);
convertView.setTag(holder);
}else {
holder = (ViewHolder) convertView.getTag();
}
aQuery.id(holder.imageView).image(mThumbIds.get(position).get("flag"),true,true);
return convertView;
}
class ViewHolder {
ImageView imageView;
}
}
//photo_gallery_list_item.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:id="#+id/main"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:orientation="vertical"
android:padding="5dp" >
<ImageView
android:id="#+id/imageView"
android:layout_width="70dp"
android:layout_height="70dp"
android:scaleType="centerCrop"
android:src="#drawable/ic_launcher"
android:adjustViewBounds="true"/>
</LinearLayout>
I've got a functioning Universal Image Loader that I'm trying to switch to grabbing the image URLs from JSON rather than the Constants Class that it normally uses. I've created a JSON Parsing Class that outputs an ArrayList called galleryArrList. But I can't figure out how to implement my JSON Parsing class and also how to modify the Adapter class in the UILGrid class to accept the galleryArrList String. Here are the Classes:
UILGrid Class:
import android.content.Intent;
import android.graphics.Bitmap;
import android.os.Bundle;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.BaseAdapter;
import android.widget.GridView;
import android.widget.ImageView;
import com.nostra13.universalimageloader.core.DisplayImageOptions;
import com.mysite.wcbc.UKVPConstants.Extra;
public class UILGrid extends AbsListViewBaseActivity {
String[] imageUrls;
DisplayImageOptions options;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.uil_grid);
Bundle bundle = getIntent().getExtras();
imageUrls = bundle.getStringArray(Extra.IMAGES);
options = new DisplayImageOptions.Builder()
.showImageOnLoading(R.drawable.ic_stub)
.showImageForEmptyUri(R.drawable.ic_empty)
.showImageOnFail(R.drawable.ic_error).cacheInMemory(true)
.cacheOnDisc(true).bitmapConfig(Bitmap.Config.RGB_565).build();
listView = (GridView) findViewById(R.id.uil_gridview);
((GridView) listView).setAdapter(new ImageAdapter());
listView.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
startImagePagerActivity(position);
}
});
}
private void startImagePagerActivity(int position) {
Intent intent = new Intent(this, CVP2.class); // ---- Change here
intent.putExtra(Extra.IMAGES, imageUrls);
intent.putExtra(Extra.IMAGE_POSITION, position);
startActivity(intent);
}
public class ImageAdapter extends BaseAdapter {
#Override
public int getCount() {
return imageUrls.length;
}
#Override
public Object getItem(int position) {
return null;
}
#Override
public long getItemId(int position) {
return position;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
final ImageView imageView;
if (convertView == null) {
imageView = (ImageView) getLayoutInflater().inflate(
R.layout.uil_grid_item, parent, false);
} else {
imageView = (ImageView) convertView;
}
imageLoader.displayImage(imageUrls[position], imageView, options);
return imageView;
}
}
}
my UILJSONParse Class:
import java.util.ArrayList;
import java.util.HashMap;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import android.os.AsyncTask;
public class UILJSONParse extends AsyncTask<String, String, JSONObject> {
// url to make request
private static String url = "http://www.mysite.com/apps/wcbc/galleryuil.txt";
// Hashmap for ListView
// ArrayList<HashMap<String, String>> arraylist;
ArrayList<HashMap<String, String>> galleryArrList = new ArrayList<HashMap<String, String>>();
// JSON Node names
private static final String TAG_GALLERY = "gallery";
private static final String TAG_GALLERYURL = "galleryurl";
private static final String TAG_ID = "id";
private static final String TAG_GALLERYDESCR = "gallerydescr";
// gallery JSONArray
JSONArray JSArrGallery = null;
#Override
protected JSONObject doInBackground(String... arg0) {
// Creating JSON Parser instance
JGrid4Adapter jParser = new JGrid4Adapter();
// getting JSON string from URL
JSONObject jsonOb = jParser.getJSONFromUrl(url);
return jsonOb;
}
#Override
protected void onPostExecute(JSONObject jsonOb) {
try {
JSArrGallery = jsonOb.getJSONArray(TAG_GALLERY);
// looping through All gallery images
for (int i = 0; i < JSArrGallery.length(); i++) {
JSONObject galleryJO = JSArrGallery.getJSONObject(i);
String idStr = galleryJO.getString(TAG_ID);
String urlStr = galleryJO.getString(TAG_GALLERYURL);
String descrStr = galleryJO.getString(TAG_GALLERYDESCR);
// creating new HashMap
HashMap<String, String> map = new HashMap<String, String>();
// adding each child node to HashMap key => value
map.put(TAG_ID, idStr);
map.put(TAG_GALLERYURL, urlStr);
map.put(TAG_GALLERYDESCR, descrStr);
// adding HashMap map to ArrayList galleryArrList, defined
// above
galleryArrList.add(map);
}// -- END for loop
} catch (JSONException e) {
e.printStackTrace();
}// --- END Try
}// --- END onPostExecute
}// --- END UILJSONParse Class
I've figured this out since asking the question. I have a Button Interface Activity where an AsyncTask is called that grabs the JSON data when a button is clicked. The AysncTask then bundles the data and sends it to my Gallery Grid Class. The AsyncTask is calling the above JSON Parsing Class. So here's the code:
// --- artwork button
cartoon_BTN.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View arg0) {
jsonFileStr = "artwork_json";
new ArtworkJSON().execute();
}
});
// --- end artwork button
private class ArtworkJSON extends AsyncTask<Void, Void, Void> {
JSONObject jsonobject;
String TAG_ID = "id";
String TAG_DESCR = "artworkdescr";
String TAG_MEDIUM = "artworkmedium";
String TAG_PRICE = "artworkprice";
String TAG_URL = "artworkurl";
ArrayList<HashMap<String, String>> hashArraylist;
ArrayList<String> urlArrayList;
ArrayList<String> idArrayList;
ArrayList<String> descrArrayList;
ArrayList<String> mediumArrayList;
ArrayList<String> priceArrayList;
String[] idStrArray, urlStrArray, descrStrArray, mediumStrArray,
priceStrArray;
String urlPathStr = "http://www.mysite.com/"
+ jsonFileStr + ".txt";
JSONArray JSArrArtwork = null;
String idStr, urlStr, descrStr, mediumStr, priceStr;
ProgressDialog loadImagesDia;
Intent bundleIn;
#Override
protected void onPreExecute() {
super.onPreExecute();
// Create a progressdialog
loadImagesDia = new ProgressDialog(Main_Interface.this);
loadImagesDia.setMessage("Loading Images...");
loadImagesDia.setIndeterminate(false);
// Show progressdialog
loadImagesDia.show();
}
#Override
protected Void doInBackground(Void... params) {
hashArraylist = new ArrayList<HashMap<String, String>>();//
// Retrieve JSON Objects from the given URL address
jsonobject = JSONforGallery.getJSONfromURL(urlPathStr);
try {
// Locate the array name in JSON
JSArrArtwork = jsonobject.getJSONArray("artwork");
idArrayList = new ArrayList<String>();
urlArrayList = new ArrayList<String>();
descrArrayList = new ArrayList<String>();
mediumArrayList = new ArrayList<String>();
priceArrayList = new ArrayList<String>();
for (int i = 0; i < JSArrArtwork.length(); i++) {
HashMap<String, String> map = new HashMap<String, String>();//
JSONObject artworkJO = JSArrArtwork.getJSONObject(i);
map.put("id", artworkJO.getString(TAG_ID));//
map.put("url", artworkJO.getString(TAG_URL));//
map.put("descr", artworkJO.getString(TAG_DESCR));//
map.put("medium", artworkJO.getString(TAG_MEDIUM));//
map.put("price", artworkJO.getString(TAG_PRICE));//
idStr = artworkJO.getString(TAG_ID);
urlStr = artworkJO.getString(TAG_URL);
descrStr = artworkJO.getString(TAG_DESCR);
mediumStr = artworkJO.getString(TAG_MEDIUM);
priceStr = artworkJO.getString(TAG_PRICE);
hashArraylist.add(map);//
idArrayList.add(idStr);
urlArrayList.add(urlStr);
descrArrayList.add(descrStr);
mediumArrayList.add(mediumStr);
priceArrayList.add(priceStr);
idStrArray = idArrayList.toArray(new String[idArrayList
.size()]);
urlStrArray = urlArrayList.toArray(new String[urlArrayList
.size()]);
descrStrArray = descrArrayList
.toArray(new String[descrArrayList.size()]);
mediumStrArray = mediumArrayList
.toArray(new String[mediumArrayList.size()]);
priceStrArray = priceArrayList
.toArray(new String[priceArrayList.size()]);
}
} catch (JSONException e) {
Log.e("Error", e.getMessage());
e.printStackTrace();
}
return null;
}
#Override
protected void onPostExecute(Void args) {
loadImagesDia.dismiss();
bundleIn = new Intent("com.veedabugmedia.ktg.UILGRID");
bundleIn.putExtra("idStrArrayKey", idStrArray);
bundleIn.putExtra("hashARKey", hashArraylist);
bundleIn.putExtra("urlStrArrayKey", urlStrArray);
bundleIn.putExtra("descrStrArrayKey", descrStrArray);
bundleIn.putExtra("mediumStrArrayKey", mediumStrArray);
bundleIn.putExtra("priceStrArrayKey", priceStrArray);
startActivity(bundleIn);
}
}
My updated UILGrid Activity:
public class UILGrid extends AbsListViewBaseActivity {
String[] idStr, imageUrls, descrStrGrid, mediumStrGrid, priceStrGrid;
DisplayImageOptions options;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.uil_grid);
// Retrieve data from About_Interface on item click event
Intent getBundsIn = getIntent();
idStr = getBundsIn.getStringArrayExtra("idStrArrayKey");
imageUrls = getBundsIn.getStringArrayExtra("urlStrArrayKey");
descrStrGrid = getBundsIn.getStringArrayExtra("descrStrArrayKey");
mediumStrGrid = getBundsIn.getStringArrayExtra("mediumStrArrayKey");
priceStrGrid = getBundsIn.getStringArrayExtra("priceStrArrayKey");
options = new DisplayImageOptions.Builder()
.showImageOnLoading(R.drawable.ic_stub)
.showImageForEmptyUri(R.drawable.ic_empty)
.showImageOnFail(R.drawable.ic_error).cacheInMemory(true)
.cacheOnDisc(true).bitmapConfig(Bitmap.Config.RGB_565).build();
listView = (GridView) findViewById(R.id.uil_gridview);
((GridView) listView).setAdapter(new ImageAdapter());
listView.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
startImagePagerActivity(position);
}
});
}// --- END onCreate
private void startImagePagerActivity(int position) {
Intent pagerIn = new Intent(this, UILPager.class);
pagerIn.putExtra("pagerUrlStrKey", imageUrls);
pagerIn.putExtra("pagerDescrStrKey", descrStrGrid);
pagerIn.putExtra("pagerMediumStrKey", mediumStrGrid);
pagerIn.putExtra("pagerPriceStrKey", priceStrGrid);
pagerIn.putExtra("pagerPositionKey", position);
startActivity(pagerIn);
}
public class ImageAdapter extends BaseAdapter {
#Override
public int getCount() {
return imageUrls.length;
}
#Override
public Object getItem(int position) {
return null;
}
#Override
public long getItemId(int position) {
return position;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
final ImageView imageView;
if (convertView == null) {
imageView = (ImageView) getLayoutInflater().inflate(
R.layout.uil_grid_item, parent, false);
} else {
imageView = (ImageView) convertView;
}
imageLoader.displayImage(imageUrls[position], imageView, options);
return imageView;
}
}
#Override
protected void onPause() {
super.onPause();
overridePendingTransition(R.anim.fadein, R.anim.fadeout);
UILGrid.this.finish();
}
}