I'm relatively new to this and I've been using the AndroidHttpClient just fine to help with downloading images to my app via Parse. Now with Sdk 23, I've got to rewrite a few of my classes. My question is fairly simple.
Let's take the following code, which doesn't do anything as an example:
new TwinPrimeSDK(getApplicationContext(), "12345678-1234-1234-1234-123456789012-1234567-123");
try {
URLConnection httpConn = TPURLConnection.openConnection("your-URL");
} catch (IOException e) {
e.printStackTrace();
}
What does the "your-URL" refer to? With AndroidHttpClient over Apache I never had to use a specific URL for anything. It just worked.
Update:
public class ImageLoader {
// Last argument true for LRU ordering
private Map<String, String> objectIdToUriMap = Collections.synchronizedMap(new LinkedHashMap<String, String>(10, 1.5f, true));
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(FileCache fileCache) {
//fileCache = new FileCache(context);
this.fileCache = fileCache;
executorService = Executors.newFixedThreadPool(5);
// need to re-evaluate where to do this as it is causing problems with not being able to download feed items as they are cleared from cache
//clearCache();
// only clear file cache, we're not using mem cache (every time we instantiate with a filecache)
fileCache.clear();
}
public void DisplayImage(String url, ImageView imageView, ProgressBar progress) {
imageViews.put(imageView, url);
Bitmap bitmap = memoryCache.get(url);
if (bitmap != null) {
imageView.setImageBitmap(bitmap);
}
else {
queuePhoto(url, imageView, progress);
//imageView.setImageResource(stub_id);
imageView.setVisibility(View.GONE);
if(progress != null) {
progress.setVisibility(View.VISIBLE);
}
}
}
private void queuePhoto(String url, ImageView imageView, ProgressBar progress) {
PhotoToLoad p = new PhotoToLoad(url, imageView, progress);
executorService.submit(new PhotosLoader(p));
}
// must be run in a thread
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);
FeedUtils.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;
}
}
public Uri getImageURIWithDownload(String url) {
// try getting file from cache 1st
File f = fileCache.getFile(url);
if (f != null) {
if(f.exists()) {
return Uri.fromFile(f);
}
}
// get bitmap from http (or cache, in fact)
getBitmap(url);
// try getting file again
f = fileCache.getFile(url);
return (f != null) ? Uri.fromFile(f) : null;
}
// Decodes image and scales it to reduce memory consumption
// note. wda. doesn't use sample size (no scaling!)
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();
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 ProgressBar progress;
public PhotoToLoad(String u, ImageView i, ProgressBar p) {
url = u;
imageView = i;
progress = p;
}
}
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);
photoToLoad.imageView.setVisibility(View.VISIBLE);
if(photoToLoad.progress != null)
photoToLoad.progress.setVisibility(View.GONE);
}
else {}
//photoToLoad.imageView.setImageResource(stub_id);
}
}
public void clearCache() {
memoryCache.clear();
fileCache.clear();
}
}
What does the "your-URL" refer to?
It refers to the url which you want to access information from.
With AndroidHttpClient over Apache I never had to use a specific URL for anything. It just worked.
No you'll provide url in that case too.
HttpClient httpclient = new DefaultHttpClient();
HttpResponse response = httpclient.execute(new HttpGet(URL));
If you want to use a http request, it should have a request url, without which it doesn't know where to get data from.
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);
}
}*/
}
using below code and able to save in application cache but not in sd card..In sd card the file saved is of 0 bytes not able to get the exact error.....thanks in advance
final FileOutputStream f = new FileOutputStream(directory);
URL u = new URL(fileURL);
final HttpURLConnection c = (HttpURLConnection) u.openConnection();
c.setRequestMethod("GET");
c.setDoOutput(true);
Thread thread = new Thread(new Runnable() {
#SuppressWarnings("deprecation")
#Override
public void run() {
try {
c.connect();
InputStream in = c.getInputStream();
byte[] buffer = new byte[1024];
int len1 = 0;
int flag = 0;
while ((len1 = in.read(buffer)) != -1) {
f.write(buffer, 0, len1);
Log.d("Thread ", String.valueOf(len1));
}
f.close();
thread.start();
} catch (Exception e) {
Toast.makeText(this, "In exception", Toast.LENGTH_LONG).show();
e.printStackTrace();
Toast.makeText(this, e.getMessage(), Toast.LENGTH_LONG).show();
e.printStackTrace();
}
Use the following code to download any kind of file. I have checked this. It works like a charm.
Please check this out.
import java.io.File;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import android.app.ProgressDialog;
import android.content.Context;
import android.os.AsyncTask;
import android.os.Environment;
import android.os.Handler;
import android.util.Log;
public class DownloadMultimedia extends AsyncTask<Void, Void, Void> {
protected static final int SHOW_PROGRESS_DIALOG = 0x5;
protected static final int STOP_PROGRESS_DIALOG = 0x6;
protected static final int NETWORK_FAILURE = 0x7;
protected static final int PROBLEM_IN_CONNECTING_SERVER = 0x8;
protected static final int DOWNLOADED_SUCCESS = 0x12;
protected static final int DOWNLOADED_FAILED = 0X13;
private URL url;
private String PATH;
private String fileName = "";
private Context context;
private String mReceivedURL = "";
public DownloadMultimedia(Context context,
String mReceivedURL) {
// TODO Auto-generated constructor stub
// Here Received URL is your url to download.
this.context = context;
this.mReceivedURL = mReceivedURL;
fileName = mReceivedURL.substring(mReceivedURL.lastIndexOf("/") + 1,
mReceivedURL.length());
}
#Override
protected Void doInBackground(Void... params) {
// TODO Auto-generated method stub
downloadPhoto(mReceivedURL);
return null;
}
#Override
protected void onPreExecute() {
// TODO Auto-generated method stub
super.onPreExecute();
mHandler.sendEmptyMessage(SHOW_PROGRESS_DIALOG);
}
#Override
protected void onPostExecute(Void result) {
// TODO Auto-generated method stub
super.onPostExecute(result);
mHandler.sendEmptyMessage(STOP_PROGRESS_DIALOG);
}
public void downloadPhoto(String Video_URL) {
try {
url = new URL(Video_URL);
HttpURLConnection c = (HttpURLConnection) url.openConnection();
c.setRequestMethod("GET");
c.setDoOutput(true);
c.connect();
PATH = Environment.getExternalStorageDirectory()
+ "/Media/Videos/";
Log.d("", "the path to store : " + PATH);
File file = new File(PATH);
file.mkdirs();
File outputFile = new File(file, fileName);
FileOutputStream fos = new FileOutputStream(outputFile);
InputStream is = c.getInputStream();
byte[] buffer = new byte[1024];
int len1 = 0;
while ((len1 = is.read(buffer)) != -1) {
fos.write(buffer, 0, len1);
}
fos.close();
is.close();
mHandler.sendEmptyMessage(DOWNLOADED_SUCCESS);
} catch (Exception e) {
mHandler.sendEmptyMessage(DOWNLOADED_FAILED);
Log.d("TAG", " downloadVideo exception " + e.getMessage());
}
}
Handler mHandler = new Handler() {
private ProgressDialog progressDialog;
public void handleMessage(android.os.Message msg) {
switch (msg.what) {
case SHOW_PROGRESS_DIALOG:
if (progressDialog == null) {
progressDialog = Utils.createProgressDialog(context);
progressDialog.show();
} else {
progressDialog.show();
}
mHandler.removeMessages(SHOW_PROGRESS_DIALOG);
break;
case STOP_PROGRESS_DIALOG:
progressDialog.dismiss();
mHandler.removeMessages(STOP_PROGRESS_DIALOG);
break;
case NETWORK_FAILURE:
Utils.displayToast(context, Constant.NO_NETWORK_CONNECTION);
mHandler.removeMessages(NETWORK_FAILURE);
break;
case PROBLEM_IN_CONNECTING_SERVER:
Utils.displayToast(context,
Constant.PROBLEM_IN_CONNECTING_SERVER);
mHandler.removeMessages(PROBLEM_IN_CONNECTING_SERVER);
break;
case DOWNLOADED_SUCCESS:
Utils.displayToast(context, "File has been downloaded");
mHandler.removeMessages(DOWNLOADED_SUCCESS);
break;
case DOWNLOADED_FAILED:
Utils.displayToast(context, "Error, Try again later");
mHandler.sendEmptyMessage(DOWNLOADED_FAILED);
break;
default:
break;
}
};
};
}
Meantime, I will go through your code and check what wrong with that.
I think I'm doing something wrong with my paths but I can't figure out what. I am testing on a Nexus 7 if that's relevant. Following examples I tried to copy the tessdata folder over to the SD card however it keeps telling me unable to copy file not found. I don't quite understand why. (I have the tesseract project as a library and I have the tessdata folder copied into assets).
All help is appreciated thanks!
Code:
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import android.app.Activity;
import android.content.Intent;
import android.content.res.AssetManager;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Matrix;
import android.media.ExifInterface;
import android.os.Bundle;
import android.os.Environment;
import android.provider.MediaStore;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.Toast;
import com.googlecode.tesseract.android.TessBaseAPI;
public class MainActivity extends Activity {
private static ImageView imageView;
// protected static Bitmap bit;
protected static Bitmap mImageBitmap;
// protected static String DATA_PATH;
public static final String STORAGE_PATH = Environment.getExternalStorageDirectory().toString() + "/rjb";
protected static String tesspath = STORAGE_PATH + "/tessdata";
protected static String savepath = null;
protected static String TAG = "OCR";
protected static String lang = "eng";
// main method
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
// This is my image view for to show the image with
imageView = (ImageView) this.findViewById(R.id.imageView1);
// this is the take a photo button
Button photoButton = (Button) this.findViewById(R.id.button1);
//check if the rjb directory is there
//make it if its not
createmydir();
//if (!(new File(STORAGE_PATH + File.separator + "tessdata" + File.separator + lang + ".traineddata")).exists()) {
try {
AssetManager assetManager = this.getAssets();
//open the asset manager and open the traineddata path
InputStream in = assetManager.open("tessdata/eng.traineddata");
OutputStream out = new FileOutputStream(tesspath + "/eng.traineddata");
byte[] buf = new byte[8024];
int len;
while ((len = in.read(buf)) > 0) {
out.write(buf, 0, len);
}
in.close();
out.close();
} catch (IOException e) {
android.util.Log.e(TAG, "Was unable to copy " + lang
+ " traineddata " + e.toString());
android.util.Log.e(TAG, "IM PRINTING THE STACK TRACE");
e.printStackTrace();
}
//} else {
processImage(STORAGE_PATH + File.separator + "savedAndroid.jpg");
//}
photoButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// CALL THE PICTURE (this works)
dispatchTakePictureIntent(0);
}
});
}
private void createmydir() {
File t = new File(STORAGE_PATH);
if(t.exists()) {
Toast.makeText(getApplicationContext(), "IM TOASTIN CAUSE IT EXISTS", Toast.LENGTH_LONG).show();
}
else {
t.mkdirs();
Toast.makeText(getApplicationContext(), "IM TOASTIN CUZ I MADE IT EXIST", Toast.LENGTH_LONG).show();
}
}
private void handleSmallCameraPhoto(Intent intent) {
Bundle extras = intent.getExtras();
mImageBitmap = (Bitmap) extras.get("data");
imageView.setImageBitmap(mImageBitmap);
BitmapFactory.Options options = new BitmapFactory.Options();
options.inSampleSize = 4;
saveImageAndroid(mImageBitmap);
Bitmap bitmap = BitmapFactory.decodeFile(savepath, options);
ExifInterface exif;
try {
exif = new ExifInterface(savepath);
int exifOrientation = exif.getAttributeInt(ExifInterface.TAG_ORIENTATION,ExifInterface.ORIENTATION_NORMAL);
int rotate = 0;
switch (exifOrientation) {
case ExifInterface.ORIENTATION_ROTATE_90:
rotate = 90;
break;
case ExifInterface.ORIENTATION_ROTATE_180:
rotate = 180;
break;
case ExifInterface.ORIENTATION_ROTATE_270:
rotate = 270;
break;
}
if (rotate != 0) {
int w = bitmap.getWidth();
int h = bitmap.getHeight();
// Setting pre rotate
Matrix mtx = new Matrix();
mtx.preRotate(rotate);
// Rotating Bitmap & convert to ARGB_8888, required by tess
bitmap = Bitmap.createBitmap(bitmap, 0, 0, w, h, mtx, false);
bitmap = bitmap.copy(Bitmap.Config.ARGB_8888, true);
}
// DATA_PATH = getDataPath();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
handleSmallCameraPhoto(data);
}
// write bitmap to storage
// saves it as savedandroid.jpg
// saves location in savepath
private void saveImageAndroid(final Bitmap passedBitmap) {
try {
savepath = STORAGE_PATH + File.separator + "savedAndroid.jpg";
FileOutputStream mFileOutStream = new FileOutputStream(savepath);
passedBitmap.compress(Bitmap.CompressFormat.JPEG, 100,mFileOutStream);
mFileOutStream.flush();
mFileOutStream.close();
} catch (Exception e) {
e.printStackTrace();
}
}
private void dispatchTakePictureIntent(int actionCode) {
Intent takePictureIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
startActivityForResult(takePictureIntent, actionCode);
}
private void processImage(final String filePath) {
BitmapFactory.Options options = new BitmapFactory.Options();
options.inSampleSize = 2;
options.inPurgeable = true;
Bitmap bitmap = BitmapFactory.decodeFile(filePath, options);
if (bitmap != null) {
/*
* was for rotating but no longer needed int width =
* bitmap.getWidth(); int height = bitmap.getHeight(); Matrix matrix
* = new Matrix(); matrix.postRotate(rotation); bitmap =
* Bitmap.createBitmap(bitmap, 0, 0, width, height, matrix, false);
* bitmap = bitmap.copy(Bitmap.Config.ARGB_8888, true);
*/
TessBaseAPI baseApi = new TessBaseAPI();
baseApi.setDebug(true);
baseApi.init(STORAGE_PATH, "eng");
baseApi.setPageSegMode(100);
baseApi.setPageSegMode(7);
baseApi.setImage(bitmap);
String recognizedText = baseApi.getUTF8Text();
android.util.Log.i(TAG, "recognizedText: 1 " + recognizedText);
baseApi.end();
if (lang.equalsIgnoreCase("eng")) {
recognizedText = recognizedText
.replaceAll("[^a-zA-Z0-9]+", " ");
}
android.util.Log.i(TAG,
"recognizedText: 2 " + recognizedText.trim());
}
}
}
First try to place the files on sd card and just try simple ocr on an simple image like ear, if that works then go for copying the language files through program, because of that you may come to know where the error is.
I want to store the HashMap object in a file on SD card. So, that the same object is used again on application restart. I have no idea how to do this, please provide me a brief summary.
For example, I want the LazyList of images that is saved in HashMap to be stored in a file on SD card. So, that images are downloaded once and never need to be downloaded again.
I am including the LazyList code where I need to implement such scenario:
package com.gogozing.util;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
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.graphics.drawable.BitmapDrawable;
import android.os.Environment;
import android.widget.ImageView;
import com.abc.app.R;
public class ImageLoader {
// 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) {
// Make the background thead low priority. This way it will not affect
// the UI performance
photoLoaderThread.setPriority(Thread.NORM_PRIORITY - 1);
//String path = Environment.getExternalStorageDirectory().toString();
//OutputStream fOut = null;
//File cacheDir = new File(path, "LazyList");
// try {
// fOut = new FileOutputStream(cacheDir);
// } catch (FileNotFoundException e) {
// // TODO Auto-generated catch block
// e.printStackTrace();
// }
// 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(),
"LazyList");
else
cacheDir = context.getCacheDir();
if (!cacheDir.exists())
cacheDir.mkdirs();
}
final int stub_id = R.drawable.no_image;
public void DisplayImage(String url, Activity activity, ImageView imageView) {
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 {
return new BitmapDrawable(new URL(url).openStream()).getBitmap();
} catch (Exception ex) {
ex.printStackTrace();
cache.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;
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++;
}
// decode with inSampleSize
BitmapFactory.Options o2 = new BitmapFactory.Options();
o2.inSampleSize = scale;
return BitmapFactory.decodeStream(new FileInputStream(f), null, o2);
} catch (FileNotFoundException e) {
}
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);
if (photoToLoad.url == null) {
} else {
if (((String) photoToLoad.imageView.getTag())
.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) {
// allow thread to exit
}
}
}
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() {
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();
}
}
All objects in the HashMap must be Serializable, then you should be able to just serialize the map with something like
try {
ObjectOutputStream out = new ObjectOutputStream(...);
out.writeObject(yourMap);
out.close();
} catch(IOException ex) {
...
}
However you have bitmaps in your map, and bitmaps makes little sense to serialize like that. You should rather just save your jpg/png/etc files to the phone memory or sd-card, and read them from there on the next application start.