I am new to Android development and Java in general. I realize that this question may seem quite elementary, but I am just not understanding despite looking on numerous forums, reading about the exception and debugging my activity.
I am trying to parse JSON image data into a GridView.
import android.app.Activity;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.net.Uri;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Handler;
import android.util.Log;
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 org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.Iterator;
import java.util.LinkedHashMap;
import java.util.Map;
import java.util.WeakHashMap;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
public class JSONImageViewer extends Activity {
JSONObject jsonobject;
JSONArray jsonarray;
ListViewAdapter adapter;
ProgressDialog mProgressDialog;
ArrayList<HashMap<String, String>> arraylist;
static String TAG_IMG = "CarImageLink";
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
//Get the view from gridview_item.xml
setContentView(R.layout.gridview_item);
// Execute DownloadJSON AsyncTask
new DownloadJSON().execute();
}
// DownloadJSON AsyncTask
private class DownloadJSON extends AsyncTask<Void, Void, Void> {
#Override
protected void onPreExecute() {
super.onPreExecute();
// Create a progressdialog
mProgressDialog = new ProgressDialog(JSONImageViewer.this);
// Set progressdialog message
mProgressDialog.setMessage("Loading...");
mProgressDialog.setIndeterminate(false);
// Show progressdialog
mProgressDialog.show();
}
#Override
protected Void doInBackground(Void... params) {
//Create an array
arraylist = new ArrayList<HashMap<String, String>>();
//Retrieve JSON Objects from the given URL address
jsonobject = JSONfunctions
.getJSONfromURL("......");
try {
//Locate the array name in JSON
jsonarray = jsonobject.getJSONArray("car_images");
for (int i = 0; i < jsonarray.length(); i++) {
HashMap<String, String> map = new HashMap<String, String>();
jsonobject = jsonarray.getJSONObject(i);
//Retrieve JSON Object
map.put("CarImageLink", jsonobject.getString("CarImageLink"));
//Set the JSON Objects into the array
arraylist.add(map);
}
} catch (JSONException e) {
Log.e("Error", e.getMessage());
e.printStackTrace();
}
return null;
}
#Override
protected void onPostExecute(Void args) {
//Locate the Gridview in gridview_main.xml
GridView gridview;
gridview = (GridView) findViewById(R.id.gridview);
adapter = new ListViewAdapter(JSONImageViewer.this, arraylist);
//Set the adapter to the GridView
gridview.setAdapter(adapter);
//Close the progressdialog
mProgressDialog.dismiss();
}
}
public static class JSONfunctions {
public static JSONObject getJSONfromURL(String url) {
InputStream is = null;
String result = "";
JSONObject jArray = null;
//Download JSON data from URL
try {
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost(url);
HttpResponse response = httpclient.execute(httppost);
HttpEntity entity = response.getEntity();
is = entity.getContent();
} catch (Exception e) {
Log.e("log_tag", "Error in http connection " + e.toString());
}
//Convert response to string
try {
BufferedReader reader = new BufferedReader(new InputStreamReader(is, "iso-8859-1"), 8);
StringBuilder sb = new StringBuilder();
String line = null;
while ((line = reader.readLine()) != null) {
sb.append(line + "\n");
}
is.close();
result = sb.toString();
} catch (Exception e) {
Log.e("log_tag", "Error converting result " + e.toString());
}
try {
jArray = new JSONObject(result);
} catch (JSONException e) {
Log.e("log_tag", "Error parsing data " + e.toString());
}
return jArray;
}
}
public class ListViewAdapter extends BaseAdapter {
Context context;
LayoutInflater inflater;
ArrayList<HashMap<String, String>> data;
ImageLoader imageLoader;
HashMap<String, String> resultp = new HashMap<String, String>();
public ListViewAdapter(Context context, ArrayList<HashMap<String, String>> arraylist) {
this.context = context;
data = arraylist;
imageLoader = new ImageLoader(context);
}
#Override
public int getCount() {
return data.size();
}
#Override
public Object getItem(int position) {
return null;
}
#Override
public long getItemId(int position) {
return 0;
}
public View getView(final int position, View convertView, ViewGroup parent) {
ImageView carimg;
inflater = (LayoutInflater) context
.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
View itemView = inflater.inflate(R.layout.gridview_item, parent, false);
//Get the position
resultp = data.get(position);
//resultp.put(TAG_IMG,data.get(position).get("CarImageLink"));
//resultp.put(TAG_IMG,data.get(position).get("CarImageLink))"));
Log.v("resultp", resultp.toString());
//Locate the ImageView in gridview_item.xml
carimg = (ImageView) itemView.findViewById(R.id.car_img);
//Capture position and set results to the ImageView
//Passes images URL into ImageLoader.class
int loader = R.drawable.temp_img;
int stub_id = loader;
imageLoader.DisplayImage(resultp.get(JSONImageViewer.TAG_IMG),stub_id, carimg);
Log.v("resultp e1", (resultp.get(TAG_IMG).toString()));
//Log.v("carimg", carimg.toString());
Log.v("resultp e2", resultp.toString());
//Capture ListView item click
itemView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View arg0) {
//Get the position
resultp = data.get(position);
//resultp.put(TAG_IMG,data.get(position).get("CarImageLink"));
Intent intent = new Intent(context, SingleItemView.class);
// Pass all data
intent.putExtra("CarImageLink", resultp.get(JSONImageViewer.TAG_IMG));
//Start SingleItemView Class
context.startActivity(intent);
}
});
return itemView;
}
}
public class ImageLoader {
MemoryCache memoryCache=new MemoryCache();
FileCache fileCache;
private Map<ImageView, String> imageViews=Collections.synchronizedMap(new WeakHashMap<ImageView, String>());
ExecutorService executorService;
// Handler to display images in UI thread
Handler handler = new Handler();
public ImageLoader(Context context){
fileCache=new FileCache(context);
executorService=Executors.newFixedThreadPool(5);
}
int stub_id = R.drawable.temp_img;
public void DisplayImage(String url, int loader, ImageView imageView)
{
try {
stub_id = loader;
imageViews.put(imageView, url);
Bitmap bitmap=memoryCache.get(url);
if(bitmap!=null) {
imageView.setImageBitmap(bitmap);
Log.v("Bitmap 3", bitmap.toString());
}
else
{
queuePhoto(url, imageView);
imageView.setImageResource(stub_id);
}
} catch (Exception e) {
e.printStackTrace();
}
}
private void queuePhoto(String url, ImageView imageView) {
PhotoToLoad p = new PhotoToLoad(url, imageView);
executorService.submit(new PhotosLoader(p));
}
private Bitmap getBitmap(String url) {
File f = fileCache.getFile(url);
Bitmap b = decodeFile(f);
if (b != null) {
Log.v("bitmap 4", b.toString());
return b;
}
//Download Images from the Internet
try {
Bitmap bitmap;
// Log.v("Bitmap 5", bitmap.toString());
Uri.Builder uri = Uri.parse("....").buildUpon();
uri.appendPath(url);
uri.build();
Log.v("Build", uri.build().toString());
Log.v("Uri", uri.toString());
URL imageUrl = new URL ("http://"+ "....com" + url);
Log.v("URL 3", imageUrl.toString());
HttpURLConnection conn = (HttpURLConnection) imageUrl
.openConnection();
conn.setConnectTimeout(30000);
conn.setReadTimeout(30000);
conn.setInstanceFollowRedirects(true);
InputStream is = conn.getInputStream();
OutputStream os = new FileOutputStream(f);
Utils.CopyStream(is, os);
os.close();
conn.disconnect();
bitmap = decodeFile(f);
//Log.v("bitmap 6", bitmap.toString());
return bitmap;
} catch (Throwable ex) {
ex.printStackTrace();
if (ex instanceof OutOfMemoryError)
memoryCache.clear();
return null;
}
}
//Decodes image and scales it to reduce memory consumption
private Bitmap decodeFile(File f) {
try {
//Decode image size
BitmapFactory.Options o = new BitmapFactory.Options();
o.inJustDecodeBounds = true;
FileInputStream stream1 = new FileInputStream(f);
BitmapFactory.decodeStream(stream1, null, o);
stream1.close();
//Find the correct scale value. It should be the power of 2.
final int REQUIRED_SIZE = 70;
int width_tmp = o.outWidth, height_tmp = o.outHeight;
int scale = 1;
while (true) {
if (width_tmp / 2 < REQUIRED_SIZE
|| height_tmp / 2 < REQUIRED_SIZE)
break;
width_tmp /= 2;
height_tmp /= 2;
scale *= 2;
}
//Decode with inSampleSize
BitmapFactory.Options o2 = new BitmapFactory.Options();
o2.inSampleSize = scale;
FileInputStream stream2 = new FileInputStream(f);
Bitmap bitmap = BitmapFactory.decodeStream(stream2, null, o2);
stream2.close();
Log.v("bitmap 7", bitmap.toString());
return bitmap;
} catch (FileNotFoundException e) {
} catch (IOException e) {
e.printStackTrace();
}
return null;
}
//Task for the queue
private class PhotoToLoad {
public String url;
public ImageView imageView;
public PhotoToLoad(String u, ImageView i) {
url = u;
imageView = i;
}
}
class PhotosLoader implements Runnable {
PhotoToLoad photoToLoad;
PhotosLoader(PhotoToLoad photoToLoad) {
this.photoToLoad = photoToLoad;
}
#Override
public void run() {
try {
//if (imageViewReused(photoToLoad))
// return;
Bitmap bmp = getBitmap(photoToLoad.url);
Log.v("URL 2", photoToLoad.url.toString());
Log.v("Bitmap bmp", bmp.toString());
memoryCache.put(photoToLoad.url, bmp);
//if (imageViewReused(photoToLoad))
//return;
//BitmapDisplayer bd = new BitmapDisplayer(bmp, photoToLoad);
//handler.post(bd);
//Log.v("bd", bd.toString());
} catch (Throwable th) {
th.printStackTrace();
}
}
}
/* boolean imageViewReused(PhotoToLoad photoToLoad) {
String tag = imageViews.get(photoToLoad.imageView);
if (tag == null || !tag.equals(photoToLoad.url))
return true;
return false;
}
*/
class BitmapDisplayer implements Runnable {
Bitmap bitmap;
PhotoToLoad photoToLoad;
public BitmapDisplayer(Bitmap b, PhotoToLoad p) {
bitmap=b;
Log.v("bitmap b", b.toString());
photoToLoad=p;
}
public void run(){
// if(imageViewReused(photoToLoad)) {
//Log.v("BITMAP", bitmap.toString());
// return;
//}
Log.v("BITMAP", bitmap.toString());
if(bitmap != null) {
photoToLoad.imageView.setImageBitmap(bitmap);
Log.v("bitmap 2", bitmap.toString());
}
else {
photoToLoad.imageView.setImageResource(stub_id);
}
}
}
public void clearCache() {
memoryCache.clear();
fileCache.clear();
}
}
public class MemoryCache {
private static final String TAG = "MemoryCache";
//Last argument true for LRU ordering
private Map<String, Bitmap> cache = Collections
.synchronizedMap(new LinkedHashMap<String, Bitmap>(10, 1.5f, true));
//Current allocated size
private long size = 0;
//Max memory in bytes
private long limit = 1000000;
public MemoryCache() {
//Use 25% of available heap size
setLimit(Runtime.getRuntime().maxMemory() / 4);
}
public void setLimit(long new_limit) {
limit = new_limit;
}
public Bitmap get(String id) {
try {
if (!cache.containsKey(id))
return null;
return cache.get(id);
} catch (NullPointerException ex) {
ex.printStackTrace();
return null;
}
}
public void put(String id, Bitmap bitmap) {
try {
if (cache.containsKey(id))
size -= getSizeInBytes(cache.get(id));
cache.put(id, bitmap);
size += getSizeInBytes(bitmap);
checkSize();
} catch (Throwable th) {
th.printStackTrace();
}
}
private void checkSize() {
Log.i(TAG, "cache size=" + size + " length=" + cache.size());
if (size > limit) {
//Least recently accessed item will be the first one iterated
Iterator<Map.Entry<String, Bitmap>> iter = cache.entrySet().iterator();
while (iter.hasNext()) {
Map.Entry<String, Bitmap> entry = iter.next();
size -= getSizeInBytes(entry.getValue());
iter.remove();
if (size <= limit)
break;
}
Log.i(TAG, "Clean cache. New size " + cache.size());
}
}
public void clear() {
try {
cache.clear();
size = 0;
} catch (NullPointerException ex) {
ex.printStackTrace();
}
}
long getSizeInBytes(Bitmap bitmap) {
if (bitmap == null)
return 0;
return bitmap.getRowBytes() * bitmap.getHeight();
}
}
public class FileCache {
private File cacheDir;
public FileCache(Context context) {
//Find the dir to save cached images
if (android.os.Environment.getExternalStorageState().equals(
android.os.Environment.MEDIA_MOUNTED))
cacheDir = new File(
android.os.Environment.getExternalStorageDirectory(),
"");
else
cacheDir = context.getCacheDir();
if (!cacheDir.exists())
cacheDir.mkdirs();
}
public File getFile(String url) {
String filename = String.valueOf(url.hashCode());
//String filename = URLEncoder.encode(url);
File f = new File(cacheDir, filename);
return f;
}
public void clear() {
File[] files = cacheDir.listFiles();
if (files == null)
return;
for (File f : files)
f.delete();
}
}
public static class Utils {
public static void CopyStream(InputStream is, OutputStream os)
{
final int buffer_size=1024;
try
{
byte[] bytes=new byte[buffer_size];
for(;;)
{
int count=is.read(bytes, 0, buffer_size);
if(count==-1)
break;
os.write(bytes, 0, count);
}
}
catch(Exception ex){}
}
}
public class SingleItemView extends Activity {
String carimg;
ImageLoader imageLoader = new ImageLoader(this);
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
//Get the view from singleitemview.xml
setContentView(R.layout.singleitemview);
Intent i = getIntent();
//Get the result of CarImageLink
carimg = i.getStringExtra("CarImageLink");
Log.v("carimg", i.getStringExtra("CarImageLink").toString());
int loader = R.drawable.temp_img;
int stub_id = loader;
//Locate the ImageView in singleitemview.xml
ImageView img_car = (ImageView) findViewById(R.id.car_img);
Log.v("Imageview img_car", img_car.toString());
//Capture position and set results to the ImageView
//Passes carimg images URL into ImageLoader.class
imageLoader.DisplayImage(carimg, stub_id, img_car);
}
}
griview_item.xml
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent" >
<GridView
android:id="#+id/gridview"
android:layout_width="fill_parent"
android:layout_height="fill_parent" />
</RelativeLayout>
list_item.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="match_parent"
android:layout_height="wrap_content" >
<TextView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:id="#+id/cars"/>
<TextView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:id="#+id/car_id"
android:text="#string/id"/>
<TextView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:id="#+id/car_vin"
android:layout_below="#id/car_id"
android:text="#string/vin"/>
<ImageView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="#+id/model_img"
android:layout_toRightOf="#id/car_id"/>
<ListView
android:id="#+id/list"
android:layout_weight="1"
android:layout_height="wrap_content"
android:layout_width="fill_parent"/>
</LinearLayout>
singleitemview.xml
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="fill_parent"
android:layout_height="fill_parent" >
<ImageView
android:id="#+id/car_img"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentRight="true"
android:background="#000000"
android:padding="1dp"
android:src="#drawable/temp_img" />
</RelativeLayout>
Any suggestions as to how to solve these errors would be greatly appreciated. Thank you.
Update:
java.lang.NullPointerException
07-30 15:30:54.609 29426-29426/com.example.justin.myapplication W/System.err﹕ at com.example.justin.myapplication.JSONImageViewer$ImageLoader.DisplayImage(JSONImageViewer.java:290)
07-30 15:30:54.609 29426-29426/com.example.justin.myapplication W/System.err﹕ at com.example.justin.myapplication.JSONImageViewer$ListViewAdapter.getView(JSONImageViewer.java:229)
07-30 15:30:54.609 29426-29426/com.example.justin.myapplication W/System.err﹕ at android.widget.AbsListView.obtainView(AbsListView.java:2143)
07-30 15:30:54.609 29426-29426/com.example.justin.myapplication W/System.err﹕ at android.widget.GridView.makeAndAddView(GridView.java:1341)
07-30 15:30:54.609 29426-29426/com.example.justin.myapplication W/System.err﹕ at android.widget.GridView.makeRow(GridView.java:341)
07-30 15:30:54.609 29426-29426/com.example.justin.myapplication W/System.err﹕ at android.widget.GridView.fillDown(GridView.java:283)
07-30 15:30:54.609 29426-29426/com.example.justin.myapplication W/System.err﹕ at android.widget.GridView.fillFromTop(GridView.java:417)
07-30 15:30:54.609 29426-29426/com.example.justin.myapplication W/System.err﹕ at android.widget.GridView.layoutChildren(GridView.java:1229)
07-30 15:30:54.609 29426-29426/com.example.justin.myapplication W/System.err﹕ at android.widget.AbsListView.onLayout(AbsListView.java:1994)
07-30 15:30:54.609 29426-29426/com.example.justin.myapplication W/System.err﹕ at android.view.View.layout(View.java:14008)
07-30 15:30:54.609 29426-29426/com.example.justin.myapplication W/System.err﹕ at android.view.ViewGroup.layout(ViewGroup.java:4373)
07-30 15:30:54.609 29426-29426/com.example.justin.myapplication W/System.err﹕ at android.widget.RelativeLayout.onLayout(RelativeLayout.java:1021)
07-30 15:30:54.609 29426-29426/com.example.justin.myapplication W/System.err﹕ at android.view.View.layout(View.java:14008)
07-30 15:30:54.609 29426-29426/com.example.justin.myapplication W/System.err﹕ at android.view.ViewGroup.layout(ViewGroup.java:4373)
imageView.setImageResource(stub_id); for (JSONImageViewer.java:290)
imageLoader.DisplayImage(resultp.get(JSONImageViewer.TAG_IMG),stub_id, carimg); for (JSONImageViewer.java:229)
Straightforward debugging stuff in Android.
Faced with a seemingly impenetrable Exception stack trace, the trick is scan down the list of routines looking for the first occurrence of a line of source in YOUR code. Set a breakpoint on that line, and take a look at what's actually happening. You should also look for "Caused by" inner exceptions when doing this. When there's an inner exception, you will find the problem in the stack trace for the inner except.
In your case the line of interest is the very first line in the stack trace:
at com.example.justin.myapplication.JSONImageViewer$ImageLoader.DisplayImage(JSONImageViewer.java:287)
A Null pointer exception occured in JSONImageViewer.java at line 287.
Set a breakpoint on that line in the debugger, and look to see what's happening. You can just double-click on the file and line-number in the stack trace to go straight to the source line.
I can't tell which line is line 287. But it seems to be something to do with the URL you're constructing. You should be able to figure this out pretty easily once you set a breakpoint on line 287.
I believe that the issue is due to the hashmap.
A hashmap is made of key and value. However, you are not saving a key to the value specified. ("resultp = data.get(position);").
Therefore, when you try to access a value of the hashmap with the key : "TAG_IMG", the app is crashing with null pointer because this will return a null value.
The correct way of fixing this issue would be : resultp.put(TAG_IMG, data.get(position));
public class JSONImageViewer extends Activity {
JSONObject jsonobject;
JSONArray jsonarray;
ListViewAdapter adapter;
ProgressDialog mProgressDialog;
ArrayList<HashMap<String, String>> arraylist;
static String TAG_IMG = "CarImageLink";
GridView gridview;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
gridview = (GridView) findViewById(R.id.gridview);
new DownloadJSON().execute();
}
// DownloadJSON AsyncTask
private class DownloadJSON extends AsyncTask<Void, Void, Void> {
#Override
protected void onPreExecute() {
super.onPreExecute();
// Create a progressdialog
mProgressDialog = new ProgressDialog(JSONImageViewer.this);
// Set progressdialog message
mProgressDialog.setMessage("Loading...");
mProgressDialog.setIndeterminate(false);
// Show progressdialog
mProgressDialog.show();
}
#Override
protected Void doInBackground(Void... params) {
//Create an array
arraylist = new ArrayList<HashMap<String, String>>();
//Retrieve JSON Objects from the given URL address
jsonobject = JSONfunctions
.getJSONfromURL("......");
try {
//Locate the array name in JSON
jsonarray = jsonobject.getJSONArray("car_images");
HashMap<String, String> map = new HashMap<String, String>();
for (int i = 0; i < jsonarray.length(); i++) {
jsonobject = jsonarray.getJSONObject(i);
//Retrieve JSON Object
map.put("CarImageLink" + i, jsonobject.getString("CarImageLink"));
//Set the JSON Objects into the array
arraylist.add(map);
}
} catch (JSONException e) {
Log.e("Error", e.getMessage());
e.printStackTrace();
}
return null;
}
#Override
protected void onPostExecute(Void args) {
if (arraylist != null && arraylist.size() > 0) {
adapter = new ListViewAdapter(getApplicationContext(), arraylist);
//Set the adapter to the GridView
gridview.setAdapter(adapter);
} else Toast.makeText(getApplicationContext(), "List is null", Toast.LENGTH_SHORT);
//Close the progressdialog
mProgressDialog.dismiss();
}
}
public static class JSONfunctions {
public static JSONObject getJSONfromURL(String url) {
InputStream is = null;
String result = "";
JSONObject jArray = null;
//Download JSON data from URL
try {
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost(url);
HttpResponse response = httpclient.execute(httppost);
HttpEntity entity = response.getEntity();
is = entity.getContent();
} catch (Exception e) {
Log.e("log_tag", "Error in http connection " + e.toString());
}
//Convert response to string
try {
BufferedReader reader = new BufferedReader(new InputStreamReader(is, "iso-8859-1"), 8);
StringBuilder sb = new StringBuilder();
String line = null;
while ((line = reader.readLine()) != null) {
sb.append(line + "\n");
}
is.close();
result = sb.toString();
} catch (Exception e) {
Log.e("log_tag", "Error converting result " + e.toString());
}
try {
jArray = new JSONObject(result);
} catch (JSONException e) {
Log.e("log_tag", "Error parsing data " + e.toString());
}
return jArray;
}
}
public class ListViewAdapter extends BaseAdapter {
Context context;
LayoutInflater inflater;
ArrayList<HashMap<String, String>> data;
ImageLoader imageLoader;
HashMap<String, String> resultp = new HashMap<String, String>();
public ListViewAdapter(Context context, ArrayList<HashMap<String, String>> arraylist) {
this.context = context;
this.data = arraylist;
imageLoader = new ImageLoader(context);
}
#Override
public int getCount() {
return data.size();
}
#Override
public Object getItem(int position) {
return null;
}
#Override
public long getItemId(int position) {
return 0;
}
public View getView(final int position, View convertView, ViewGroup parent) {
ImageView carimg;
inflater = (LayoutInflater) context
.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
View itemView = inflater.inflate(R.layout.gridview_item, parent, false);
//Get the position
resultp = data.get(position);
//resultp.put(TAG_IMG,data.get(position).get("CarImageLink"));
//resultp.put(TAG_IMG,data.get(position).get("CarImageLink))"));
Log.v("resultp", resultp.toString());
//Locate the ImageView in gridview_item.xml
carimg = (ImageView) itemView.findViewById(R.id.car_img);
//Capture position and set results to the ImageView
//Passes images URL into ImageLoader.class
int loader = R.drawable.temp_img;
int stub_id = loader;
if (carimg == null) {
Toast.makeText(getApplicationContext(), "A crash is going to happen due to error in xml", Toast.LENGTH_SHORT);
}
if (resultp.get(TAG_IMG) == null) {
Toast.makeText(getApplicationContext(), "A crash is going to happen due to hashma error", Toast.LENGTH_SHORT).show();
}
imageLoader.DisplayImage(resultp.get(TAG_IMG) + position, stub_id, carimg);
Log.v("resultp e1", (resultp.get(TAG_IMG).toString()));
//Log.v("carimg", carimg.toString());
Log.v("resultp e2", resultp.toString());
//Capture ListView item click
/*itemView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View arg0) {
//Get the position
resultp = data.get(position);
//resultp.put(TAG_IMG,data.get(position).get("CarImageLink"));
Intent intent = new Intent(context, SingleItemView.class);
// Pass all data
intent.putExtra("CarImageLink", resultp.get(JSONImageViewer.TAG_IMG));
//Start SingleItemView Class
context.startActivity(intent);
}
});*/
return itemView;
}
}
public class ImageLoader {
MemoryCache memoryCache = new MemoryCache();
FileCache fileCache;
private Map<ImageView, String> imageViews = Collections.synchronizedMap(new WeakHashMap<ImageView, String>());
ExecutorService executorService;
// Handler to display images in UI thread
Handler handler = new Handler();
public ImageLoader(Context context) {
fileCache = new FileCache(context);
executorService = Executors.newFixedThreadPool(5);
}
int stub_id = R.drawable.temp_img;
public void DisplayImage(String url, int loader, ImageView imageView) {
try {
stub_id = loader;
imageViews.put(imageView, url);
Bitmap bitmap = memoryCache.get(url);
if (bitmap != null) {
imageView.setImageBitmap(bitmap);
Log.v("Bitmap 3", bitmap.toString());
} else {
queuePhoto(url, imageView);
imageView.setImageResource(stub_id);
}
} catch (Exception e) {
e.printStackTrace();
}
}
private void queuePhoto(String url, ImageView imageView) {
PhotoToLoad p = new PhotoToLoad(url, imageView);
executorService.submit(new PhotosLoader(p));
}
private Bitmap getBitmap(String url) {
File f = fileCache.getFile(url);
Bitmap b = decodeFile(f);
if (b != null) {
Log.v("bitmap 4", b.toString());
return b;
}
//Download Images from the Internet
try {
Bitmap bitmap;
// Log.v("Bitmap 5", bitmap.toString());
Uri.Builder uri = Uri.parse("....").buildUpon();
uri.appendPath(url);
uri.build();
Log.v("Build", uri.build().toString());
Log.v("Uri", uri.toString());
URL imageUrl = new URL("http://" + "....com" + url);
Log.v("URL 3", imageUrl.toString());
HttpURLConnection conn = (HttpURLConnection) imageUrl
.openConnection();
conn.setConnectTimeout(30000);
conn.setReadTimeout(30000);
conn.setInstanceFollowRedirects(true);
InputStream is = conn.getInputStream();
OutputStream os = new FileOutputStream(f);
Utils.CopyStream(is, os);
os.close();
conn.disconnect();
bitmap = decodeFile(f);
//Log.v("bitmap 6", bitmap.toString());
return bitmap;
} catch (Throwable ex) {
ex.printStackTrace();
if (ex instanceof OutOfMemoryError)
memoryCache.clear();
return null;
}
}
//Decodes image and scales it to reduce memory consumption
private Bitmap decodeFile(File f) {
try {
//Decode image size
BitmapFactory.Options o = new BitmapFactory.Options();
o.inJustDecodeBounds = true;
FileInputStream stream1 = new FileInputStream(f);
BitmapFactory.decodeStream(stream1, null, o);
stream1.close();
//Find the correct scale value. It should be the power of 2.
final int REQUIRED_SIZE = 70;
int width_tmp = o.outWidth, height_tmp = o.outHeight;
int scale = 1;
while (true) {
if (width_tmp / 2 < REQUIRED_SIZE
|| height_tmp / 2 < REQUIRED_SIZE)
break;
width_tmp /= 2;
height_tmp /= 2;
scale *= 2;
}
//Decode with inSampleSize
BitmapFactory.Options o2 = new BitmapFactory.Options();
o2.inSampleSize = scale;
FileInputStream stream2 = new FileInputStream(f);
Bitmap bitmap = BitmapFactory.decodeStream(stream2, null, o2);
stream2.close();
Log.v("bitmap 7", bitmap.toString());
return bitmap;
} catch (FileNotFoundException e) {
} catch (IOException e) {
e.printStackTrace();
}
return null;
}
//Task for the queue
private class PhotoToLoad {
public String url;
public ImageView imageView;
public PhotoToLoad(String u, ImageView i) {
url = u;
imageView = i;
}
}
class PhotosLoader implements Runnable {
PhotoToLoad photoToLoad;
PhotosLoader(PhotoToLoad photoToLoad) {
this.photoToLoad = photoToLoad;
}
#Override
public void run() {
try {
//if (imageViewReused(photoToLoad))
// return;
Bitmap bmp = getBitmap(photoToLoad.url);
Log.v("URL 2", photoToLoad.url.toString());
Log.v("Bitmap bmp", bmp.toString());
memoryCache.put(photoToLoad.url, bmp);
//if (imageViewReused(photoToLoad))
//return;
//BitmapDisplayer bd = new BitmapDisplayer(bmp, photoToLoad);
//handler.post(bd);
//Log.v("bd", bd.toString());
} catch (Throwable th) {
th.printStackTrace();
}
}
}
/* boolean imageViewReused(PhotoToLoad photoToLoad) {
String tag = imageViews.get(photoToLoad.imageView);
if (tag == null || !tag.equals(photoToLoad.url))
return true;
return false;
}
*/
class BitmapDisplayer implements Runnable {
Bitmap bitmap;
PhotoToLoad photoToLoad;
public BitmapDisplayer(Bitmap b, PhotoToLoad p) {
bitmap = b;
Log.v("bitmap b", b.toString());
photoToLoad = p;
}
public void run() {
// if(imageViewReused(photoToLoad)) {
//Log.v("BITMAP", bitmap.toString());
// return;
//}
Log.v("BITMAP", bitmap.toString());
if (bitmap != null) {
photoToLoad.imageView.setImageBitmap(bitmap);
Log.v("bitmap 2", bitmap.toString());
} else {
photoToLoad.imageView.setImageResource(stub_id);
}
}
}
public void clearCache() {
memoryCache.clear();
fileCache.clear();
}
}
public class MemoryCache {
private static final String TAG = "MemoryCache";
//Last argument true for LRU ordering
private Map<String, Bitmap> cache = Collections
.synchronizedMap(new LinkedHashMap<String, Bitmap>(10, 1.5f, true));
//Current allocated size
private long size = 0;
//Max memory in bytes
private long limit = 1000000;
public MemoryCache() {
//Use 25% of available heap size
setLimit(Runtime.getRuntime().maxMemory() / 4);
}
public void setLimit(long new_limit) {
limit = new_limit;
}
public Bitmap get(String id) {
try {
if (!cache.containsKey(id))
return null;
return cache.get(id);
} catch (NullPointerException ex) {
ex.printStackTrace();
return null;
}
}
public void put(String id, Bitmap bitmap) {
try {
if (cache.containsKey(id))
size -= getSizeInBytes(cache.get(id));
cache.put(id, bitmap);
size += getSizeInBytes(bitmap);
checkSize();
} catch (Throwable th) {
th.printStackTrace();
}
}
private void checkSize() {
Log.i(TAG, "cache size=" + size + " length=" + cache.size());
if (size > limit) {
//Least recently accessed item will be the first one iterated
Iterator<Map.Entry<String, Bitmap>> iter = cache.entrySet().iterator();
while (iter.hasNext()) {
Map.Entry<String, Bitmap> entry = iter.next();
size -= getSizeInBytes(entry.getValue());
iter.remove();
if (size <= limit)
break;
}
Log.i(TAG, "Clean cache. New size " + cache.size());
}
}
public void clear() {
try {
cache.clear();
size = 0;
} catch (NullPointerException ex) {
ex.printStackTrace();
}
}
long getSizeInBytes(Bitmap bitmap) {
if (bitmap == null)
return 0;
return bitmap.getRowBytes() * bitmap.getHeight();
}
}
public class FileCache {
private File cacheDir;
public FileCache(Context context) {
//Find the dir to save cached images
if (android.os.Environment.getExternalStorageState().equals(
android.os.Environment.MEDIA_MOUNTED))
cacheDir = new File(
android.os.Environment.getExternalStorageDirectory(),
"");
else
cacheDir = context.getCacheDir();
if (!cacheDir.exists())
cacheDir.mkdirs();
}
public File getFile(String url) {
String filename = String.valueOf(url.hashCode());
//String filename = URLEncoder.encode(url);
File f = new File(cacheDir, filename);
return f;
}
public void clear() {
File[] files = cacheDir.listFiles();
if (files == null)
return;
for (File f : files)
f.delete();
}
}
public static class Utils {
public static void CopyStream(InputStream is, OutputStream os) {
final int buffer_size = 1024;
try {
byte[] bytes = new byte[buffer_size];
for (; ; ) {
int count = is.read(bytes, 0, buffer_size);
if (count == -1)
break;
os.write(bytes, 0, count);
}
} catch (Exception ex) {
}
}
}
/* public class SingleItemView extends Activity {
String carimg;
ImageLoader imageLoader = new ImageLoader(this);
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
//Get the view from singleitemview.xml
setContentView(R.layout.singleitemview);
Intent i = getIntent();
//Get the result of CarImageLink
carimg = i.getStringExtra("CarImageLink");
Log.v("carimg", i.getStringExtra("CarImageLink").toString());
int loader = R.drawable.temp_img;
int stub_id = loader;
//Locate the ImageView in singleitemview.xml
ImageView img_car = (ImageView) findViewById(R.id.car_img);
Log.v("Imageview img_car", img_car.toString());
//Capture position and set results to the ImageView
//Passes carimg images URL into ImageLoader.class
imageLoader.DisplayImage(carimg, stub_id, img_car);
}
}*/
}
Related
I am using ViewPager to hold my Fragments. I have two Fragments with different Parse Queries. One of My Fragment has grid view layout. I have created and Adapter for the GridView to load images.
This is my fragment
public class FeedsFragment extends Fragment {
GridView gridview;
List<ParseObject> ob;
FeedsGridAdapter adapter;
private List<ParseFeeds> phonearraylist = null;
View rootView;
public static final String TAG = FeedsFragment.class.getSimpleName();
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
rootView = inflater.inflate(R.layout.feeds_layout,
container, false);
new RemoteDataTask().execute();
return rootView;
}
private class RemoteDataTask extends AsyncTask<Void,Void,Void> {
#Override
protected void onPreExecute() {
super.onPreExecute();
}
#Override
protected Void doInBackground(Void... params) {
// Create the array
phonearraylist = new ArrayList<ParseFeeds>();
try {
// Locate the class table named "SamsungPhones" in Parse.com
ParseQuery<ParseObject> query = new ParseQuery<ParseObject>(
"AroundMe");
// Locate the column named "position" in Parse.com and order list
// by ascending
// query.whereEqualTo(ParseConstants.KEY_RECIPIENT_IDS, ParseUser.getCurrentUser().getUsername());
query.orderByAscending("createdAt");
ob = query.find();
for (ParseObject country : ob) {
ParseFile image = (ParseFile) country.get("videoThumbs");
ParseFeeds map = new ParseFeeds();
map.setPhone(image.getUrl());
phonearraylist.add(map);
}
} catch (ParseException e) {
Log.e("Error", e.getMessage());
e.printStackTrace();
}
return null;
}
#Override
protected void onPostExecute(Void result) {
// Locate the gridview in gridview_main.xml
gridview = (GridView) rootView.findViewById(R.id.gridview);
// Pass the results into ListViewAdapter.java
adapter = new FeedsGridAdapter(FeedsFragment.this.getActivity(),
phonearraylist);
// Binds the Adapter to the ListView
gridview.setAdapter(adapter);
}
}
}
The Adapter I created to load the images into
public static final String TAG = FeedsGridAdapter.class.getSimpleName();
// Declare Variables
Context context;
LayoutInflater inflater;
ImageLoader imageLoader;
private List<ParseFeeds> phonearraylist = null;
private ArrayList<ParseFeeds> arraylist;
public FeedsGridAdapter(Context context, List<ParseFeeds> phonearraylist) {
this.context = context;
this.phonearraylist = phonearraylist;
inflater = LayoutInflater.from(context);
this.arraylist = new ArrayList<ParseFeeds>();
this.arraylist.addAll(phonearraylist);
imageLoader = new ImageLoader(context);
}
public class ViewHolder {
ImageView phone;
}
#Override
public int getCount() {
return phonearraylist.size();
}
#Override
public Object getItem(int position) {
return phonearraylist.get(position);
}
#Override
public long getItemId(int position) {
return position;
}
public View getView(final int position, View view, ViewGroup parent) {
final ViewHolder holder;
if (view == null) {
holder = new ViewHolder();
view = inflater.inflate(R.layout.feeds_layout, null);
// Locate the ImageView in gridview_item.xml
holder.phone = (ImageView) view.findViewById(R.id.videoThumb);
view.setTag(holder);
} else {
holder = (ViewHolder) view.getTag();
}
// Load image into GridView
imageLoader.DisplayImage(phonearraylist.get(position).getPhone(),
holder.phone);
// Capture GridView item click
view.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View arg0) {
// Send single item click data to SingleItemView Class
Intent intent = new Intent(context, SingleVideoView.class);
// Pass all data phone
intent.putExtra("phone", phonearraylist.get(position)
.getPhone());
context.startActivity(intent);
}
});
return view;
}
}
Here its giving me NullPointerException on imageLoader.DisplayImage(phonearraylist.get(position).getPhone(),
holder.phone);
When I run the same code in another project with only one Fragment its working but when I use it in my current project with Two Fargments having different parse queries it gives me NullPointerException.Please help I wasted around 5 days on this to get it working tried everything possible at my end.
Here is my ImageLoader Class
MemoryCache memoryCache = new MemoryCache();
FileCache fileCache;
private Map<ImageView, String> imageViews = Collections
.synchronizedMap(new WeakHashMap<ImageView, String>());
ExecutorService executorService;
// Handler to display images in UI thread
Handler handler = new Handler();
public ImageLoader(Context context) {
fileCache = new FileCache(context);
executorService = Executors.newFixedThreadPool(5);
}
// int stub_id = ;
public void DisplayImage(String url, ImageView imageView) {
imageViews.put(imageView, url);
Bitmap bitmap = memoryCache.get(url);
if (bitmap != null)
imageView.setImageBitmap(bitmap);
else {
queuePhoto(url, imageView);
imageView.setImageResource(R.drawable.camera_iris);
}
}
private void queuePhoto(String url, ImageView imageView) {
PhotoToLoad p = new PhotoToLoad(url, imageView);
executorService.submit(new PhotosLoader(p));
}
private Bitmap getBitmap(String url) {
File f = fileCache.getFile(url);
Bitmap b = decodeFile(f);
if (b != null)
return b;
// Download Images from the Internet
try {
Bitmap bitmap = null;
URL imageUrl = new URL(url);
HttpURLConnection conn = (HttpURLConnection) imageUrl
.openConnection();
conn.setConnectTimeout(30000);
conn.setReadTimeout(30000);
conn.setInstanceFollowRedirects(true);
InputStream is = conn.getInputStream();
OutputStream os = new FileOutputStream(f);
Utils.CopyStream(is, os);
os.close();
conn.disconnect();
bitmap = decodeFile(f);
return bitmap;
} catch (Throwable ex) {
ex.printStackTrace();
if (ex instanceof OutOfMemoryError)
memoryCache.clear();
return null;
}
}
// Decodes image and scales it to reduce memory consumption
private Bitmap decodeFile(File f) {
try {
// Decode image size
BitmapFactory.Options o = new BitmapFactory.Options();
o.inJustDecodeBounds = true;
FileInputStream stream1 = new FileInputStream(f);
BitmapFactory.decodeStream(stream1, null, o);
stream1.close();
// Find the correct scale value. It should be the power of 2.
final int REQUIRED_SIZE = 100;
int width_tmp = o.outWidth, height_tmp = o.outHeight;
int scale = 1;
while (true) {
if (width_tmp / 2 < REQUIRED_SIZE
|| height_tmp / 2 < REQUIRED_SIZE)
break;
width_tmp /= 2;
height_tmp /= 2;
scale *= 2;
}
// Decode with inSampleSize
BitmapFactory.Options o2 = new BitmapFactory.Options();
o2.inSampleSize = scale;
FileInputStream stream2 = new FileInputStream(f);
Bitmap bitmap = BitmapFactory.decodeStream(stream2, null, o2);
stream2.close();
return bitmap;
} catch (FileNotFoundException e) {
} catch (IOException e) {
e.printStackTrace();
}
return null;
}
// Task for the queue
private class PhotoToLoad {
public String url;
public ImageView imageView;
public PhotoToLoad(String u, ImageView i) {
url = u;
imageView = i;
}
}
class PhotosLoader implements Runnable {
PhotoToLoad photoToLoad;
PhotosLoader(PhotoToLoad photoToLoad) {
this.photoToLoad = photoToLoad;
}
#Override
public void run() {
try {
if (imageViewReused(photoToLoad))
return;
Bitmap bmp = getBitmap(photoToLoad.url);
memoryCache.put(photoToLoad.url, bmp);
if (imageViewReused(photoToLoad))
return;
BitmapDisplayer bd = new BitmapDisplayer(bmp, photoToLoad);
handler.post(bd);
} catch (Throwable th) {
th.printStackTrace();
}
}
}
boolean imageViewReused(PhotoToLoad photoToLoad) {
String tag = imageViews.get(photoToLoad.imageView);
if (tag == null || !tag.equals(photoToLoad.url))
return true;
return false;
}
// Used to display bitmap in the UI thread
class BitmapDisplayer implements Runnable {
Bitmap bitmap;
PhotoToLoad photoToLoad;
public BitmapDisplayer(Bitmap b, PhotoToLoad p) {
bitmap = b;
photoToLoad = p;
}
public void run() {
if (imageViewReused(photoToLoad))
return;
if (bitmap != null)
photoToLoad.imageView.setImageBitmap(bitmap);
else
photoToLoad.imageView.setImageResource(R.drawable.camera_iris);
}
}
public void clearCache() {
memoryCache.clear();
fileCache.clear();
}
}
There is a NullPointerException imageLoader.DisplayImage(phonearraylist.get(position).getPhone(), holder.phone);
Which leads to a suspiciously null (ImageView) holder.phone.
Why it must be null ?
Because it might not be lying inside the view you inflated to.
So
You should check if you are inflating a proper layout from resource and not making any of the most common mistakes like using activity/fragment's layout resource instead of using adapter's item layout.
You're welcome.
ImageLoader Initialize like below way
DisplayImageOptions defaultOptions = new DisplayImageOptions.Builder()
.cacheOnDisc()//.imageScaleType(ImageScaleType.EXACTLY)
.bitmapConfig(Bitmap.Config.RGB_565).build();
ImageLoaderConfiguration.Builder builder = new ImageLoaderConfiguration.Builder(
this).defaultDisplayImageOptions(defaultOptions).memoryCache(
new WeakMemoryCache());
Display display = getWindowManager().getDefaultDisplay();
Point size = new Point();
display.getSize(size);
int width = size.x;
int height = size.y;
ImageLoaderConfiguration config = builder.build();
imageLoader = ImageLoader.getInstance();
imageLoader.init(config);
Im beginner and try to work on an app. I want to create a new page/activity when the imageButton on the listView is clicked. (The image is grab from url). Any help is appreciated.
Here is themain.java
public class IngredientCategoryMain extends Activity {
ListView list;
String[] title;
CategoryImageAdapter adapter;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_ingredient_category_main);
list=(ListView)findViewById(R.id.listView);
title = getResources().getStringArray(R.array.titles);
adapter=new CategoryImageAdapter(this, mStrings, title);
list.setAdapter(adapter);
}
#Override
public void onDestroy() {
list.setAdapter(null);
super.onDestroy();
}
public View.OnClickListener listener=new View.OnClickListener() {
#Override
public void onClick(View arg0) {
adapter.imageLoader.clearCache();
adapter.notifyDataSetChanged();
}
};
public void onItemClick(int mPosition) {
String tempValues = title[mPosition];
Toast.makeText(IngredientCategoryMain.this, "You have clicked "+tempValues, Toast.LENGTH_LONG).show();
}
private String[] mStrings={
"https://upload.wikimedia.org/wikipedia/commons/thumb/8/83/Ic_cake_48px.svg/2000px-Ic_cake_48px.svg.png",
"https://pixabay.com/static/uploads/photo/2013/04/01/21/30/can-99137_960_720.png",
"http://publicdomainvectors.org/photos/Gerald_G_Fast_Food_Drinks_(FF_Menu)_9.png",
"https://pixabay.com/static/uploads/photo/2014/03/25/16/59/apple-297775_960_720.png",
"https://pixabay.com/static/uploads/photo/2012/04/16/11/14/mortar-35544_960_720.png",
"https://pixabay.com/static/uploads/photo/2013/07/13/10/05/cattle-156498_960_720.png",
"https://pixabay.com/static/uploads/photo/2013/07/12/15/39/acorn-150258_960_720.png",
"http://publicdomainvectors.org/photos/johnny_automatic_bread_with_knife.png",
"https://pixabay.com/static/uploads/photo/2015/09/13/00/12/chicken-937584_960_720.jpg",
"http://publicdomainvectors.org/photos/bowl-of-steaming-soup-01.png",
"https://pixabay.com/static/uploads/photo/2014/04/02/10/38/fish-304097_960_720.png",
"http://publicdomainvectors.org/photos/Erbsen-lineart.png"
};
}
Adapter
public class CategoryImageAdapter extends BaseAdapter implements OnClickListener {
private Activity activity;
private String[] data;
private String[] title;
private static LayoutInflater inflater = null;
public ImageLoader imageLoader;
public CategoryImageAdapter(Activity a, String[] d, String[] t) {
activity = a;
title = t;
data = d;
inflater = (LayoutInflater)activity.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
imageLoader = new ImageLoader(activity.getApplicationContext());
}
#Override
public int getCount() {
return title.length;
}
#Override
public Object getItem(int position) {
return position;
}
#Override
public long getItemId(int position) {
return position;
}
#Override
public void onClick(View v) {
}
public static class ViewHolder {
public ImageButton imageButton;
public TextView textView;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
View vi = convertView;
ViewHolder holder;
if (convertView == null) {
vi = inflater.inflate(R.layout.ingcategoryrow, null);
holder = new ViewHolder();
holder.textView = (TextView) vi.findViewById(R.id.textView2);
holder.imageButton = (ImageButton) vi.findViewById(R.id.imageButton2);
vi.setTag(holder);
} else
holder = (ViewHolder) vi.getTag();
holder.textView.setText(title[position]);
ImageButton imageButton = holder.imageButton;
imageLoader.DisplayImage(data[position], imageButton);
vi.setOnClickListener(new OnItemClickListener(position));
return vi;
}
private class OnItemClickListener implements OnClickListener{
private int mPosition;
OnItemClickListener(int position) {
mPosition = position;
}
#Override
public void onClick(View arg0) {
IngredientCategoryMain sct = (IngredientCategoryMain)activity;
sct.onItemClick(mPosition);
}
}
ImageLoader
public class ImageLoader {
MemoryCache memoryCache = new MemoryCache();
FileCache fileCache;
private Map<ImageButton, String> imageButtons = Collections.synchronizedMap(new WeakHashMap<ImageButton, String>());
ExecutorService executorService;
Handler handler = new Handler();
public ImageLoader(Context context) {
fileCache = new FileCache(context);
executorService= Executors.newFixedThreadPool(5);
}
final int stub_id=R.drawable.bakingood;
public void DisplayImage(String url, ImageButton imageButton) {
imageButtons.put(imageButton, url);
Bitmap bitmap = memoryCache.get(url);
if(bitmap!=null) {
imageButton.setImageBitmap(bitmap);
} else {
queuePhoto(url, imageButton);
imageButton.setImageResource(stub_id);
}
}
private void queuePhoto(String url, ImageButton imageButton){
PhotoToLoad p = new PhotoToLoad(url, imageButton);
executorService.submit(new PhotosLoader(p));
}
private class PhotoToLoad {
public String url;
public ImageButton imageButton;
public PhotoToLoad(String u, ImageButton i) {
url=u;
imageButton=i;
}
}
class PhotosLoader implements Runnable {
PhotoToLoad photoToLoad;
PhotosLoader(PhotoToLoad photoToLoad) {
this.photoToLoad=photoToLoad;
}
#Override
public void run() {
try{
if(imageButtonReused(photoToLoad))
return;
Bitmap bmp = getBitmap(photoToLoad.url);
memoryCache.put(photoToLoad.url, bmp);
if(imageButtonReused(photoToLoad))
return;
BitmapDisplayer bd=new BitmapDisplayer(bmp, photoToLoad);
handler.post(bd);
} catch (Throwable th) {
th.printStackTrace();
}
}
}
private Bitmap getBitmap(String url) {
File f=fileCache.getFile(url);
Bitmap b= decodeFile(f);
if(b!=null)
return b;
try {
Bitmap bitmap=null;
URL imageUrl = new URL(url);
HttpURLConnection conn = (HttpURLConnection)imageUrl.openConnection();
conn.setConnectTimeout(30000);
conn.setReadTimeout(30000);
conn.setInstanceFollowRedirects(true);
InputStream is=conn.getInputStream();
OutputStream os = new FileOutputStream(f);
Utils.CopyStream(is, os);
os.close();
conn.disconnect();
bitmap = decodeFile(f);
return bitmap;
} catch (Throwable ex) {
ex.printStackTrace();
if(ex instanceof OutOfMemoryError)
memoryCache.clear();
return null;
}
}
private Bitmap decodeFile(File f) {
try {
//Decode image size
BitmapFactory.Options o = new BitmapFactory.Options();
o.inJustDecodeBounds = true;
FileInputStream stream1=new FileInputStream(f);
BitmapFactory.decodeStream(stream1,null,o);
stream1.close();
//Find the correct scale value. It should be the power of 2.
// Set width/height of recreated image
final int REQUIRED_SIZE=85;
int width_tmp=o.outWidth, height_tmp=o.outHeight;
int scale=1;
while(true){
if(width_tmp/2 < REQUIRED_SIZE || height_tmp/2 < REQUIRED_SIZE)
break;
width_tmp/=2;
height_tmp/=2;
scale*=2;
}
//decode with current scale values
BitmapFactory.Options o2 = new BitmapFactory.Options();
o2.inSampleSize=scale;
FileInputStream stream2=new FileInputStream(f);
Bitmap bitmap= BitmapFactory.decodeStream(stream2, null, o2);
stream2.close();
return bitmap;
} catch (FileNotFoundException e) {
}
catch (IOException e) {
e.printStackTrace();
}
return null;
}
boolean imageButtonReused(PhotoToLoad photoToLoad){
String tag=imageButtons.get(photoToLoad.imageButton);
if (tag==null || !tag.equals(photoToLoad.url))
return true;
return false;
}
class BitmapDisplayer implements Runnable {
Bitmap bitmap;
PhotoToLoad photoToLoad;
public BitmapDisplayer(Bitmap b, PhotoToLoad p) {bitmap = b;photoToLoad = p;}
public void run() {
if (imageButtonReused(photoToLoad))
return;
if (bitmap!=null)
photoToLoad.imageButton.setImageBitmap(bitmap);
else
photoToLoad.imageButton.setImageResource(stub_id);
}
}
public void clearCache() {
memoryCache.clear();
fileCache.clear();
}
}
MemoryCache
public class MemoryCache {
private static final String TAG = "MemoryCache";
private Map<String, Bitmap> cache = Collections.synchronizedMap(
new LinkedHashMap<String, Bitmap>(10,1.5f, true));
private long size=0;
private long limit=1000000;
public MemoryCache () {
setLimit(Runtime.getRuntime().maxMemory() / 4);
}
public void setLimit(long limit) {
this.limit = limit;
Log.i(TAG, "MemoryCache will use up to " + limit / 1024. / 1024. + "MB");
}
public Bitmap get(String id) {
try {
if (!cache.containsKey(id))
return null;
return cache.get(id);
} catch (NullPointerException ex) {
ex.printStackTrace();
return null;
}
}
public void put(String id, Bitmap bitmap) {
try{
if(cache.containsKey(id))
size-=getSizeInBytes(cache.get(id));
cache.put(id, bitmap);
size+=getSizeInBytes(bitmap);
checkSize();
}catch (Throwable th) {
th.printStackTrace();
}
}
private void checkSize() {
Log.i(TAG, "cache size="+size+" length="+cache.size());
if(size>limit) {
Iterator<Map.Entry<String, Bitmap>> iter=cache.entrySet().iterator();
while (iter.hasNext()) {
Map.Entry<String, Bitmap> entry=iter.next();
size-=getSizeInBytes(entry.getValue());
iter.remove();
if(size<=limit)
break;
}
Log.i(TAG, "Clean cache.New size "+cache.size());
}
}
public void clear() {
try{
cache.clear();
size=0;
}catch (NullPointerException ex) {
}
}
private long getSizeInBytes(Bitmap bitmap) {
if (bitmap==null)
return 0;
return bitmap.getRowBytes()*bitmap.getHeight();
}
}
FileCache
public class FileCache {
private File cacheDir;
public FileCache(Context context) {
if (android.os.Environment.getExternalStorageState().equals(
android.os.Environment.MEDIA_MOUNTED))
{
//if SDCARD is mounted (SDCARD is present on device and mounted)
cacheDir = new File(
android.os.Environment.getExternalStorageDirectory(),"LazyList");
}
else
{
// if checking on simulator the create cache dir in your application context
cacheDir=context.getCacheDir();
}
if(!cacheDir.exists()){
// create cache dir in your application context
cacheDir.mkdirs();
}
}
public void clear() {
File[] files=cacheDir.listFiles();
if(files==null)
return;
for (File f:files)
f.delete();
}
public File getFile(String url) {
//Identify images by hashcode or encode by URLEncoder.encode.
String filename=String.valueOf(url.hashCode());
File f = new File(cacheDir, filename);
return f;
}
}
Utils
public class Utils {
public static void CopyStream(InputStream is, OutputStream os)
{
final int buffer_size=1024;
try {
byte[] bytes=new byte[buffer_size];
for(;;) {
int count = is.read(bytes, 0, buffer_size);
if (count == -1)
break;
os.write(bytes, 0, count);
}
}
catch (IOException e) {
e.printStackTrace();
}
}
}
In your adapter, after this line:
ImageButton imageButton = holder.imageButton;
do something like this:
imageButton.setOnClickListener(new.View.OnClickListener(){
#Override
Public void onClick(View :)
{
Intent intent = New intent(activity, ExampleActivityName.class);
activity.startActivity(intent);
}
});
The way it works is that every view has an option to react to click events that the user performs ”on him”, all you need to do is to pass an implementation of the View.OnClickListener Interface to the View (via the setOnClickListener method) and that's it.
Second step is to start an activity which is faily easy, you need to create an intent with the current context and the class of the activity you wish to start, and than call the startActivity method from your current context.
In this case, the current context is represented by the activity reference.
add the code of 'startActivity(intent)' in your listitem.onclick - you can check which image is being clicked or also the position and then launch the appropriate activity.
after this line
ImageButton imageButton = holder.imageButton;
just add this lines of code
imageButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
activity.startActivity(new Intent(activity, YourActivityClass.class));
}
});
I'm new in android. I have a problem about loading the image from Json Url to ListView. ListView works only without image.
This is my json url:
{
"infoBooks": [{
"user_name": "carlo",
"title": "Title: Il potere del cane\nAuthor\/s: Don Winslow",
"author": "",
"urlImage": "https:\/\/books.google.it\/books\/content?id=qiLanQEACAAJ&printsec=frontcover&img=1&zoom=1&source=gbs_api"
}, {
"user_name": "ff",
"title": "Title: Incontro con la storia. Con espansione online. Per la Scuola media\nAuthor\/s: Luisa Benucci",
"author": "",
"urlImage": "https:\/\/books.google.it\/books\/content?id=qTzFSgAACAAJ&printsec=frontcover&img=1&zoom=1&source=gbs_api"
}]
}
SearchBooks.java:
public class SearchBooks extends AppCompatActivity {
ListView mListView;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_search_books);
String strUrl = "http://192.168.1.118:8888/webappdb/listViewBooks.php";
DownloadTask downloadTask = new DownloadTask();
downloadTask.execute(strUrl);
mListView = (ListView) findViewById(R.id.listView);
}
private String downloadUrl (String strUrl) throws IOException{
String data = "";
InputStream iStream = null;
try {
URL url = new URL(strUrl);
HttpURLConnection urlConnection = (HttpURLConnection) url.openConnection();
urlConnection.connect();
iStream = urlConnection.getInputStream();
BufferedReader br = new BufferedReader(new InputStreamReader(iStream));
StringBuffer sb = new StringBuffer();
String line = "";
while ((line = br.readLine()) != null) {
sb.append(line);
}
data = sb.toString();
br.close();
}catch (Exception e){
Log.d("Exception while downloading url", e.toString());
}finally {
iStream.close();
}
return data;
}
private class DownloadTask extends AsyncTask<String, Integer, String>{
String data = null;
#Override
protected String doInBackground(String... url) {
try {
data = downloadUrl(url[0]);
} catch (IOException e) {
Log.d("Background Task", e.toString());
}
return data;
}
#Override
protected void onPostExecute(String result) {
super.onPostExecute(result);
ListViewLoaderTask listViewLoaderTask = new ListViewLoaderTask();
listViewLoaderTask.execute(result);
}
}
private class ListViewLoaderTask extends AsyncTask<String, Void, SimpleAdapter>{
JSONObject jObject;
#Override
protected SimpleAdapter doInBackground(String... strJson) {
try {
jObject = new JSONObject(strJson[0]);
customAdapter customAdapter = new customAdapter();
customAdapter.parse(jObject);
} catch (JSONException e) {
Log.d("JSON Exception1", e.toString());
}
customAdapter customAdapter = new customAdapter();
List<HashMap<String, Object>> books = null;
try {
books = customAdapter.parse(jObject);
} catch (Exception e){
Log.d("Exception", e.toString());
}
String infoFrom[] = {"user_name", "details", "launcherImage"};
int infoTo[] = {R.id.user_name_search, R.id.bookDescriptionSearch, R.id.coverBookSearch};
SimpleAdapter adapter = new SimpleAdapter(getBaseContext(), books, R.layout.row_list_books, infoFrom, infoTo);
return adapter;
}
#Override
protected void onPostExecute(SimpleAdapter adapter) {
mListView.setAdapter(adapter);
for (int i = 0; i < adapter.getCount(); i++){
HashMap<String, Object> hm = (HashMap<String, Object>) adapter.getItem(i);
String imgUrl = (String) hm.get("urlImage");
ImageLoaderTask imageLoaderTask = new ImageLoaderTask();
hm.put("urlImage", imgUrl);
hm.put("position", i);
imageLoaderTask.execute(hm);
}
}
}
private class ImageLoaderTask extends AsyncTask<HashMap<String, Object>, Void, HashMap<String, Object>>{
#Override
protected HashMap<String, Object> doInBackground(HashMap<String, Object>... hm) {
InputStream iStream = null;
String imgUrl = (String) hm[0].get("urlImage");
int position = (Integer) hm[0].get("position");
URL url;
try {
url = new URL(imgUrl);
HttpURLConnection urlConnection = (HttpURLConnection) url.openConnection();
urlConnection.connect();
iStream = urlConnection.getInputStream();
File cacheDirectory = getBaseContext().getCacheDir();
File tmpFile = new File (cacheDirectory.getPath() + "/wpta_" + position + ".png");
FileOutputStream fOutputStream = new FileOutputStream(tmpFile);
Bitmap b = BitmapFactory.decodeStream(iStream);
b.compress(Bitmap.CompressFormat.PNG, 100, fOutputStream);
fOutputStream.flush();
fOutputStream.close();
HashMap<String, Object> hmBitmap = new HashMap<String, Object>();
hmBitmap.put("launcherImage", tmpFile.getPath());
hmBitmap.put("position", position);
return hmBitmap;
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return null;
}
#Override
protected void onPostExecute(HashMap<String, Object> result) {
String path = (String) result.get("launcherImage");
int position = (Integer) result.get("position");
SimpleAdapter simpleAdapter = (SimpleAdapter) mListView.getAdapter();
HashMap<String, Object> hm = (HashMap<String, Object>) simpleAdapter.getItem(position);
hm.put("launcherImage", path);
simpleAdapter.notifyDataSetChanged();
}
}
}
customAdapter.java :
public class customAdapter{
public List<HashMap<String, Object>> parse(JSONObject JObject) {
JSONArray infoBooks = null;
try {
infoBooks = JObject.getJSONArray("infoBooks");
} catch (JSONException e) {
e.printStackTrace();
}
return getBooks(infoBooks);
}
private List<HashMap<String, Object>> getBooks(JSONArray infoBooks){
int booksCount = infoBooks.length();
List<HashMap<String, Object>> bookList = new ArrayList<HashMap<String, Object>>();
HashMap<String, Object> book;
for(int i = 0; i < booksCount; i++) {
try {
book = getBook((JSONObject) infoBooks.get(i));
bookList.add(book);
} catch (JSONException e) {
e.printStackTrace();
}
}
return bookList;
}
private HashMap<String, Object> getBook(JSONObject jBook){
HashMap<String, Object> book = new HashMap<String, Object>();
String user_name = "";
String title = "";
String author = "";
String urlImage = "";
try {
user_name = jBook.getString("user_name");
title = jBook.getString("title");
author = jBook.getString("author");
urlImage = jBook.getString("urlImage");
String details = "Title: " + title + "\n" +
"Author/s: " + author;
book.put("user_name", user_name);
book.put("details", details);
book.put("launcherImage", R.mipmap.ic_launcher);
book.put("urlImage", urlImage);
} catch (JSONException e) {
e.printStackTrace();
}
return book;
}
}
logcat:
03-10 12:02:42.088 969-1029/? E/lights: write_led_info failed to open -1
03-10 12:02:42.088 969-1029/? E/lights: write_led_info failed to open -1
03-10 12:02:42.188 969-1065/? E/native: do suspend false
03-10 12:02:42.288 969-1065/? E/WifiStateMachine: WifiStateMachine CMD_START_SCAN source 10007 txSuccessRate=0,00 rxSuccessRate=0,13 targetRoamBSSID=any RSSI=-73
03-10 12:02:42.388 247-569/? E/qdutils: int qdutils::getHDMINode(): Failed to open fb node 2
03-10 12:02:42.388 247-569/? E/qdutils: int qdutils::getHDMINode(): Failed to find HDMI node
03-10 12:02:42.638 969-1104/? E/lights: write_int failed to open -1
03-10 12:02:42.718 969-969/? E/LocSvc_flp: I/===> int flp_inject_location(FlpLocation*) line 222
03-10 12:02:42.728 969-1336/? E/LocSvc_ApiV02: I/<--- void globalRespCb(locClientHandleType, uint32_t, locClientRespIndUnionType, void*) line 125 QMI_LOC_INJECT_POSITION_REQ_V02
03-10 12:02:42.738 969-1367/? E/LocSvc_ApiV02: I/<--- void globalRespCb(locClientHandleType, uint32_t, locClientRespIndUnionType, void*) line 125 QMI_LOC_INJECT_POSITION_REQ_V02
03-10 12:02:43.238 274-763/? E/FastThread: did not receive expected priority boost
03-10 12:02:44.138 969-1104/? E/lights: write_int failed to open -1
03-10 12:02:44.838 969-981/? E/PersonaManagerService: inState(): stateMachine is null !!
03-10 12:02:45.078 270-270/? E/SMD: DCD OFF
03-10 12:02:45.568 23494-23494/gamingproject.sellmybooks E/AndroidRuntime: FATAL EXCEPTION: main
Process: gamingproject.sellmybooks, PID: 23494
java.lang.NullPointerException: Attempt to invoke virtual method 'java.lang.Object java.util.HashMap.get(java.lang.Object)' on a null object reference
at gamingproject.sellmybooks.SearchBooks$ImageLoaderTask.onPostExecute(SearchBooks.java:216)
at gamingproject.sellmybooks.SearchBooks$ImageLoaderTask.onPostExecute(SearchBooks.java:174)
at android.os.AsyncTask.finish(AsyncTask.java:632)
at android.os.AsyncTask.access$600(AsyncTask.java:177)
at android.os.AsyncTask$InternalHandler.handleMessage(AsyncTask.java:645)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:135)
at android.app.ActivityThread.main(ActivityThread.java:5536)
at java.lang.reflect.Method.invoke(Native Method)
at java.lang.reflect.Method.invoke(Method.java:372)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1397)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1192)
03-10 12:02:45.578 969-31049/? E/android.os.Debug: ro.product_ship = true
03-10 12:02:45.578 969-31049/? E/android.os.Debug: ro.debug_level = 0x4f4c
03-10 12:02:45.668 2326-31050/? E/SQLiteLog: (284) automatic index on crash_info_summary(package_name_touched)
03-10 12:02:45.728 2326-31050/? E/SQLiteLog: (284) automatic index on crash_info_summary(package_name_touched)
03-10 12:02:48.078 270-270/? E/SMD: DCD OFF
I don't understand the error.
Thanks in advance.
You can not load an image from a url directly.
You should convert it to drawable before load it in a imageview.
Take a look at this library to load images in Android.
http://square.github.io/picasso/
Why are you making the code so complex ? Keep it simple. I have a Demo code. Maybe it can help you. Just Create a Model Class Which you Require. Other things are the same.
public class MainActivity extends AppCompatActivity {
private Button btnHit;
private HttpURLConnection connection = null;
private URL url;
private BufferedReader reader = null;
private StringBuffer buffer;
private ListView lvMovies;
private ProgressDialog dialog;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
dialog = new ProgressDialog(this);
dialog.setIndeterminate(true);
dialog.setCancelable(false);
dialog.setMessage("Loading !! Please wait..");
DisplayImageOptions defaultOptions = new DisplayImageOptions.Builder()
.cacheInMemory(true)
.cacheOnDisk(true)
.build();
ImageLoaderConfiguration config = new ImageLoaderConfiguration.Builder(getApplicationContext())
.defaultDisplayImageOptions(defaultOptions)
.build();
ImageLoader.getInstance().init(config);
lvMovies = (ListView) findViewById(R.id.lvMovies);
new JSONTask().execute("http://jsonparsing.parseapp.com/jsonData/moviesData.txt");
}
public class JSONTask extends AsyncTask<String, String, List<MovieModel>> {
#Override
protected void onPreExecute() {
super.onPreExecute();
dialog.show();
}
#Override
protected List<MovieModel> doInBackground(String... params) {
try {
url = new URL(params[0]);
connection = (HttpURLConnection) url.openConnection();
connection.connect();
InputStream stream = connection.getInputStream();
reader = new BufferedReader(new InputStreamReader(stream));
buffer = new StringBuffer();
String line = "";
while ((line = reader.readLine()) != null) {
buffer.append(line);
}
String finalJson = buffer.toString();
JSONObject parentObject = new JSONObject(finalJson);
JSONArray parentArray = parentObject.getJSONArray("movies");
List<MovieModel> movieModelList = new ArrayList<>();
Gson gson = new Gson();
for (int i = 0; i < parentArray.length(); i++) {
JSONObject finalObject = parentArray.getJSONObject(i);
MovieModel movieModel = gson.fromJson(finalObject.toString(), MovieModel.class);
movieModelList.add(movieModel);
}
return movieModelList;
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} catch (JSONException e) {
e.printStackTrace();
} finally {
if (connection != null) {
connection.disconnect();
}
try {
if (reader != null) {
reader.close();
}
} catch (IOException e) {
e.printStackTrace();
}
}
return null;
}
#Override
protected void onPostExecute(List<MovieModel> result) {
super.onPostExecute(result);
dialog.dismiss();
MovieAdapter adapter = new MovieAdapter(getApplicationContext(), R.layout.row, result);
lvMovies.setAdapter(adapter);
// TODO Need to set Data on List
}
}
public class MovieAdapter extends ArrayAdapter {
private List<MovieModel> movieModelList;
private int resource;
private LayoutInflater inflater;
public MovieAdapter(Context context, int resource, List<MovieModel> objects) {
super(context, resource, objects);
movieModelList = objects;
this.resource = resource;
inflater = (LayoutInflater) getSystemService(LAYOUT_INFLATER_SERVICE);
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
ViewHolder holder = null;
if (convertView == null) {
holder = new ViewHolder();
convertView = inflater.inflate(resource, null);
holder.ivMovieIcon = (ImageView) convertView.findViewById(R.id.ivIcon);
holder.tvMovie = (TextView) convertView.findViewById(R.id.tvMovie);
holder.tvTagline = (TextView) convertView.findViewById(R.id.tvTagLine);
holder.tvYear = (TextView) convertView.findViewById(R.id.tvYear);
holder.tvDuration = (TextView) convertView.findViewById(R.id.tvDuration);
holder.tvDirector = (TextView) convertView.findViewById(R.id.tvDirector);
holder.rbMovieRating = (RatingBar) convertView.findViewById(R.id.rbMovie);
holder.tvCast = (TextView) convertView.findViewById(R.id.tvCast);
holder.tvStory = (TextView) convertView.findViewById(R.id.tvStory);
convertView.setTag(holder);
} else {
holder = (ViewHolder) convertView.getTag();
}
final ProgressBar progressBar = (ProgressBar) convertView.findViewById(R.id.progressBar);
ImageLoader.getInstance().displayImage(movieModelList.get(position).getImage(), holder.ivMovieIcon, new ImageLoadingListener() {
#Override
public void onLoadingStarted(String imageUri, View view) {
progressBar.setVisibility(View.VISIBLE);
}
#Override
public void onLoadingFailed(String imageUri, View view, FailReason failReason) {
progressBar.setVisibility(View.GONE);
}
#Override
public void onLoadingComplete(String imageUri, View view, Bitmap loadedImage) {
progressBar.setVisibility(View.GONE);
}
#Override
public void onLoadingCancelled(String imageUri, View view) {
progressBar.setVisibility(View.GONE);
}
});
holder.tvMovie.setText(movieModelList.get(position).getMovie());
holder.tvTagline.setText(movieModelList.get(position).getTagline());
holder.tvYear.setText("Year : " + movieModelList.get(position).getYear());
holder.tvDuration.setText(movieModelList.get(position).getDuration());
holder.tvDirector.setText(movieModelList.get(position).getDirector());
// Rating Bar
holder.rbMovieRating.setRating(movieModelList.get(position).getRating() / 2);
Log.v("Rating is", "" + movieModelList.get(position).getRating() / 2);
StringBuffer stringBuffer = new StringBuffer();
for (MovieModel.Cast cast : movieModelList.get(position).getCastList()) {
stringBuffer.append(cast.getName() + ", ");
}
holder.tvCast.setText(stringBuffer);
holder.tvStory.setText(movieModelList.get(position).getStory());
return convertView;
}
class ViewHolder {
private ImageView ivMovieIcon;
private TextView tvMovie;
private TextView tvTagline;
private TextView tvYear;
private TextView tvDuration;
private TextView tvDirector;
private RatingBar rbMovieRating;
private TextView tvCast;
private TextView tvStory;
}
}
}
Try my Adapter code:
public class MyAdapter extends BaseAdapter implements OnClickListener {
Context con;
ArrayList<Model> mlist;
LayoutInflater inflater=null;
public MyAdapter(Context con,ArrayList<Model> list,SpinnerInterface sp)
{
this.con=con;
this.mlist=list;
inflater=(LayoutInflater)con.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
// UNIVERSAL IMAGE LOADER SETUP
DisplayImageOptions defaultOptions = new DisplayImageOptions.Builder()
.cacheOnDisc(true).cacheInMemory(true)
.imageScaleType(ImageScaleType.EXACTLY)
.displayer(new FadeInBitmapDisplayer(300)).build();
ImageLoaderConfiguration config = new ImageLoaderConfiguration.Builder(con)
.defaultDisplayImageOptions(defaultOptions)
.memoryCache(new WeakMemoryCache())
.discCacheSize(100 * 1024 * 1024).build();
ImageLoader.getInstance().init(config);
// END - UNIVERSAL IMAGE LOADER SETUP
}
#Override
public int getCount() {
// TODO Auto-generated method stub
return mlist.size();
}
#Override
public Object getItem(int position) {
// TODO Auto-generated method stub
return mlist.get(position);
}
#Override
public long getItemId(int position) {
// TODO Auto-generated method stub
return position;
}
#Override
public int getViewTypeCount() {
if (getCount() != 0)
return getCount();
return 1;
}
#Override
public View getView(final int position, View convertView, ViewGroup parent) {
// TODO Auto-generated method stub
model=mlist.get(position);
ViewHolder holder=null;
if(convertView==null){
convertView=inflater.inflate(R.layout.product_layour,parent,false);
holder=new ViewHolder();
holder.img1=(ImageView)convertView.findViewById(R.id.imageViewProductImage);
convertView.setTag(holder);
}else{ holder=(ViewHolder)convertView.getTag(); }
String img_url=model.getPhoto();
ImageLoader imageLoader = ImageLoader.getInstance();
DisplayImageOptions options = new DisplayImageOptions.Builder().cacheInMemory(true)
.cacheOnDisc(true).resetViewBeforeLoading(true)
.showImageForEmptyUri(R.drawable.productimg)
.showImageOnFail(R.drawable.productimg)
.showImageOnLoading(R.drawable.productimg).build();
//download and display image from url
imageLoader.displayImage(img_url,holder.img1, options);
return convertView;
}
private class ViewHolder{
public ImageView img1 ;
}
}
Hope it helps you
Check this URL I am USING :: http://54.218.73.244:7006/DescriptionSortedRating/
Images will append with relative path from JSON out put using restaurantIMAGE
EX::
http://54.218.73.244:7006/CopperChimney1.jpg
I am using restaurantIMAGE from JSON
{
"restaurants": [
{
"restaurantID": 4,
"restaurantNAME": "CopperChimney1",
"restaurantIMAGE": "MarkBoulevard1.jpg",
"restaurantDISTANCE": 15,
"restaurantTYPE": "Indian",
"restaurantRATING": 1,
"restaurantPrice": 11,
"restaurantTime": "9am t0 8pm"
},
{
"restaurantID": 1,
"restaurantNAME": "CopperChimney",
"restaurantIMAGE": "CopperChimney.png",
"restaurantDISTANCE": 5,
"restaurantTYPE": "Indian",
"restaurantRATING": 3,
"restaurantPrice": 20,
"restaurantTime": "8pm to 11pm"
},
I am USING IMAGE LOADER
ImageLoader.java
public class ImageLoader {
MemoryCache memoryCache = new MemoryCache();
FileCache fileCache;
private Map<ImageView, String> imageViews = Collections
.synchronizedMap(new WeakHashMap<ImageView, String>());
ExecutorService executorService;
// Handler to display images in UI thread
Handler handler = new Handler();
public ImageLoader(Context context) {
fileCache = new FileCache(context);
executorService = Executors.newFixedThreadPool(5);
}
final int stub_id = R.drawable.temp_img;
public void DisplayImage(String url, ImageView imageView) {
imageViews.put(imageView, url);
Bitmap bitmap = memoryCache.get(url);
if (bitmap != null)
imageView.setImageBitmap(bitmap);
else {
queuePhoto(url, imageView);
imageView.setImageResource(stub_id);
}
}
private void queuePhoto(String url, ImageView imageView) {
PhotoToLoad p = new PhotoToLoad(url, imageView);
executorService.submit(new PhotosLoader(p));
}
private Bitmap getBitmap(String url) {
File f = fileCache.getFile(url);
Bitmap b = decodeFile(f);
if (b != null)
return b;
// Download Images from the Internet
try {
Bitmap bitmap = null;
URL imageUrl = new URL(url);
HttpURLConnection conn = (HttpURLConnection) imageUrl
.openConnection();
conn.setConnectTimeout(30000);
conn.setReadTimeout(30000);
conn.setInstanceFollowRedirects(true);
InputStream is = conn.getInputStream();
OutputStream os = new FileOutputStream(f);
Utils.CopyStream(is, os);
os.close();
conn.disconnect();
bitmap = decodeFile(f);
return bitmap;
} catch (Throwable ex) {
ex.printStackTrace();
if (ex instanceof OutOfMemoryError)
memoryCache.clear();
return null;
}
}
// Decodes image and scales it to reduce memory consumption
private Bitmap decodeFile(File f) {
try {
// Decode image size
BitmapFactory.Options o = new BitmapFactory.Options();
o.inJustDecodeBounds = true;
FileInputStream stream1 = new FileInputStream(f);
BitmapFactory.decodeStream(stream1, null, o);
stream1.close();
// Find the correct scale value. It should be the power of 2.
// Recommended Size 512
final int REQUIRED_SIZE = 70;
int width_tmp = o.outWidth, height_tmp = o.outHeight;
int scale = 1;
while (true) {
if (width_tmp / 2 < REQUIRED_SIZE
|| height_tmp / 2 < REQUIRED_SIZE)
break;
width_tmp /= 2;
height_tmp /= 2;
scale *= 2;
}
// Decode with inSampleSize
BitmapFactory.Options o2 = new BitmapFactory.Options();
o2.inSampleSize = scale;
FileInputStream stream2 = new FileInputStream(f);
Bitmap bitmap = BitmapFactory.decodeStream(stream2, null, o2);
stream2.close();
return bitmap;
} catch (FileNotFoundException e) {
} catch (IOException e) {
e.printStackTrace();
}
return null;
}
// Task for the queue
private class PhotoToLoad {
public String url;
public ImageView imageView;
public PhotoToLoad(String u, ImageView i) {
url = u;
imageView = i;
}
}
class PhotosLoader implements Runnable {
PhotoToLoad photoToLoad;
PhotosLoader(PhotoToLoad photoToLoad) {
this.photoToLoad = photoToLoad;
}
#Override
public void run() {
try {
if (imageViewReused(photoToLoad))
return;
Bitmap bmp = getBitmap(photoToLoad.url);
memoryCache.put(photoToLoad.url, bmp);
if (imageViewReused(photoToLoad))
return;
BitmapDisplayer bd = new BitmapDisplayer(bmp, photoToLoad);
handler.post(bd);
} catch (Throwable th) {
th.printStackTrace();
}
}
}
boolean imageViewReused(PhotoToLoad photoToLoad) {
String tag = imageViews.get(photoToLoad.imageView);
if (tag == null || !tag.equals(photoToLoad.url))
return true;
return false;
}
// Used to display bitmap in the UI thread
class BitmapDisplayer implements Runnable {
Bitmap bitmap;
PhotoToLoad photoToLoad;
public BitmapDisplayer(Bitmap b, PhotoToLoad p) {
bitmap = b;
photoToLoad = p;
}
public void run() {
if (imageViewReused(photoToLoad))
return;
if (bitmap != null)
photoToLoad.imageView.setImageBitmap(bitmap);
else
photoToLoad.imageView.setImageResource(stub_id);
}
}
public void clearCache() {
memoryCache.clear();
fileCache.clear();
}
}
Utils,FileCache,MemoryCache java files are also there
RestaurantDescPhotos.java
public class RestaurantDescPhotos extends Activity {
// url to make request
private static String url = "http://54.218.73.244:7006/DescriptionSortedRating/";
String restaurant_name, cc_res;
ProgressDialog progressDialog;
JSONObject jsonObject;
JSONArray first_array;
ImageLoader imageLoader;
TextView textView;
TextView text;
private SparseArray<String> imagesMap = new SparseArray<String>();
ArrayList<HashMap<String, String>> list_of_images = new ArrayList<HashMap<String, String>>();
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.restaurant_desc_photos);
imageLoader=new ImageLoader(RestaurantDescPhotos.this);
progressDialog = new ProgressDialog(RestaurantDescPhotos.this);
new ParsingAsync().execute();
}
private class ParsingAsync extends AsyncTask<Void, Void, Void> {
#Override
protected void onPreExecute() {
super.onPreExecute();
progressDialog = ProgressDialog.show(RestaurantDescPhotos.this, "",
"Please Wait", true, false);
}
#Override
protected Void doInBackground(Void... params) {
// TODO Auto-generated method stub
String _response = null;
try {
HttpClient httpclient = new DefaultHttpClient();
httpclient.getParams().setParameter(
CoreProtocolPNames.PROTOCOL_VERSION,
HttpVersion.HTTP_1_1);
HttpGet request = new HttpGet(url);
HttpResponse response = httpclient.execute(request);
HttpEntity resEntity = response.getEntity();
_response = EntityUtils.toString(resEntity);
jsonObject = new JSONObject(_response);
first_array = jsonObject.getJSONArray("restaurants");
} catch (JSONException e) {
e.printStackTrace();
} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return null;
}
#Override
protected void onPostExecute(Void result) {
// TODO Auto-generated method stub
super.onPostExecute(result);
progressDialog.dismiss();
// TextView timedisplay=(TextView)
// findViewById(R.id.RestaurantTimeID);
for (int i = 0; i < first_array.length(); i++) {
try {
JSONObject detail_obj = first_array.getJSONObject(i);
HashMap<String, String> map_for_images = new HashMap<String, String>();
int id = detail_obj.getInt("_id");
String IMAGES = "http://54.218.73.244:7006/"+detail_obj.getString("restaurantIMAGE");
map_for_images.put("Starters", IMAGES);
list_of_images.add(map_for_images);
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
ImageView imageView = (ImageView) findViewById(R.id.DISP_IMG);
imageLoader.DisplayImage(url, imageView);
}
}
}
I am facing the problems in setting the images onto image view using image loader
There is some problem in RestaurantDescPhotos.java ... I am not able to figure it out
Any Ideas
The url content is not a valid image url:
imageLoader.DisplayImage(url, imageView);
I tried a fixed image url, and image is loaded successfully:
String path = "http://54.218.73.244:7006/CopperChimney1.jpg";
imageLoader.DisplayImage(path, imageView);
I have an ImageView called tab1. My code looks this.
import java.io.InputStream;
import java.net.URL;
import android.app.Activity;
import android.graphics.drawable.Drawable;
import android.os.Bundle;
import android.widget.ImageView;
import android.widget.TabHost;
import android.widget.Toast;
public class Paikallissaa extends Activity {
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
TabHost tabs = (TabHost) findViewById(R.id.tabhost);
tabs.setup();
TabHost.TabSpec spec = tabs.newTabSpec("tag1");
try {
ImageView iv = (ImageView) findViewById(R.id.tab1);
URL url = new URL("http://cdn.fmi.fi/weather-observations/products/finland/finland-weather-observations-map.png");
InputStream content = (InputStream) url.getContent();
Drawable d = Drawable.createFromStream(content, "src");
iv.setImageDrawable(d);
} catch (Exception e) {
Toast.makeText(this, "Error getting image: " + e, Toast.LENGTH_SHORT);
}
spec.setContent(R.id.tab1);
spec.setIndicator("Koko maa");
tabs.addTab(spec);
spec = tabs.newTabSpec("tag2");
spec.setContent(R.id.tab2);
spec.setIndicator("Raisio");
tabs.addTab(spec);
}
}
(Ash I suck with the code block thing...)
It wont update the image. What's wrong? It keeps showing the image I set there earlier in main.xml.
To do this i've been using a helper class that i found somewhere on the internet and modified a tiny bit. It takes care of caching the image and loading the image on a background thread.
Since your image changes on the server you might want to remove the caching portion of this code.
Usage:
ImageLoader loader = new ImageLoader(this);
loader.DisplayImage(String.format(headshotUrl, data.Id), this, headshot);
here it is:
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.URL;
import java.util.HashMap;
import java.util.Stack;
import android.app.Activity;
import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.util.Log;
import android.widget.ImageView;
public class ImageLoader
{
public static String TAG = "xxx";
// the simplest in-memory cache implementation. This should be replaced with
// something like SoftReference or BitmapOptions.inPurgeable(since 1.6)
private HashMap<String, Bitmap> cache = new HashMap<String, Bitmap>();
private File cacheDir;
public ImageLoader(Context context)
{
photoLoaderThread.setPriority(Thread.NORM_PRIORITY - 1);
cacheDir = Utilities.GetCacheDir(context);
}
final int stub_id = R.drawable.face_placeholder;
public void DisplayImage(String url, Activity activity, ImageView imageView)
{
imageView.setTag(url);
Log.i(TAG, url);
if (cache.containsKey(url))
imageView.setImageBitmap(cache.get(url));
else
{
queuePhoto(url, activity, imageView);
imageView.setImageResource(stub_id);
}
}
private void queuePhoto(String url, Activity activity, ImageView imageView)
{
// This ImageView may be used for other images before. So there may be
// some old tasks in the queue. We need to discard them.
photosQueue.Clean(imageView);
PhotoToLoad p = new PhotoToLoad(url, imageView);
synchronized (photosQueue.photosToLoad)
{
photosQueue.photosToLoad.push(p);
photosQueue.photosToLoad.notifyAll();
}
// start thread if it's not started yet
if (photoLoaderThread.getState() == Thread.State.NEW)
photoLoaderThread.start();
}
private Bitmap getBitmap(String url)
{
// I identify images by hashcode. Not a perfect solution, good for the
// demo.
String filename = String.valueOf(url.hashCode());
File f = new File(cacheDir, filename);
// from SD cache
Bitmap b = decodeFile(f);
if (b != null)
return b;
// from web
try
{
Bitmap bitmap = null;
InputStream is = new URL(url).openStream();
OutputStream os = new FileOutputStream(f);
Utilities.CopyStream(is, os);
os.close();
bitmap = decodeFile(f);
return bitmap;
} catch (Exception ex)
{
ex.printStackTrace();
return null;
}
}
// decodes image and scales it to reduce memory consumption
private Bitmap decodeFile(File f)
{
try
{
// decode image size
BitmapFactory.Options o = new BitmapFactory.Options();
o.inJustDecodeBounds = true;
BitmapFactory.decodeStream(new FileInputStream(f), null, o);
// Find the correct scale value. It should be the power of 2.
final int REQUIRED_SIZE = 70;
int width_tmp = o.outWidth, height_tmp = o.outHeight;
int scale = 1;
while (true)
{
if (width_tmp / 2 < REQUIRED_SIZE || height_tmp / 2 < REQUIRED_SIZE)
break;
width_tmp /= 2;
height_tmp /= 2;
scale *= 2;
}
// decode with inSampleSize
BitmapFactory.Options o2 = new BitmapFactory.Options();
o2.inSampleSize = scale;
return BitmapFactory.decodeStream(new FileInputStream(f), null, o2);
} catch (FileNotFoundException e)
{
e.printStackTrace();
}
return null;
}
// Task for the queue
private class PhotoToLoad
{
public String url;
public ImageView imageView;
public PhotoToLoad(String u, ImageView i)
{
url = u;
imageView = i;
}
}
PhotosQueue photosQueue = new PhotosQueue();
public void stopThread()
{
photoLoaderThread.interrupt();
}
// stores list of photos to download
class PhotosQueue
{
private Stack<PhotoToLoad> photosToLoad = new Stack<PhotoToLoad>();
// removes all instances of this ImageView
public void Clean(ImageView image)
{
for (int j = 0; j < photosToLoad.size();)
{
if (photosToLoad.get(j).imageView == image)
photosToLoad.remove(j);
else
++j;
}
};
}
class PhotosLoader extends Thread
{
public void run()
{
try
{
while (true)
{
// thread waits until there are any images to load in the
// queue
if (photosQueue.photosToLoad.size() == 0)
synchronized (photosQueue.photosToLoad)
{
photosQueue.photosToLoad.wait();
}
if (photosQueue.photosToLoad.size() != 0)
{
PhotoToLoad photoToLoad;
synchronized (photosQueue.photosToLoad)
{
photoToLoad = photosQueue.photosToLoad.pop();
}
Bitmap bmp = getBitmap(photoToLoad.url);
cache.put(photoToLoad.url, bmp);
Object tag = photoToLoad.imageView.getTag();
if (tag != null && ((String) tag).equals(photoToLoad.url))
{
BitmapDisplayer bd = new BitmapDisplayer(bmp, photoToLoad.imageView);
Activity a = (Activity) photoToLoad.imageView.getContext();
a.runOnUiThread(bd);
}
}
if (Thread.interrupted())
break;
}
} catch (InterruptedException e)
{
e.printStackTrace();
}
}
}
PhotosLoader photoLoaderThread = new PhotosLoader();
// Used to display bitmap in the UI thread
class BitmapDisplayer implements Runnable
{
Bitmap bitmap;
ImageView imageView;
public BitmapDisplayer(Bitmap b, ImageView i)
{
bitmap = b;
imageView = i;
}
public void run()
{
Log.i(TAG, "BitmapDisplayer run()");
if (bitmap != null)
imageView.setImageBitmap(bitmap);
else
imageView.setImageResource(stub_id);
}
}
public void clearCache()
{
// clear memory cache
cache.clear();
// clear SD cache
File[] files = cacheDir.listFiles();
for (File f : files)
f.delete();
}
}
in a utility class i have my GetCacheDir(...)
public static File GetCacheDir(Context context)
{
File cacheDir;
if (android.os.Environment.getExternalStorageState().equals(android.os.Environment.MEDIA_MOUNTED))
cacheDir = new File(android.os.Environment.getExternalStorageDirectory(), "com.example.app");
else
cacheDir = context.getCacheDir();
if (!cacheDir.exists())
cacheDir.mkdirs();
return cacheDir;
}
CopyStream function:
public static void CopyStream(InputStream is, OutputStream os)
{
final int buffer_size = 1024;
try
{
byte[] bytes = new byte[buffer_size];
for (;;)
{
int count = is.read(bytes, 0, buffer_size);
if (count == -1)
break;
os.write(bytes, 0, count);
}
} catch (Exception ex)
{
}
}
To get the image from the internet try the following,
HttpGet httpRequest = new HttpGet(URI.create("http://cdn.fmi.fi/weather-observations/products/finland/finland-weather-observations-map.png") );
HttpClient httpclient = new DefaultHttpClient();
HttpResponse response = (HttpResponse) httpclient.execute(httpRequest);
HttpEntity entity = response.getEntity();
BufferedHttpEntity bufHttpEntity = new BufferedHttpEntity(entity);
bmp = BitmapFactory.decodeStream(bufHttpEntity.getContent());
ImageView iv = (ImageView) findViewById(R.id.tab1);
iv.setImageBitmat(bmp);
httpRequest.abort();
This will download an image and set it to an image view, taken from an app I helped write. I stripped out some of the useless code that I was using, but the methods remain the same.
public void setImage(){
imageView.setImageURI(DownloadImage);
}
public String DownloadImage(){
string filepath = DownloadFromUrl("url","filename.png");
}
public String DownloadFromUrl(String imageURL, String fileName) {
File file = new File(PATH + fileName);
try {
URL url = new URL(imageURL);
long startTime = System.currentTimeMillis();
Log.d("ImageManager", "download begining");
Log.d("ImageManager", "download url:" + url);
Log.d("ImageManager", "downloaded file name:" + fileName);
/* Open a connection to that URL. */
URLConnection ucon = url.openConnection();
/*
* Define InputStreams to read from the URLConnection.
*/
InputStream is = ucon.getInputStream();
BufferedInputStream bis = new BufferedInputStream(is);
/*
* Read bytes to the Buffer until there is nothing more to read(-1).
*/
ByteArrayBuffer baf = new ByteArrayBuffer(50);
int current = 0;
while ((current = bis.read()) != -1) {
baf.append((byte) current);
}
/* Convert the Bytes read to a String. */
FileOutputStream fos = new FileOutputStream(file);
fos.write(baf.toByteArray());
fos.close();
Log.d("ImageManager",
"download ready in"
+ ((System.currentTimeMillis() - startTime) / 1000)
+ " sec");
} catch (IOException e) {
Log.d("ImageManager", "Error: " + e);
}
return file.toString();
}