Android OCR App using Tesseract - android

I was following the tutorial mentioned at this this site:
http://gaut.am/making-an-ocr-android-app-using-tesseract/
First I imported Tess-Two from github:
https://github.com/rmtheis/tess-two
And linked it to my project
https://github.com/GautamGupta/Simple-Android-OCR
The app compiles and runs fine. But after clicking an image when I hit save it crashes.
Here is the source main activity:
public class SimpleAndroidOCRActivity extends Activity {
public static final String PACKAGE_NAME = "com.datumdroid.android.ocr.simple";
public static final String DATA_PATH = Environment
.getExternalStorageDirectory().toString() + "/SimpleAndroidOCR/";
// You should have the trained data file in assets folder
// You can get them at:
// http://code.google.com/p/tesseract-ocr/downloads/list
public static final String lang = "eng";
private static final String TAG = "SimpleAndroidOCR.java";
protected Button _button;
// protected ImageView _image;
protected EditText _field;
protected String _path;
protected boolean _taken;
protected static final String PHOTO_TAKEN = "photo_taken";
#Override
public void onCreate(Bundle savedInstanceState) {
String[] paths = new String[] { DATA_PATH, DATA_PATH + "tessdata/" };
for (String path : paths) {
File dir = new File(path);
if (!dir.exists()) {
if (!dir.mkdirs()) {
Log.v(TAG, "ERROR: Creation of directory " + path + " on sdcard failed");
return;
} else {
Log.v(TAG, "Created directory " + path + " on sdcard");
}
}
}
// lang.traineddata file with the app (in assets folder)
// You can get them at:
// http://code.google.com/p/tesseract-ocr/downloads/list
// This area needs work and optimization
if (!(new File(DATA_PATH + "tessdata/" + lang + ".traineddata")).exists()) {
try {
AssetManager assetManager = getAssets();
InputStream in = assetManager.open("tessdata/" + lang + ".traineddata");
//GZIPInputStream gin = new GZIPInputStream(in);
OutputStream out = new FileOutputStream(DATA_PATH
+ "tessdata/" + lang + ".traineddata");
// Transfer bytes from in to out
byte[] buf = new byte[1024];
int len;
//while ((lenf = gin.read(buff)) > 0) {
while ((len = in.read(buf)) > 0) {
out.write(buf, 0, len);
}
in.close();
//gin.close();
out.close();
Log.v(TAG, "Copied " + lang + " traineddata");
} catch (IOException e) {
Log.e(TAG, "Was unable to copy " + lang + " traineddata " + e.toString());
}
}
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
// _image = (ImageView) findViewById(R.id.image);
_field = (EditText) findViewById(R.id.field);
_button = (Button) findViewById(R.id.button);
_button.setOnClickListener(new ButtonClickHandler());
_path = DATA_PATH + "/ocr.jpg";
}
public class ButtonClickHandler implements View.OnClickListener {
public void onClick(View view) {
Log.v(TAG, "Starting Camera app");
startCameraActivity();
}
}
// Simple android photo capture:
// http://labs.makemachine.net/2010/03/simple-android-photo-capture/
protected void startCameraActivity() {
File file = new File(_path);
Uri outputFileUri = Uri.fromFile(file);
final Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
intent.putExtra(MediaStore.EXTRA_OUTPUT, outputFileUri);
startActivityForResult(intent, 0);
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
Log.i(TAG, "resultCode: " + resultCode);
if (resultCode == -1) {
onPhotoTaken();
} else {
Log.v(TAG, "User cancelled");
}
}
#Override
protected void onSaveInstanceState(Bundle outState) {
outState.putBoolean(SimpleAndroidOCRActivity.PHOTO_TAKEN, _taken);
}
#Override
protected void onRestoreInstanceState(Bundle savedInstanceState) {
Log.i(TAG, "onRestoreInstanceState()");
if (savedInstanceState.getBoolean(SimpleAndroidOCRActivity.PHOTO_TAKEN)) {
onPhotoTaken();
}
}
protected void onPhotoTaken() {
_taken = true;
BitmapFactory.Options options = new BitmapFactory.Options();
options.inSampleSize = 4;
Bitmap bitmap = BitmapFactory.decodeFile(_path, options);
try {
ExifInterface exif = new ExifInterface(_path);
int exifOrientation = exif.getAttributeInt(
ExifInterface.TAG_ORIENTATION,
ExifInterface.ORIENTATION_NORMAL);
Log.v(TAG, "Orient: " + exifOrientation);
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;
}
Log.v(TAG, "Rotation: " + rotate);
if (rotate != 0) {
// Getting width & height of the given image.
int w = bitmap.getWidth();
int h = bitmap.getHeight();
// Setting pre rotate
Matrix mtx = new Matrix();
mtx.preRotate(rotate);
// Rotating Bitmap
bitmap = Bitmap.createBitmap(bitmap, 0, 0, w, h, mtx, false);
}
// Convert to ARGB_8888, required by tess
bitmap = bitmap.copy(Bitmap.Config.ARGB_8888, true);
} catch (IOException e) {
Log.e(TAG, "Couldn't correct orientation: " + e.toString());
}
// _image.setImageBitmap( bitmap );
Log.v(TAG, "Before baseApi");
TessBaseAPI baseApi = new TessBaseAPI();
baseApi.setDebug(true);
baseApi.init(DATA_PATH, lang);
baseApi.setImage(bitmap);
String recognizedText = baseApi.getUTF8Text();
baseApi.end();
// You now have the text in recognizedText var, you can do anything with it.
// We will display a stripped out trimmed alpha-numeric version of it (if lang is eng)
// so that garbage doesn't make it to the display.
Log.v(TAG, "OCRED TEXT: " + recognizedText);
if ( lang.equalsIgnoreCase("eng") ) {
recognizedText = recognizedText.replaceAll("[^a-zA-Z0-9]+", " ");
}
recognizedText = recognizedText.trim();
if ( recognizedText.length() != 0 ) {
_field.setText(_field.getText().toString().length() == 0 ? recognizedText : _field.getText() + " " + recognizedText);
_field.setSelection(_field.getText().toString().length());
}
// Cycle done.
}
// www.Gaut.am was here
// Thanks for reading!
}
And I know the error is towards the end in the following part:
TessBaseAPI baseApi = new TessBaseAPI();
baseApi.setDebug(true);
baseApi.init(DATA_PATH, lang);
baseApi.setImage(bitmap);
String recognizedText = baseApi.getUTF8Text();
baseApi.end();
Any idea why it might be crashing?

Go to unzip your target *.apk file,check if there is a libs folder of which contains the *.so files.If this is your problem,check this link I have answered before.

Are you using correct tessdata files ? if not go for this.
https://github.com/tesseract-ocr/tesseract/wiki/Data-Files#data-files-for-version-304305
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />
Here may be permission issue while saving files to directory.
Or check lib folder of code directory it can be issue of libtess.so file not available for CPU architecture like x86,x64,mips,armv7.

The issue is with your path, you have to download a language in which you want to get a result from code.google.com/p/tesseract-ocr/downloads/list download (eg: tesseract-ocr-3.02.eng.tar.gz ) extract it and locate the file “yourLanguage.traineddata” (eg: “eng.traineddata”) and put this file in your storage path in sd card, then you can get it as a path
TessBaseAPI mTess = new TessBaseAPI();
String datapath = Environment.getExternalStorageDirectory() + "/tesseract/";
String language = "eng";
File dir = new File(datapath + "tessdata/");
if (!dir.exists())
dir.mkdirs();
mTess.init(datapath, language);
mTess.setImage(yourBitmapImage);
String result = mTess.getUTF8Text();
Toast.makeText(tesswork.this, "Result : " + result, Toast.LENGTH_LONG).show();

Related

Tressact Arabic OCR app gets stuck

I've followed these links: http://gaut.am/making-an-ocr-android-app-using-tesseract/#comment-184181
http://gaut.am/making-an-ocr-android-app-using-tesseract/
to make an OCR app on android studio. The app works perfectly fine when i include eng.traineddata in the src->main->assets folder
However, when i used ara.traineddata to make an OCR app for arabic, the app gets stuck
I used the debug point to check where the problem might be and it seems that the problem is at
baseApi.init(DATA_PATH, lang);
in MainActivity.java
Here is my MainActivity.java
package com.innam.tryingtomaketesseractwork;
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.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.provider.MediaStore;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import com.googlecode.tesseract.android.TessBaseAPI;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
public class MainActivity extends Activity {
public static final String PACKAGE_NAME = "com.datumdroid.android.ocr.simple";
public static final String DATA_PATH = Environment
.getExternalStorageDirectory().toString() + "/SimpleAndroidOCR/";
// You should have the trained data file in assets folder
// You can get them at:
// http://code.google.com/p/tesseract-ocr/downloads/list
public static final String lang = "ara";
private static final String TAG = "SimpleAndroidOCR.java";
protected Button _button;
// protected ImageView _image;
protected EditText _field;
protected String _path;
protected boolean _taken;
protected static final String PHOTO_TAKEN = "photo_taken";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
String[] paths = new String[] { DATA_PATH, DATA_PATH + "tessdata/" };
for (String path : paths) {
File dir = new File(path);
if (!dir.exists()) {
if (!dir.mkdirs()) {
Log.v(TAG, "ERROR: Creation of directory " + path + " on sdcard failed");
return;
} else {
Log.v(TAG, "Created directory " + path + " on sdcard");
}
}
}
// lang.traineddata file with the app (in assets folder)
// You can get them at:
// http://code.google.com/p/tesseract-ocr/downloads/list
// This area needs work and optimization
if (!(new File(DATA_PATH + "tessdata/" + lang + ".traineddata")).exists()) {
try {
AssetManager assetManager = getAssets();
InputStream in = assetManager.open("tessdata/" + lang + ".traineddata");
//GZIPInputStream gin = new GZIPInputStream(in);
OutputStream out = new FileOutputStream(DATA_PATH
+ "tessdata/" + lang + ".traineddata");
// Transfer bytes from in to out
byte[] buf = new byte[1024];
int len;
//while ((lenf = gin.read(buff)) > 0) {
while ((len = in.read(buf)) > 0) {
out.write(buf, 0, len);
}
in.close();
//gin.close();
out.close();
Log.v(TAG, "Copied " + lang + " traineddata");
} catch (IOException e) {
Log.e(TAG, "Was unable to copy " + lang + " traineddata " + e.toString());
}
}
// _image = (ImageView) findViewById(R.id.image);
_field = (EditText) findViewById(R.id.field);
_button = (Button) findViewById(R.id.button);
_button.setOnClickListener(new ButtonClickHandler());
_path = DATA_PATH + "/ocr.jpg";
}
public class ButtonClickHandler implements View.OnClickListener {
public void onClick(View view) {
Log.v(TAG, "Starting Camera app");
startCameraActivity();
}
}
// Simple android photo capture:
// http://labs.makemachine.net/2010/03/simple-android-photo-capture/
protected void startCameraActivity() {
File file = new File(_path);
Uri outputFileUri = Uri.fromFile(file);
final Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
intent.putExtra(MediaStore.EXTRA_OUTPUT, outputFileUri);
startActivityForResult(intent, 0);
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
Log.i(TAG, "resultCode: " + resultCode);
if (resultCode == -1) {
onPhotoTaken();
} else {
Log.v(TAG, "User cancelled");
}
}
#Override
protected void onSaveInstanceState(Bundle outState) {
outState.putBoolean(MainActivity.PHOTO_TAKEN, _taken);
}
#Override
protected void onRestoreInstanceState(Bundle savedInstanceState) {
Log.i(TAG, "onRestoreInstanceState()");
if (savedInstanceState.getBoolean(MainActivity.PHOTO_TAKEN)) {
onPhotoTaken();
}
}
protected void onPhotoTaken() {
_taken = true;
BitmapFactory.Options options = new BitmapFactory.Options();
options.inSampleSize = 4;
Bitmap bitmap = BitmapFactory.decodeFile(_path, options);
try {
ExifInterface exif = new ExifInterface(_path);
int exifOrientation = exif.getAttributeInt(
ExifInterface.TAG_ORIENTATION,
ExifInterface.ORIENTATION_NORMAL);
Log.v(TAG, "Orient: " + exifOrientation);
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;
}
Log.v(TAG, "Rotation: " + rotate);
if (rotate != 0) {
// Getting width & height of the given image.
int w = bitmap.getWidth();
int h = bitmap.getHeight();
// Setting pre rotate
Matrix mtx = new Matrix();
mtx.preRotate(rotate);
// Rotating Bitmap
bitmap = Bitmap.createBitmap(bitmap, 0, 0, w, h, mtx, false);
}
// Convert to ARGB_8888, required by tess
bitmap = bitmap.copy(Bitmap.Config.ARGB_8888, true);
} catch (IOException e) {
Log.e(TAG, "Couldn't correct orientation: " + e.toString());
}
// _image.setImageBitmap( bitmap );
Log.v(TAG, "Before baseApi");
TessBaseAPI baseApi = new TessBaseAPI();
baseApi.setDebug(true);
baseApi.init(DATA_PATH, lang);
baseApi.setImage(bitmap);
String recognizedText = baseApi.getUTF8Text();
baseApi.end();
// You now have the text in recognizedText var, you can do anything with it.
// We will display a stripped out trimmed alpha-numeric version of it (if lang is eng)
// so that garbage doesn't make it to the display.
Log.v(TAG, "OCRED TEXT: " + recognizedText);
if ( lang.equalsIgnoreCase("eng") ) {
recognizedText = recognizedText.replaceAll("[^a-zA-Z0-9]+", " ");
}
recognizedText = recognizedText.trim();
if ( recognizedText.length() != 0 ) {
_field.setText(_field.getText().toString().length() == 0 ? recognizedText : _field.getText() + " " + recognizedText);
_field.setSelection(_field.getText().toString().length());
}
// Cycle done.
}
// www.Gaut.am was here
// Thanks for reading!
}
logcat:
08-04 12:58:38.900 24836-24836/com.innam.tryingtomaketesseractwork D/libEGL: loaded /system/lib/egl/libEGL_mali.so
08-04 12:58:38.905 24836-24836/com.innam.tryingtomaketesseractwork D/libEGL: loaded /system/lib/egl/libGLESv1_CM_mali.so
08-04 12:58:38.905 24836-24836/com.innam.tryingtomaketesseractwork D/libEGL: loaded /system/lib/egl/libGLESv2_mali.so
[ 08-04 12:58:38.910 24836:24836 D/ ]
Device driver API match
Device driver API version: 10
User space API version: 10
[ 08-04 12:58:38.910 24836:24836 D/ ]
mali: REVISION=Linux-r2p4-02rel0 BUILD_DATE=Tue Oct 16 15:37:13 KST 2012
08-04 12:58:38.960 24836-24836/com.innam.tryingtomaketesseractwork D/OpenGLRenderer: Enabling debug mode 0
08-04 12:58:38.965 24836-24836/com.innam.tryingtomaketesseractwork E/SensorManager: thread start
08-04 12:58:38.965 24836-24836/com.innam.tryingtomaketesseractwork D/SensorManager: registerListener :: handle = 1 name= LIS3DH Acceleration Sensor delay= 200000
Any help will be highly appreciated
You'd need all the ara.cube.* files also.
https://github.com/tesseract-ocr/tessdata

Tesseract - Help me understand datapath

Can someone explain what exactly is going on and how I can rectify it. So I understand tesseract has to have an image to target and presumably this would be the bitmap I've captured and tried to save. That saved location would be my _path variable. Now what is the DATA_PATH for tesseract? Does the image need to be stored in a folder called 'tesseract' ? Do I create that folder and store some kind of training in it? I'm looking for an explanation rather than a code example.
http://gaut.am/making-an-ocr-android-app-using-tesseract/ - I am trying to follow this tutorial and checking others to try and understand the paths which all of them use.
public class MainActivity extends Activity {
private static ImageView imageView;
protected String _path;
// protected static Bitmap bit;
static File myDir;
protected static Bitmap mImageBitmap;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
this.imageView = (ImageView) this.findViewById(R.id.imageView1);
Button photoButton = (Button) this.findViewById(R.id.button1);
_path = Environment.getExternalStorageDirectory() + "/images/test.bmp";
Toast t = Toast.makeText(getApplicationContext(), "HEELLLLLLOO", 100000);
t.show();
photoButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// CALL THE PICTURE
dispatchTakePictureIntent(0);
}
});
}
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;
Bitmap bitmap = BitmapFactory.decodeFile( _path, options );
imageView.setImageBitmap(bitmap);
//_path = path to the image to be OCRed
ExifInterface exif;
try {
exif = new ExifInterface(_path);
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);
}
TessBaseAPI baseApi = new TessBaseAPI();
// DATA_PATH = Path to the storage
// lang for which the language data exists, usually "eng"
baseApi.init(_path, "eng"); //THIS SHOULD BE DATA_PATH ?
baseApi.setImage(bitmap);
String recognizedText = baseApi.getUTF8Text();
System.out.println(recognizedText);
baseApi.end();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
protected void onActivityResult(int requestCode, int resultCode, Intent data){
handleSmallCameraPhoto(data);
}
private void dispatchTakePictureIntent(int actionCode) {
Intent takePictureIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
startActivityForResult(takePictureIntent, actionCode);
}
protected static void identifyunicode() {
// DATA_PATH = Path to the storage
// lang for which the language data exists, usually "eng"
/*
* TessBaseAPI baseApi = new TessBaseAPI();
* baseApi.init(myDir.toString(), "eng"); // myDir + //
* "/tessdata/eng.traineddata" // must be present baseApi.setImage(bit);
* String recognizedText = baseApi.getUTF8Text(); // Log or otherwise //
* display this // string... baseApi.end();
*/
}
}
DataPath is the path where you copied your tessdata files from Assets.
import java.io.File;
import java.util.ArrayList;
import android.os.Environment;
public class Utils {
public static boolean isSDCardMounted() {
boolean isMounted = false;
String state = Environment.getExternalStorageState();
if (Environment.MEDIA_MOUNTED.equals(state)) {
isMounted = true;
} else if (Environment.MEDIA_BAD_REMOVAL.equals(state)) {
isMounted = false;
} else if (Environment.MEDIA_CHECKING.equals(state)) {
isMounted = false;
} else if (Environment.MEDIA_MOUNTED_READ_ONLY.equals(state)) {
isMounted = false;
} else if (Environment.MEDIA_NOFS.equals(state)) {
isMounted = false;
} else if (Environment.MEDIA_REMOVED.equals(state)) {
isMounted = false;
} else if (Environment.MEDIA_UNMOUNTABLE.equals(state)) {
isMounted = false;
} else if (Environment.MEDIA_UNMOUNTED.equals(state)) {
isMounted = false;
}
return isMounted;
}
public static boolean isDirectoryExists(final String filePath) {
boolean isDirectoryExists = false;
File mFilePath = new File(filePath);
if(mFilePath.exists()) {
isDirectoryExists = true;
} else {
isDirectoryExists = mFilePath.mkdirs();
}
return isDirectoryExists;
}
public static boolean deleteFile(final String filePath) {
boolean isFileExists = false;
File mFilePath = new File(filePath);
if(mFilePath.exists()) {
mFilePath.delete();
isFileExists = true;
}
return isFileExists;
}
public static String getDataPath() {
String returnedPath = "";
final String mDirName = "tesseract";
final String mDataDirName = "tessdata";
if(isSDCardMounted()) {
final String mSDCardPath = Environment.getExternalStorageDirectory() + File.separator + mDirName;
if(isDirectoryExists(mSDCardPath)) {
final String mSDCardDataPath = Environment.getExternalStorageDirectory() + File.separator + mDirName +
File.separator + mDataDirName;
isDirectoryExists(mSDCardDataPath);
return mSDCardPath;
}
}
return returnedPath;
}
}
Activity Class
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.database.Cursor;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Canvas;
import android.graphics.ColorMatrix;
import android.graphics.ColorMatrixColorFilter;
import android.graphics.Matrix;
import android.graphics.Paint;
import android.media.ExifInterface;
import android.net.Uri;
import android.os.Bundle;
import android.provider.MediaStore;
import android.view.View;
import android.widget.TextView;
import com.googlecode.tesseract.android.TessBaseAPI;
public class AndroidCommonTest extends Activity {
private static final String TAG = AndroidCommonTest.class.getSimpleName();
private TextView txtGotTime = null;
private final int START_CODE = 101;
private String mDirPath = null;
private Uri mOutPutUri = null;
private static final String lang = "eng";
private String mPath = null;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
txtGotTime = (TextView) findViewById(R.id.txtGotTime);
mDirPath = Utils.getDataPath();
mPath = mDirPath + File.separator + "test.jpg";
android.util.Log.i(TAG, "mDirPath: " + mDirPath + " mPath: " + mPath);
if (!(new File(mDirPath + File.separator + "tessdata" + File.separator + lang + ".traineddata")).exists()) {
try {
AssetManager assetManager = getAssets();
InputStream in = assetManager.open("tessdata" + File.separator + lang + ".traineddata");
OutputStream out = new FileOutputStream(mDirPath + File.separator
+ "tessdata" + File.separator + lang + ".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());
}
} else {
processImage(mDirPath + File.separator + "six.jpg", 0);
}
}
public void getTime(View view) {
android.util.Log.i(TAG, "mDirPath: " + mDirPath + " mPath: " + mPath);
if(mDirPath != null && mDirPath.length() > 0) {
mOutPutUri = Uri.fromFile(new File(mPath));
Intent intent = new Intent(android.provider.MediaStore.ACTION_IMAGE_CAPTURE);
intent.putExtra(android.provider.MediaStore.EXTRA_OUTPUT, mOutPutUri);
startActivityForResult(intent, START_CODE);
}
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if(requestCode == START_CODE) {
if(resultCode == Activity.RESULT_OK) {
int rotation = -1;
long fileSize = new File(mPath).length();
android.util.Log.i(TAG, "fileSize " + fileSize);
//Suppose Device Supports ExifInterface
ExifInterface exif;
try {
exif = new ExifInterface(mPath);
int exifOrientation = exif.getAttributeInt(
ExifInterface.TAG_ORIENTATION,
ExifInterface.ORIENTATION_NORMAL);
switch (exifOrientation) {
case ExifInterface.ORIENTATION_ROTATE_90 :
rotation = 90;
break;
case ExifInterface.ORIENTATION_ROTATE_180 :
rotation = 180;
break;
case ExifInterface.ORIENTATION_ROTATE_270 :
rotation = 270;
break;
case ExifInterface.ORIENTATION_NORMAL:
case ExifInterface.ORIENTATION_UNDEFINED:
rotation = 0;
break;
}
android.util.Log.i(TAG, "Exif:rotation " + rotation);
if (rotation != -1) {
processImage(mPath, rotation);
} else {
//Device Does Not Support ExifInterface
Cursor mediaCursor = getContentResolver().query(mOutPutUri,
new String[] { MediaStore.Images.ImageColumns.ORIENTATION,
MediaStore.MediaColumns.SIZE },
null, null, null);
if (mediaCursor != null && mediaCursor.getCount() != 0 ) {
while(mediaCursor.moveToNext()){
long size = mediaCursor.getLong(1);
android.util.Log.i(TAG, "Media:size " + size);
if(size == fileSize){
rotation = mediaCursor.getInt(0);
break;
}
}
android.util.Log.i(TAG, "Media:rotation " + rotation);
processImage(mPath, rotation);
} else {
android.util.Log.i(TAG, "Android Problem");
txtGotTime.setText("Android Problem");
}
}
}
catch (IOException exception) {
exception.printStackTrace();
}
} else if(resultCode == Activity.RESULT_CANCELED) {
android.util.Log.i(TAG, "RESULT_CANCELED");
txtGotTime.setText("RESULT_CANCELED");
}
}
}
private void processImage(final String filePath, final int rotation) {
BitmapFactory.Options options = new BitmapFactory.Options();
options.inSampleSize = 2;
options.inPurgeable = true;
Bitmap bitmap = BitmapFactory.decodeFile(filePath, options);
if (bitmap != null) {
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(mDirPath, lang);
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());
txtGotTime.setText(recognizedText.trim());
}
}
private void saveImageAndroid(final Bitmap passedBitmap) {
try {
FileOutputStream mFileOutStream = new FileOutputStream(mDirPath + File.separator + "savedAndroid.jpg");
passedBitmap.compress(Bitmap.CompressFormat.JPEG, 100, mFileOutStream);
mFileOutStream.flush();
mFileOutStream.close();
} catch (Exception e) {
e.printStackTrace();
}
}
}
Put tessdata folder in Assets.
Do not forget to give reference path of Tess Library.
Thanks.

Android version with tesseract-android-tools-library

I have developed one OCR application which works perfectly on Android version 4.0 but not on 2.2 and 2.3 Android version. I don't know what's the problem with this versions. I searched a lot on Google but no reason found.
package com.datumdroid.android.ocr.simple;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.zip.GZIPInputStream;
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.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.provider.MediaStore;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import com.googlecode.tesseract.android.TessBaseAPI;
public class SimpleAndroidOCRActivity extends Activity {
public static final String PACKAGE_NAME = "com.datumdroid.android.ocr.simple";
public static final String DATA_PATH = Environment
.getExternalStorageDirectory().toString() + "/SimpleAndroidOCR/";
// You should have the trained data file in assets folder
// You can get them at:
// http://code.google.com/p/tesseract-ocr/downloads/list
public static final String lang = "eng";
private static final String TAG = "SimpleAndroidOCR.java";
protected Button _button;
// protected ImageView _image;
protected EditText _field;
protected String _path;
protected boolean _taken;
protected static final String PHOTO_TAKEN = "photo_taken";
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
String[] paths = new String[] { DATA_PATH, DATA_PATH + "tessdata/" };
for (String path : paths) {
File dir = new File(path);
if (!dir.exists()) {
if (!dir.mkdirs()) {
Log.v(TAG, "ERROR: Creation of directory " + path + " on
sdcard failed");
return;
} else {
Log.v(TAG, "Created directory " + path + " on sdcard");
}
}
}
// lang.traineddata file with the app (in assets folder)
// You can get them at:
// http://code.google.com/p/tesseract-ocr/downloads/list
// This area needs work and optimization
if (!(new File(DATA_PATH + "tessdata/" + lang + ".traineddata")).exists()) {
try {
AssetManager assetManager = getAssets();
InputStream in = assetManager.open("tessdata/eng.traineddata");
//GZIPInputStream gin = new GZIPInputStream(in);
OutputStream out = new FileOutputStream(DATA_PATH
+ "tessdata/eng.traineddata");
// Transfer bytes from in to out
byte[] buf = new byte[1024];
int len;
//while ((lenf = gin.read(buff)) > 0) {
while ((len = in.read(buf)) > 0) {
out.write(buf, 0, len);
}
in.close();
//gin.close();
out.close();
Log.v(TAG, "Copied " + lang + " traineddata");
} catch (IOException e) {
Log.e(TAG, "Was unable to copy " + lang + " traineddata " +
e.toString());
}
}
// _image = (ImageView) findViewById(R.id.image);
_field = (EditText) findViewById(R.id.field);
_button = (Button) findViewById(R.id.button);
_button.setOnClickListener(new ButtonClickHandler());
_path = DATA_PATH + "/ocr.jpg";
}
public class ButtonClickHandler implements View.OnClickListener {
public void onClick(View view) {
Log.v(TAG, "Starting Camera app");
startCameraActivity();
}
}
// Simple android photo capture:
// http://labs.makemachine.net/2010/03/simple-android-photo-capture/
protected void startCameraActivity() {
File file = new File(_path);
Uri outputFileUri = Uri.fromFile(file);
final Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
intent.putExtra(MediaStore.EXTRA_OUTPUT, outputFileUri);
startActivityForResult(intent, 0);
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
Log.i(TAG, "resultCode: " + resultCode);
if (resultCode == -1) {
onPhotoTaken();
} else {
Log.v(TAG, "User cancelled");
}
}
#Override
protected void onSaveInstanceState(Bundle outState) {
outState.putBoolean(SimpleAndroidOCRActivity.PHOTO_TAKEN, _taken);
}
#Override
protected void onRestoreInstanceState(Bundle savedInstanceState) {
Log.i(TAG, "onRestoreInstanceState()");
if (savedInstanceState.getBoolean(SimpleAndroidOCRActivity.PHOTO_TAKEN)) {
onPhotoTaken();
}
}
protected void onPhotoTaken() {
_taken = true;
BitmapFactory.Options options = new BitmapFactory.Options();
options.inSampleSize = 4;
Bitmap bitmap = BitmapFactory.decodeFile(_path, options);
try {
ExifInterface exif = new ExifInterface(_path);
int exifOrientation = exif.getAttributeInt(
ExifInterface.TAG_ORIENTATION,
ExifInterface.ORIENTATION_NORMAL);
Log.v(TAG, "Orient: " + exifOrientation);
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;
}
Log.v(TAG, "Rotation: " + rotate);
if (rotate != 0) {
// Getting width & height of the given image.
int w = bitmap.getWidth();
int h = bitmap.getHeight();
// Setting pre rotate
Matrix mtx = new Matrix();
mtx.preRotate(rotate);
// Rotating Bitmap
bitmap = Bitmap.createBitmap(bitmap, 0, 0, w, h, mtx, false);
}
// Convert to ARGB_8888, required by tess
bitmap = bitmap.copy(Bitmap.Config.ARGB_8888, true);
} catch (IOException e) {
Log.e(TAG, "Couldn't correct orientation: " + e.toString());
}
// _image.setImageBitmap( bitmap );
Log.v(TAG, "Before baseApi");
TessBaseAPI baseApi = new TessBaseAPI();
baseApi.setDebug(true);
baseApi.init(DATA_PATH, lang);
baseApi.setImage(bitmap);
String recognizedText = baseApi.getUTF8Text();
baseApi.end();
// You now have the text in recognizedText var, you can do anything with it.
// We will display a stripped out trimmed alpha-numeric version of it (if lang is
eng)
// so that garbage doesn't make it to the display.
Log.v(TAG, "OCRED TEXT: " + recognizedText);
if ( lang.equalsIgnoreCase("eng") ) {
recognizedText = recognizedText.replaceAll("[^a-zA-Z0-9]+", " ");
}
recognizedText = recognizedText.trim();
if ( recognizedText.length() != 0 ) {
_field.setText(_field.getText().toString().length() == 0 ? recognizedText :
_field.getText() + " " + recognizedText);
_field.setSelection(_field.getText().toString().length());
}
// Cycle done.
}
// www.Gaut.am was here
// Thanks for reading!
}

Force Close After Run Android Simple OCR Aplication

I've follow this tutorial to learn about ocr in android.
http://gaut.am/making-an-ocr-android-app-using-tesseract/
After successfully run the program on my device, take a photo, it force close. As if it failed to analyze the image.
I already put the trained data on my /asset/testdata/
the trained data is downloaded from :
http://code.google.com/p/tesseract-ocr/downloads/list
My logcat show that I've error on
java.lang.ExceptionInInitializerError
Can you teach me how to fix it?
This is the code:
package com.datumdroid.android.ocr.simple;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.zip.GZIPInputStream;
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.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.provider.MediaStore;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import com.googlecode.tesseract.android.TessBaseAPI;
public class SimpleAndroidOCRActivity extends Activity {
public static final String PACKAGE_NAME = "com.datumdroid.android.ocr.simple";
public static final String DATA_PATH = Environment
.getExternalStorageDirectory().toString() + "/SimpleAndroidOCR/";
// You should have the trained data file in assets folder
// You can get them at:
// http://code.google.com/p/tesseract-ocr/downloads/list
public static final String lang = "eng";
private static final String TAG = "SimpleAndroidOCR.java";
protected Button _button;
// protected ImageView _image;
protected EditText _field;
protected String _path;
protected boolean _taken;
protected static final String PHOTO_TAKEN = "photo_taken";
#Override
public void onCreate(Bundle savedInstanceState) {
String[] paths = new String[] { DATA_PATH, DATA_PATH + "tessdata/" };
for (String path : paths) {
File dir = new File(path);
if (!dir.exists()) {
if (!dir.mkdirs()) {
Log.v(TAG, "ERROR: Creation of directory " + path
+ " on sdcard failed");
return;
} else {
Log.v(TAG, "Created directory " + path + " on sdcard");
}
}
}
// lang.traineddata file with the app (in assets folder)
// You can get them at:
// http://code.google.com/p/tesseract-ocr/downloads/list
// This area needs work and optimization
if (!(new File(DATA_PATH + "tessdata/" + lang + ".traineddata"))
.exists()) {
try {
AssetManager assetManager = getAssets();
InputStream in = assetManager.open("tessdata/eng.traineddata");
// GZIPInputStream gin = new GZIPInputStream(in);
OutputStream out = new FileOutputStream(DATA_PATH
+ "tessdata/eng.traineddata");
// Transfer bytes from in to out
byte[] buf = new byte[1024];
int len;
// while ((lenf = gin.read(buff)) > 0) {
while ((len = in.read(buf)) > 0) {
out.write(buf, 0, len);
}
in.close();
// gin.close();
out.close();
Log.v(TAG, "Copied " + lang + " traineddata");
} catch (IOException e) {
Log.e(TAG,
"Was unable to copy " + lang + " traineddata "
+ e.toString());
}
}
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
// _image = (ImageView) findViewById(R.id.image);
_field = (EditText) findViewById(R.id.field);
_button = (Button) findViewById(R.id.button);
_button.setOnClickListener(new ButtonClickHandler());
_path = DATA_PATH + "/ocr.jpg";
}
public class ButtonClickHandler implements View.OnClickListener {
public void onClick(View view) {
Log.v(TAG, "Starting Camera app");
startCameraActivity();
}
}
// Simple android photo capture:
// http://labs.makemachine.net/2010/03/simple-android-photo-capture/
protected void startCameraActivity() {
File file = new File(_path);
Uri outputFileUri = Uri.fromFile(file);
final Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
intent.putExtra(MediaStore.EXTRA_OUTPUT, outputFileUri);
startActivityForResult(intent, 0);
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
Log.i(TAG, "resultCode: " + resultCode);
if (resultCode == -1) {
onPhotoTaken();
} else {
Log.v(TAG, "User cancelled");
}
}
#Override
protected void onSaveInstanceState(Bundle outState) {
outState.putBoolean(SimpleAndroidOCRActivity.PHOTO_TAKEN, _taken);
}
#Override
protected void onRestoreInstanceState(Bundle savedInstanceState) {
Log.i(TAG, "onRestoreInstanceState()");
if (savedInstanceState.getBoolean(SimpleAndroidOCRActivity.PHOTO_TAKEN)) {
onPhotoTaken();
}
}
protected void onPhotoTaken() {
_taken = true;
BitmapFactory.Options options = new BitmapFactory.Options();
options.inSampleSize = 4;
Bitmap bitmap = BitmapFactory.decodeFile(_path, options);
try {
ExifInterface exif = new ExifInterface(_path);
int exifOrientation = exif.getAttributeInt(
ExifInterface.TAG_ORIENTATION,
ExifInterface.ORIENTATION_NORMAL);
Log.v(TAG, "Orient: " + exifOrientation);
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;
}
Log.v(TAG, "Rotation: " + rotate);
if (rotate != 0) {
// Getting width & height of the given image.
int w = bitmap.getWidth();
int h = bitmap.getHeight();
// Setting pre rotate
Matrix mtx = new Matrix();
mtx.preRotate(rotate);
// Rotating Bitmap
bitmap = Bitmap.createBitmap(bitmap, 0, 0, w, h, mtx, false);
}
// Convert to ARGB_8888, required by tess
bitmap = bitmap.copy(Bitmap.Config.ARGB_8888, true);
System.out.println("Bitmap Selesai");
} catch (IOException e) {
Log.e(TAG, "Couldn't correct orientation: " + e.toString());
}
// _image.setImageBitmap( bitmap );
//System.loadLibrary("tess");
System.out.println("Masuk");
Log.v(TAG, "Before baseApi");
TessBaseAPI baseApi = new TessBaseAPI();
baseApi.setDebug(true);
baseApi.init(DATA_PATH, lang);
baseApi.setImage(bitmap);
String recognizedText = baseApi.getUTF8Text();
baseApi.end();
System.out.println("Keluar");
// You now have the text in recognizedText var, you can do anything with
// it.
// We will display a stripped out trimmed alpha-numeric version of it
// (if lang is eng)
// so that garbage doesn't make it to the display.
Log.v(TAG, "OCRED TEXT: " + recognizedText);
if (lang.equalsIgnoreCase("eng")) {
recognizedText = recognizedText.replaceAll("[^a-zA-Z0-9]+", " ");
}
recognizedText = recognizedText.trim();
if (recognizedText.length() != 0) {
_field.setText(_field.getText().toString().length() == 0 ? recognizedText
: _field.getText() + " " + recognizedText);
_field.setSelection(_field.getText().toString().length());
}
// Cycle done.
}
// www.Gaut.am was here
// Thanks for reading!
}
Do you have this in your AndroidManifest.xml?:
<uses-permission android:name="WRITE_EXTERNAL_STORAGE" />
I notice that you're trying to create files/directories during initialization, maybe this will help
Can you try to add System.loadLibrary("tess"); before initializing tesseract-ocr?

android download image and then read it from sd-card using sqlite

my question is that i have a code that is suppose to receive a variable that contains a website that has an image so this variable changes every time i send a new link this code should go online and download the image and save it to the sd-card then i read it and display it
so my problem with the code is if im sending 2 links to it, it downloads 1 of the images and it always stores it with the second image name (example: im sending image1 and image2 the code downloads image1 two times and stores it as "image2") when i mount the sd-card and check the image directory there is only 1 image there named image2, i thought that doInBackground was causing the problem but im also using onPostExecute() so please if someone can help me i would be thankful for his help Note this is how i call it:
Note: i have no errors in the code // no red marks
This is all the code:
private void UpdateAds(String Bookinfo,TextView myText){
elhgsdatabase db = new elhgsdatabase(this);
if (Bookinfo != "didn't read titels"){
String debContent="";
String output ="";
int NUMBEROFFIELDS = 5;
String s = addressString;
long idx;
String [] buffer = new String[NUMBEROFFIELDS];
output = "";
int l = 0;
while (s.indexOf("[")>-1){
int fk = s.indexOf("[");
int fl = s.indexOf("]");
if(fk > -1){
buffer[l] = s.substring(fk+1, fl);
s = s.substring(fl+1);
l++;
if (l == NUMBEROFFIELDS){
//1. Query the database to check if the book exists
//---get all titles---
db.open();
Cursor c = db.getBookTitle (buffer[0]);
if (c.getCount()==1)
{ myText.setText("This Books Exist \n"); }
else if(c.getCount()==0)
{ String locLink;
locLink = getLocalLink(buffer[3], buffer[0]);
c.moveToFirst();
if (!locLink.equalsIgnoreCase("-1")){
idx= db.insertTitle(buffer[0], buffer[1], buffer[2], getDate(buffer[3]), buffer[4], locLink);
}
else { //there was a problem with retrieval-saving of the Book info locally
myText.setText("There was a problem with retrieval-saving of the Book info locally\n");
}
}//if(c.getCount()==0)
else{//The table has two Books with the same Name. Do something
myText.setText("The table has two Books with the same Name\n");
}
c.close();
l = 0;
}//if(l == NUMBEROFFIELDS)
} //if (fk>-1)
}//while
db.close();
} //of if(BookInfo...
else {
myText.setText("Nothing is Done\n");
}
}
//This method gets the local link field of the active book records
// it goes on the web, gets the content and stores it in a place
// and saves the path of that place in the database for that
//it returns -1 if something wrong happened during the process
public String getLocalLink(String image_URL, String BookName){
/** This is what we do with this method:
* Go online, according to the link, get the content, call the method to save, get the local link
* and return it
*/
setContentView(R.layout.main);
reviewImageLink = image_URL;
URL reviewImageURL;
String name = reviewImageLink.substring(reviewImageLink.lastIndexOf("/") + 1);
try {
reviewImageURL = new URL(reviewImageLink);
if (!hasExternalStoragePublicPicture(name)) {
isImage = false;
new DownloadImageTask().execute(reviewImageURL);
Log.v("log_tag", "if");
isImage = true;
File sdImageMainDirectory = new File(Environment.getExternalStorageDirectory(), getResources()
.getString(R.string.directory));
sdImageMainDirectory.mkdirs();
File file = new File(sdImageMainDirectory, name);
Log.v("log_tag", "Directory created");
}
} catch (MalformedURLException e) {
Log.v(TAG, e.toString());
}
return ("/sdcard/Hanud/"+BookName+".jpg");
}
private class DownloadImageTask extends AsyncTask<URL, Integer, Bitmap> {
// This class definition states that DownloadImageTask will take String
// parameters, publish Integer progress updates, and return a Bitmap
protected Bitmap doInBackground(URL... paths) {
URL url;
try {
url = paths[0];
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
int length = connection.getContentLength();
InputStream is = (InputStream) url.getContent();
byte[] imageData = new byte[length];
int buffersize = (int) Math.ceil(length / (double) 100);
int downloaded = 0;
int read;
while (downloaded < length) {
if (length < buffersize) {
read = is.read(imageData, downloaded, length);}
else if ((length - downloaded) <= buffersize) {
read = is.read(imageData, downloaded, length- downloaded);
}
else {read = is.read(imageData, downloaded, buffersize);}
downloaded += read;
publishProgress((downloaded * 100) / length);
}
Bitmap bitmap = BitmapFactory.decodeByteArray(imageData, 0,
length);
if (bitmap != null) {
Log.i(TAG, "Bitmap created");
} else {
Log.i(TAG, "Bitmap not created");
}
is.close();
return bitmap;
} catch (MalformedURLException e) {
Log.e(TAG, "Malformed exception: " + e.toString());
} catch (IOException e) {
Log.e(TAG, "IOException: " + e.toString());
} catch (Exception e) {
Log.e(TAG, "Exception: " + e.toString());
}
return null;
}
protected void onPostExecute(Bitmap result) {
String name = reviewImageLink.substring(reviewImageLink
.lastIndexOf("/") + 1);
if (result != null) {
hasExternalStoragePublicPicture(name);
saveToSDCard(result, name);
isImage = true;
} else {
isImage = false;
}
}
}
public void saveToSDCard(Bitmap bitmap, String name) {
boolean mExternalStorageAvailable = false;
boolean mExternalStorageWriteable = false;
String state = Environment.getExternalStorageState();
if (Environment.MEDIA_MOUNTED.equals(state)) {
mExternalStorageAvailable = mExternalStorageWriteable = true;
Log.v(TAG, "SD Card is available for read and write "
+ mExternalStorageAvailable + mExternalStorageWriteable);
saveFile(bitmap, name);
} else if (Environment.MEDIA_MOUNTED_READ_ONLY.equals(state)) {
mExternalStorageAvailable = true;
mExternalStorageWriteable = false;
Log.v(TAG, "SD Card is available for read "
+ mExternalStorageAvailable);
} else {
mExternalStorageAvailable = mExternalStorageWriteable = false;
Log.v(TAG, "Please insert a SD Card to save your Video "
+ mExternalStorageAvailable + mExternalStorageWriteable);
}
}
private void saveFile(Bitmap bitmap, String name) {
String filename = name;
ContentValues values = new ContentValues();
File sdImageMainDirectory = new File(Environment
.getExternalStorageDirectory(), getResources().getString(
R.string.directory));
sdImageMainDirectory.mkdirs();
File outputFile = new File(sdImageMainDirectory, filename);
values.put(MediaStore.MediaColumns.DATA, outputFile.toString());
values.put(MediaStore.MediaColumns.TITLE, filename);
values.put(MediaStore.MediaColumns.DATE_ADDED, System
.currentTimeMillis());
values.put(MediaStore.MediaColumns.MIME_TYPE, "image/png");
Uri uri = this.getContentResolver().insert(
android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI,
values);
try {
OutputStream outStream = this.getContentResolver()
.openOutputStream(uri);
bitmap.compress(Bitmap.CompressFormat.PNG, 95, outStream);
outStream.flush();
outStream.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
private boolean hasExternalStoragePublicPicture(String name) {
File sdImageMainDirectory = new File(Environment
.getExternalStorageDirectory(), getResources().getString(
R.string.directory));
File file = new File(sdImageMainDirectory, name);
if (file != null) {
file.delete();
}
return file.exists();
}
public void showAllBooks( )
{
final elhgsdatabase db = new elhgsdatabase(this);
Handler handler = new Handler();
handler.postDelayed(new Runnable() {
public void run() {
// Get new entry
db.open();
long currTime = System.currentTimeMillis();
String p_query = "select * from ads where timeFrom<=?";
Cursor c = db.rawQuery(p_query, new String[] { Long.toString(currTime)});
if (c.moveToFirst())
{
do {
DisplayTitle(c);
} while (c.moveToNext());
}
db.close();
}
}, 5000); // 5000 miliseconds
}
public long getDate(String s){
String[] formats = new String[] {
"yyyy-MM-dd HH:mm:ss"
};
SimpleDateFormat sdf=null;
String st;
for (String format : formats) {
sdf = new SimpleDateFormat(format, Locale.US);
sdf.setTimeZone(TimeZone.getTimeZone("EST"));//UTC or EST
st = new String(sdf.format(new Date(0)));
System.err.format(format, st);
}
Calendar c = Calendar.getInstance();
Date dt;
try {
dt = sdf.parse(s);
c.setTime(dt);
} catch (ParseException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return c.getTimeInMillis() ;
}
public void DisplayTitle(final Cursor c)
{
Toast.makeText(this,
"Title: " + c.getString(0) + "\n" +
"isbn: " + c.getString(1) + "\n" +
"Publisher: " + c.getString(2) + "\n" +
"Year: " + c.getString(3) + "\n" +
"Image On Line: " + c.getString(4) + "\n" +
"Image On SD " + c.getString(5) + "\n" ,
Toast.LENGTH_LONG).show();
String imageInSD = c.getString(5);
Bitmap bitmap = BitmapFactory.decodeFile(imageInSD);
myImageView=(ImageView)findViewById(R.id.imageview1);
myImageView.setImageBitmap(bitmap);
}
----------
I'm pretty sure you're setting the second image name to the reviewImageLink (not sure if this is a class variable or what) variable. Instead, try passing both the URL and the String to the AsyncTask. Instead of passing a URL... pass in an Object... where the first one is the URL and the second is the name, and use that in the onPostExecute.
You don't show how ImageLink is set up. But as the filename is constructed from it, I guess your problem has almost nothing to do with the code you showed here.

Categories

Resources