Android Error while Uploading an image to server - java

I'am using the following code from the tutorial :
http://geekonjava.blogspot.in/2014/03/upload-image-on-server-in-android-using.html
Whenever I run the code , it shows the following error on log cat and force closes the app on click of Upload Button. Can anyone help me on this ?
03-30 09:00:35.026: E/Trace(1086): error opening trace file: No such file or directory (2)
03-30 09:00:35.238: D/libEGL(1086): loaded /system/lib/egl/libEGL_emulation.so
03-30 09:00:35.242: D/(1086): HostConnection::get() New Host Connection established 0xb85a7800, tid 1086
03-30 09:00:35.646: D/libEGL(1086): loaded /system/lib/egl/libGLESv1_CM_emulation.so
03-30 09:00:35.650: D/libEGL(1086): loaded /system/lib/egl/libGLESv2_emulation.so
03-30 09:00:37.062: W/EGL_emulation(1086): eglSurfaceAttrib not implemented
03-30 09:00:37.106: D/OpenGLRenderer(1086): Enabling debug mode 0
03-30 09:00:37.158: D/OpenGLRenderer(1086): TextureCache::get: create texture(0xb8550e18): name, size, mSize = 1, 1048576, 1048576
03-30 09:00:38.226: D/OpenGLRenderer(1086): TextureCache::get: create texture(0xb8562e40): name, size, mSize = 2, 2304, 1050880
03-30 09:00:38.386: D/OpenGLRenderer(1086): TextureCache::get: create texture(0xb85555a0): name, size, mSize = 4, 9216, 1060096
03-30 09:00:38.398: D/OpenGLRenderer(1086): TextureCache::get: create texture(0xb858bd48): name, size, mSize = 5, 3328, 1063424
03-30 09:00:38.486: D/OpenGLRenderer(1086): TextureCache::get: create texture(0xb8539dd0): name, size, mSize = 7, 1024, 1064448
03-30 09:00:43.450: D/OpenGLRenderer(1086): TextureCache::get: create texture(0xb8577238): name, size, mSize = 9, 3328, 1067776
03-30 09:00:43.898: W/dalvikvm(1086): threadid=10: thread exiting with uncaught exception (group=0xa62e3288)
03-30 09:00:43.898: E/AndroidRuntime(1086): FATAL EXCEPTION: Thread-95
03-30 09:00:43.898: E/AndroidRuntime(1086): java.lang.NullPointerException
03-30 09:00:43.898: E/AndroidRuntime(1086): at java.io.File.fixSlashes(File.java:185)
03-30 09:00:43.898: E/AndroidRuntime(1086): at java.io.File.<init>(File.java:134)
03-30 09:00:43.898: E/AndroidRuntime(1086): at com.sunil.upload.MainActivity.uploadFile(MainActivity.java:115)
03-30 09:00:43.898: E/AndroidRuntime(1086): at com.sunil.upload.MainActivity$1.run(MainActivity.java:72)
03-30 09:00:43.898: E/AndroidRuntime(1086): at java.lang.Thread.run(Thread.java:856)
03-30 09:00:44.050: W/EGL_emulation(1086): eglSurfaceAttrib not implemented
03-30 09:00:44.230: D/OpenGLRenderer(1086): TextureCache::get: create texture(0xb8558c50): name, size, mSize = 12, 15360, 1083136
03-30 09:00:44.242: D/OpenGLRenderer(1086): TextureCache::get: create texture(0xb8551420): name, size, mSize = 13, 9216, 1092352
03-30 09:00:44.294: D/OpenGLRenderer(1086): TextureCache::get: create texture(0xb8551880): name, size, mSize = 14, 9216, 1101568
03-30 09:00:45.598: D/OpenGLRenderer(1086): TextureCache::flush: target size: 660940
03-30 09:00:45.598: D/OpenGLRenderer(1086): TextureCache::callback: name, removed size, mSize = 9, 3328, 1098240
03-30 09:00:45.598: D/OpenGLRenderer(1086): TextureCache::callback: name, removed size, mSize = 1, 1048576, 49664
03-30 09:00:45.634: E/WindowManager(1086): Activity com.sunil.upload.MainActivity has leaked window com.android.internal.policy.impl.PhoneWindow$DecorView#53473594 that was originally added here
03-30 09:00:45.634: E/WindowManager(1086): android.view.WindowLeaked: Activity com.sunil.upload.MainActivity has leaked window com.android.internal.policy.impl.PhoneWindow$DecorView#53473594 that was originally added here
03-30 09:00:45.634: E/WindowManager(1086): at android.view.ViewRootImpl.<init>(ViewRootImpl.java:374)
03-30 09:00:45.634: E/WindowManager(1086): at android.view.WindowManagerImpl.addView(WindowManagerImpl.java:292)
03-30 09:00:45.634: E/WindowManager(1086): at android.view.WindowManagerImpl.addView(WindowManagerImpl.java:224)
03-30 09:00:45.634: E/WindowManager(1086): at android.view.WindowManagerImpl$CompatModeWrapper.addView(WindowManagerImpl.java:149)
03-30 09:00:45.634: E/WindowManager(1086): at android.view.Window$LocalWindowManager.addView(Window.java:547)
03-30 09:00:45.634: E/WindowManager(1086): at android.app.Dialog.show(Dialog.java:277)
03-30 09:00:45.634: E/WindowManager(1086): at android.app.ProgressDialog.show(ProgressDialog.java:116)
03-30 09:00:45.634: E/WindowManager(1086): at android.app.ProgressDialog.show(ProgressDialog.java:99)
03-30 09:00:45.634: E/WindowManager(1086): at com.sunil.upload.MainActivity.onClick(MainActivity.java:67)
03-30 09:00:45.634: E/WindowManager(1086): at android.view.View.performClick(View.java:4084)
03-30 09:00:45.634: E/WindowManager(1086): at android.view.View$PerformClick.run(View.java:16966)
03-30 09:00:45.634: E/WindowManager(1086): at android.os.Handler.handleCallback(Handler.java:615)
03-30 09:00:45.634: E/WindowManager(1086): at android.os.Handler.dispatchMessage(Handler.java:92)
03-30 09:00:45.634: E/WindowManager(1086): at android.os.Looper.loop(Looper.java:137)
03-30 09:00:45.634: E/WindowManager(1086): at android.app.ActivityThread.main(ActivityThread.java:4745)
03-30 09:00:45.634: E/WindowManager(1086): at java.lang.reflect.Method.invokeNative(Native Method)
03-30 09:00:45.634: E/WindowManager(1086): at java.lang.reflect.Method.invoke(Method.java:511)
03-30 09:00:45.634: E/WindowManager(1086): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:786)
03-30 09:00:45.634: E/WindowManager(1086): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:553)
03-30 09:00:45.634: E/WindowManager(1086): at dalvik.system.NativeStart.main(Native Method)
03-30 09:00:45.906: I/Process(1086): Sending signal. PID: 1086 SIG: 9
Code:
public class MainActivity extends Activity implements OnClickListener{
private TextView messageText;
private Button uploadButton, btnselectpic;
private ImageView imageview;
private int serverResponseCode = 0;
private ProgressDialog dialog = null;
private String upLoadServerUri = null;
private String imagepath=null;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
uploadButton = (Button)findViewById(R.id.uploadButton);
btnselectpic = (Button)findViewById(R.id.button_selectpic);
messageText = (TextView)findViewById(R.id.messageText);
imageview = (ImageView)findViewById(R.id.imageView_pic);
btnselectpic.setOnClickListener(this);
uploadButton.setOnClickListener(this);
upLoadServerUri = "http://localhost/UploadFile.php";
ImageView img= new ImageView(this);
}
#Override
public void onClick(View arg0) {
if(arg0==btnselectpic)
{
Intent intent = new Intent();
intent.setType("image/*");
intent.setAction(Intent.ACTION_GET_CONTENT);
startActivityForResult(Intent.createChooser(intent, "Complete action using"), 1);
}
else if (arg0==uploadButton) {
dialog = ProgressDialog.show(MainActivity.this, "", "Uploading file...", true);
messageText.setText("uploading started.....");
new Thread(new Runnable() {
public void run() {
uploadFile(imagepath);
}
}).start();
}
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if (requestCode == 1 && resultCode == RESULT_OK) {
//Bitmap photo = (Bitmap) data.getData().getPath();
Uri selectedImageUri = data.getData();
imagepath = getPath(selectedImageUri);
Bitmap bitmap=BitmapFactory.decodeFile(imagepath);
imageview.setImageBitmap(bitmap);
messageText.setText("Uploading file path:" +imagepath);
}
}
public String getPath(Uri uri) {
String[] projection = { MediaStore.Images.Media.DATA };
Cursor cursor = managedQuery(uri, projection, null, null, null);
int column_index = cursor.getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
cursor.moveToFirst();
return cursor.getString(column_index);
}
public int uploadFile(String sourceFileUri) {
String fileName = sourceFileUri;
HttpURLConnection conn = null;
DataOutputStream dos = null;
String lineEnd = "\r\n";
String twoHyphens = "--";
String boundary = "*****";
int bytesRead, bytesAvailable, bufferSize;
byte[] buffer;
int maxBufferSize = 1 * 1024 * 1024;
File sourceFile = new File(sourceFileUri);
if (!sourceFile.isFile()) {
dialog.dismiss();
Log.e("uploadFile", "Source File not exist :"+imagepath);
runOnUiThread(new Runnable() {
public void run() {
messageText.setText("Source File not exist :"+ imagepath);
}
});
return 0;
}
else
{
try {
// open a URL connection to the Servlet
FileInputStream fileInputStream = new FileInputStream(sourceFile);
URL url = new URL(upLoadServerUri);
// Open a HTTP connection to the URL
conn = (HttpURLConnection) url.openConnection();
conn.setDoInput(true); // Allow Inputs
conn.setDoOutput(true); // Allow Outputs
conn.setUseCaches(false); // Don't use a Cached Copy
conn.setRequestMethod("POST");
conn.setRequestProperty("Connection", "Keep-Alive");
conn.setRequestProperty("ENCTYPE", "multipart/form-data");
conn.setRequestProperty("Content-Type", "multipart/form-data;boundary=" + boundary);
conn.setRequestProperty("uploaded_file", fileName);
dos = new DataOutputStream(conn.getOutputStream());
dos.writeBytes(twoHyphens + boundary + lineEnd);
dos.writeBytes("Content-Disposition: form-data; name=\"uploaded_file\";filename=\""
+ fileName + "\"" + lineEnd);
dos.writeBytes(lineEnd);
// create a buffer of maximum size
bytesAvailable = fileInputStream.available();
bufferSize = Math.min(bytesAvailable, maxBufferSize);
buffer = new byte[bufferSize];
// read file and write it into form...
bytesRead = fileInputStream.read(buffer, 0, bufferSize);
while (bytesRead > 0) {
dos.write(buffer, 0, bufferSize);
bytesAvailable = fileInputStream.available();
bufferSize = Math.min(bytesAvailable, maxBufferSize);
bytesRead = fileInputStream.read(buffer, 0, bufferSize);
}
// send multipart form data necesssary after file data...
dos.writeBytes(lineEnd);
dos.writeBytes(twoHyphens + boundary + twoHyphens + lineEnd);
// Responses from the server (code and message)
serverResponseCode = conn.getResponseCode();
String serverResponseMessage = conn.getResponseMessage();
Log.i("uploadFile", "HTTP Response is : "
+ serverResponseMessage + ": " + serverResponseCode);
if(serverResponseCode == 200){
runOnUiThread(new Runnable() {
public void run() {
String msg = "File Upload Completed.\n\n See uploaded file here : \n\n"
+" F:/wamp/wamp/www/uploads";
messageText.setText(msg);
Toast.makeText(MainActivity.this, "File Upload Complete.", Toast.LENGTH_SHORT).show();
}
});
}
//close the streams //
fileInputStream.close();
dos.flush();
dos.close();
} catch (MalformedURLException ex) {
dialog.dismiss();
ex.printStackTrace();
runOnUiThread(new Runnable() {
public void run() {
messageText.setText("MalformedURLException Exception : check script url.");
Toast.makeText(MainActivity.this, "MalformedURLException", Toast.LENGTH_SHORT).show();
}
});
Log.e("Upload file to server", "error: " + ex.getMessage(), ex);
} catch (Exception e) {
dialog.dismiss();
e.printStackTrace();
runOnUiThread(new Runnable() {
public void run() {
messageText.setText("Got Exception : see logcat ");
Toast.makeText(MainActivity.this, "Got Exception : see logcat ", Toast.LENGTH_SHORT).show();
}
});
Log.e("Upload file to server Exception", "Exception : " + e.getMessage(), e);
}
dialog.dismiss();
return serverResponseCode;
} // End else block
}
}
UploadFile.php :
<?php
$file_path = "uploads/";
$file_path = $file_path . basename( $_FILES['uploaded_file']['name']);
if(move_uploaded_file($_FILES['uploaded_file']['tmp_name'], $file_path)) {
echo "success";
} else{
echo "fail";
}
?>

Check your logs : you have NullPonterException in line :
File sourceFile = new File(sourceFileUri); // your sourceFileUri = null here,
since you call uploadFile() with null agrument.

Related

android video mp4 upload to php server

hello i am having trouble uploading a video file to my server the code i am using was working before now it no longer works after i switched servers i don't know what the problem is please help
upload code :
private class sendvid extends AsyncTask<String, String, String> {
File mediaStorageDir = new File(Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_MOVIES), "reelyChat/vids/"+vid_name);
#Override
protected String doInBackground(String... urls) {
File mediaFile = new File(mediaStorageDir.getPath() + File.separator + vid_name);
String url = urls[0];
uploadvid(url, mediaStorageDir);
return null;
}
#Override
protected void onPostExecute(String result) {
newVideo = mediaStorageDir;
uploadIcon.setVisibility(View.GONE);
}
}
public int uploadvid(String SERVER_URL, File sourceFileUri){
int serverResponseCode = 200;
HttpURLConnection conn = null;
DataOutputStream dos = null;
String lineEnd = "\r\n";
String twoHyphens = "--";
String boundary = "------------------------afb19f4aeefb356c";
int bytesRead, bytesAvailable, bufferSize;
byte[] buffer;
int maxBufferSize = 1 * 1024 * 1024;
File sourceFile = sourceFileUri;
if (!sourceFile.isFile()) {
return 0; //RETURN #1
}
else{
try{
Log.v("joshtag","UPLOADING .WAV FILE");
FileInputStream fileInputStream = new FileInputStream(sourceFile);
URL url = new URL(SERVER_URL);
Log.v("joshtag","UL URL: "+url.toString());
// Open a HTTP connection to the URL
conn = (HttpURLConnection) url.openConnection();
conn.setDoInput(true); // Allow Inputs
conn.setDoOutput(true); // Allow Outputs
conn.setUseCaches(false); // Don't use a Cached Copy
conn.setRequestMethod("POST");
// conn.setRequestProperty("Connection", "Keep-Alive");
conn.setRequestProperty("ENCTYPE", "multipart/form-data");
conn.setRequestProperty("Content-Type", "multipart/form-data;boundary=" + boundary);
conn.setRequestProperty("file", sourceFile.getName());
conn.setRequestProperty("user", "value_1");
//so on and so forth...
//conn.setRequestProperty("param", "value");
conn.setRequestProperty("connection", "close");
dos = new DataOutputStream(conn.getOutputStream());
dos.writeBytes(twoHyphens + boundary + lineEnd);
dos.writeBytes("Content-Disposition: form-data; name=\"file\";filename=\"" + sourceFile.getName() + "\"" + lineEnd);
dos.writeBytes(lineEnd);
// create a buffer of maximum size
bytesAvailable = fileInputStream.available();
bufferSize = Math.min(bytesAvailable, maxBufferSize);
buffer = new byte[bufferSize];
// read file and write it into form...
bytesRead = fileInputStream.read(buffer, 0, bufferSize);
while(bytesRead > 0){
dos.write(buffer, 0, bufferSize);
bytesAvailable = fileInputStream.available();
bufferSize = Math.min(bytesAvailable, maxBufferSize);
bytesRead = fileInputStream.read(buffer, 0, bufferSize);
Log.i("joshtag","->");
}
Log.i("joshtag","->->");
// send multipart form data necesssary after file data...
dos.writeBytes(lineEnd);
dos.writeBytes(twoHyphens + boundary + twoHyphens + lineEnd);
conn.connect();
Log.i("joshtag","->->->");
// Responses from the server (code and message)
serverResponseCode = conn.getResponseCode();
Log.i("joshtag","->->->->");
String serverResponseMessage = conn.getResponseMessage().toString();
Log.i("joshtag","->->->->->");
Log.i("joshtag", "HTTP Response is : " + serverResponseMessage + ": " + serverResponseCode);
// ------------------ read the SERVER RESPONSE
BufferedReader inStream;
String str="";
String response="";
try{
Log.i("joshtag","->->->->->->");
inStream = new BufferedReader(new InputStreamReader(conn.getInputStream()));
while((str = inStream.readLine()) != null) {
Log.e("joshtag", "SOF Server Response" + str);
response = str;
}
inStream.close();
}
catch (IOException ioex) {
Log.e("joshtag", "SOF error: " + ioex.getMessage(), ioex);
}
conn.disconnect();
conn = null;
//close the streams //
fileInputStream.close();
dos.flush();
dos.close();
if(serverResponseCode == 201){
Log.e("*** SERVER RESPONSE: 201" + response);
}//END IF Response code 201
// conn.disconnect();
}//END TRY - FILE READ
catch (MalformedURLException ex) {
ex.printStackTrace();
Log.e("joshtag", "UL error: " + ex.getMessage(), ex);
} //CATCH - URL Exception
catch (Exception e) {
e.printStackTrace();
Log.e("Upload file to server Exception", "Exception : " + e.getMessage(), e);
}
return serverResponseCode; //after try
}//END ELSE, if file exists.
}
php counterpart:
$vid_name = $_FILES["file"]["name"];
$split = strtok($vid_name, "_");
$split = strtok("_");
$user = $split;
$target_dir = "../users/$user/profileVid/";
$target_file = $target_dir . basename($_FILES["file"]["name"]);
move_uploaded_file($_FILES["file"]["tmp_name"], $target_file);
here is the logcast:
07-14 04:26:47.822 24150-24170/com.reelychat.reelychat I/dalvikvm: "AsyncTask #1" prio=5 tid=11 RUNNABLE
07-14 04:26:47.822 24150-24170/com.reelychat.reelychat I/dalvikvm: | group="main" sCount=0 dsCount=0 obj=0x41e9d360 self=0x5012c6d0
07-14 04:26:47.822 24150-24170/com.reelychat.reelychat I/dalvikvm: | sysTid=24170 nice=10 sched=0/0 cgrp=apps/bg_non_interactive handle=1074255192
07-14 04:26:47.822 24150-24170/com.reelychat.reelychat I/dalvikvm: | state=R schedstat=( 0 0 0 ) utm=27 stm=17 core=1
07-14 04:26:47.822 24150-24170/com.reelychat.reelychat I/dalvikvm: at java.io.ByteArrayOutputStream.expand(ByteArrayOutputStream.java:~91)
07-14 04:26:47.822 24150-24170/com.reelychat.reelychat I/dalvikvm: at java.io.ByteArrayOutputStream.write(ByteArrayOutputStream.java:201)
07-14 04:26:47.822 24150-24170/com.reelychat.reelychat I/dalvikvm: at libcore.net.http.RetryableOutputStream.write(RetryableOutputStream.java:61)
07-14 04:26:47.822 24150-24170/com.reelychat.reelychat I/dalvikvm: at java.io.DataOutputStream.write(DataOutputStream.java:98)
07-14 04:26:47.832 24150-24170/com.reelychat.reelychat I/dalvikvm: at com.reelychat.reelychat.ProfileUser.uploadvid(ProfileUser.java:1027)
07-14 04:26:47.832 24150-24170/com.reelychat.reelychat I/dalvikvm: at com.reelychat.reelychat.ProfileUser$sendvid.doInBackground(ProfileUser.java:1370)
07-14 04:26:47.832 24150-24170/com.reelychat.reelychat I/dalvikvm: at com.reelychat.reelychat.ProfileUser$sendvid.doInBackground(ProfileUser.java:1357)
07-14 04:26:47.832 24150-24170/com.reelychat.reelychat I/dalvikvm: at android.os.AsyncTask$2.call(AsyncTask.java:287)
07-14 04:26:47.842 24150-24170/com.reelychat.reelychat I/dalvikvm: at java.util.concurrent.FutureTask.run(FutureTask.java:234)
07-14 04:26:47.842 24150-24170/com.reelychat.reelychat I/dalvikvm: at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1080)
07-14 04:26:47.842 24150-24170/com.reelychat.reelychat I/dalvikvm: at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:573)
07-14 04:26:47.842 24150-24170/com.reelychat.reelychat I/dalvikvm: at java.lang.Thread.run(Thread.java:856)
07-14 04:26:47.842 24150-24170/com.reelychat.reelychat W/dalvikvm: threadid=11: thread exiting with uncaught exception (group=0x41533930)
07-14 04:26:47.842 24150-24170/com.reelychat.reelychat E/AndroidRuntime: FATAL EXCEPTION: AsyncTask #1
java.lang.RuntimeException: An error occured while executing doInBackground()
at android.os.AsyncTask$3.done(AsyncTask.java:299)
at java.util.concurrent.FutureTask.finishCompletion(FutureTask.java:352)
at java.util.concurrent.FutureTask.setException(FutureTask.java:219)
at java.util.concurrent.FutureTask.run(FutureTask.java:239)
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1080)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:573)
at java.lang.Thread.run(Thread.java:856)
Caused by: java.lang.OutOfMemoryError
at java.io.ByteArrayOutputStream.expand(ByteArrayOutputStream.java:91)
at java.io.ByteArrayOutputStream.write(ByteArrayOutputStream.java:201)
at libcore.net.http.RetryableOutputStream.write(RetryableOutputStream.java:61)
at java.io.DataOutputStream.write(DataOutputStream.java:98)
at com.reelychat.reelychat.ProfileUser.uploadvid(ProfileUser.java:1027)
at com.reelychat.reelychat.ProfileUser$sendvid.doInBackground(ProfileUser.java:1370)
at com.reelychat.reelychat.ProfileUser$sendvid.doInBackground(ProfileUser.java:1357)
at android.os.AsyncTask$2.call(AsyncTask.java:287)
at java.util.concurrent.FutureTask.run(FutureTask.java:234)
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1080) 
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:573) 
at java.lang.Thread.run(Thread.java:856) 

Upload file to server using android

I am using the code below to upload files on server. But whenever I run this code my application closes unexpectedly.
Code:
import java.io.DataOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import android.annotation.SuppressLint;
import android.app.Activity;
import android.app.ProgressDialog;
import android.util.Log;
import android.widget.TextView;
import android.widget.Toast;
#SuppressLint("Registered") public class UploadToServer extends Activity {
TextView messageText;
//Button uploadButton;
int serverResponseCode = 0;
//ProgressDialog dialog = null;
String upLoadServerUri = null;
/********** File Path *************/
String uploadFilePath = "/mnt/sdcard/";
String uploadFileName = "service_lifecycle.png";
void uploadToServer(File file, TextView msgText)
{
/************* Php script path ****************/
upLoadServerUri = "http://192.168.1.3/media/UploadToServer.php";
messageText = msgText;
uploadFilePath = file.getParent()+"/";
uploadFileName = file.getName();
try
{
// dialog = ProgressDialog.show(UploadToServer.this, "", "Uploading file...", true);
}
catch(Exception e)
{
msgText.setText("1 : "+e.toString());
}
new Thread(new Runnable() {
public void run() {
runOnUiThread(new Runnable() {
public void run() {
messageText.setText("uploading started.....");
}
});
try{
uploadFile(uploadFilePath + "" + uploadFileName);
}catch(Exception e)
{messageText.setText(e.toString());}
}
}).start();
}
public int uploadFile(String sourceFileUri) {
String fileName = sourceFileUri;
HttpURLConnection conn = null;
DataOutputStream dos = null;
String lineEnd = "\r\n";
String twoHyphens = "--";
String boundary = "*****";
int bytesRead, bytesAvailable, bufferSize;
byte[] buffer;
int maxBufferSize = 1 * 1024 * 1024;
File sourceFile = new File(sourceFileUri);
if (!sourceFile.isFile()) {
// dialog.dismiss();
Log.e("uploadFile", "Source File not exist :"
+uploadFilePath + "" + uploadFileName);
runOnUiThread(new Runnable() {
public void run() {
messageText.setText("Source File not exist :"
+uploadFilePath + "" + uploadFileName);
}
});
return 0;
}
else
{
try {
messageText.setText("1");
// open a URL connection to the Servlet
FileInputStream fileInputStream = new FileInputStream(sourceFile);
URL url = new URL(upLoadServerUri);
// Open a HTTP connection to the URL
conn = (HttpURLConnection) url.openConnection();
conn.setDoInput(true); // Allow Inputs
conn.setDoOutput(true); // Allow Outputs
conn.setUseCaches(false); // Don't use a Cached Copy
conn.setRequestMethod("POST");
conn.setRequestProperty("Connection", "Keep-Alive");
conn.setRequestProperty("ENCTYPE", "multipart/form-data");
conn.setRequestProperty("Content-Type", "multipart/form-data;boundary=" + boundary);
conn.setRequestProperty("uploaded_file", fileName);
dos = new DataOutputStream(conn.getOutputStream());
dos.writeBytes(twoHyphens + boundary + lineEnd);
dos.writeBytes("Content-Disposition: form-data; name=\"uploaded_file\";filename=\""+ fileName + "\"" + lineEnd);
//-=----------
messageText.setText("2");
dos.writeBytes(lineEnd);
// create a buffer of maximum size
bytesAvailable = fileInputStream.available();
bufferSize = Math.min(bytesAvailable, maxBufferSize);
buffer = new byte[bufferSize];
// read file and write it into form...
bytesRead = fileInputStream.read(buffer, 0, bufferSize);
messageText.setText("3");
while (bytesRead > 0) {
dos.write(buffer, 0, bufferSize);
bytesAvailable = fileInputStream.available();
bufferSize = Math.min(bytesAvailable, maxBufferSize);
bytesRead = fileInputStream.read(buffer, 0, bufferSize);
}
messageText.setText("4");
// send multipart form data necesssary after file data...
dos.writeBytes(lineEnd);
dos.writeBytes(twoHyphens + boundary + twoHyphens + lineEnd);
// Responses from the server (code and message)
serverResponseCode = conn.getResponseCode();
String serverResponseMessage = conn.getResponseMessage();
Log.i("uploadFile", "HTTP Response is : "
+ serverResponseMessage + ": " + serverResponseCode);
if(serverResponseCode == 200){
runOnUiThread(new Runnable() {
public void run() {
String msg = "File Upload Completed.\n\n See uploaded file here : \n\n"
+" http://www.androidexample.com/media/uploads/"
+uploadFileName;
messageText.setText(msg);
Toast.makeText(UploadToServer.this, "File Upload Complete.",
Toast.LENGTH_SHORT).show();
}
});
}
//close the streams //
fileInputStream.close();
dos.flush();
dos.close();
} catch (MalformedURLException ex) {
// dialog.dismiss();
ex.printStackTrace();
runOnUiThread(new Runnable() {
public void run() {
messageText.setText("MalformedURLException Exception : check script url.");
Toast.makeText(UploadToServer.this, "MalformedURLException",
Toast.LENGTH_SHORT).show();
}
});
Log.e("Upload file to server", "error: " + ex.getMessage(), ex);
} catch (Exception e) {
// dialog.dismiss();
e.printStackTrace();
runOnUiThread(new Runnable() {
public void run() {
messageText.setText("Got Exception : see logcat ");
Toast.makeText(UploadToServer.this, "Got Exception : see logcat ",
Toast.LENGTH_SHORT).show();
}
});
Log.e("Upload file to server Exception", "Exception : "
+ e.getMessage(), e);
}
// dialog.dismiss();
return serverResponseCode;
} // End else block
}
}
And code for php is:
<?php
$file_path = "uploads/";
$file_path = $file_path . basename( $_FILES['uploaded_file']['name']);
if(move_uploaded_file($_FILES['uploaded_file']['tmp_name'], $file_path)) {
echo "success";
} else{
echo "fail";
}
?>
And I am calling this method through:
void openDialogBox()
{
Intent intent = new Intent(Intent.ACTION_GET_CONTENT);
intent.setType("file/*");
startActivityForResult(intent, PICK_CONTACT_REQUEST);
}
protected void onActivityResult(int requestCode, int resultCode,
Intent data) {
if (requestCode == PICK_CONTACT_REQUEST) {
if (resultCode == RESULT_OK) {
// A contact was picked. Here we will just display it
// to the user.
Uri uri = data.getData();
File file = new File(uri.toString());
if(uri.toString().startsWith("file:/"))
file = new File(uri.toString().substring(6));
msgTxt.setText(file.getName());
Toast.makeText(this, uri.toString(), Toast.LENGTH_SHORT).show();
try
{
UploadToServer upToServer = new UploadToServer();
upToServer.uploadToServer(file,msgTxt);
}catch(Exception e)
{
msgTxt.setText(e.toString());
e.printStackTrace();
}
}
}
}
I don't know how but it uploaded two image files before closing down.
Any help is appreciated.
03-07 02:24:35.092: W/Resources(2847): Converting to string: TypedValue{t=0x12/d=0x0 a=2 r=0x7f050003}
03-07 02:24:35.252: D/dalvikvm(2847): GC_FOR_ALLOC freed 118K, 6% free 3265K/3448K, paused 40ms, total 45ms
03-07 02:24:35.382: D/(2847): HostConnection::get() New Host Connection established 0xb80e2ae0, tid 2847
03-07 02:24:35.482: W/EGL_emulation(2847): eglSurfaceAttrib not implemented
03-07 02:24:35.502: D/OpenGLRenderer(2847): Enabling debug mode 0
03-07 02:24:40.332: W/IInputConnectionWrapper(2847): showStatusIcon on inactive InputConnection
03-07 02:24:49.832: W/EGL_emulation(2847): eglSurfaceAttrib not implemented
03-07 02:24:50.872: I/Choreographer(2847): Skipped 60 frames! The application may be doing too much work on its main thread.
03-07 02:24:51.612: D/dalvikvm(2847): GC_FOR_ALLOC freed 262K, 9% free
3464K/3792K, paused 348ms, total 351ms
03-07 02:24:52.072: D/dalvikvm(2847): GC_FOR_ALLOC freed 6K, 9% free 3553K/3888K, paused 410ms, total 411ms
03-07 02:24:54.862: I/uploadFile(2847): HTTP Response is : OK: 200
03-07 02:24:55.112: D/AndroidRuntime(2847): Shutting down VM
03-07 02:24:55.122: W/dalvikvm(2847): threadid=1: thread exiting with uncaught exception (group=0xb1a97b90)
03-07 02:24:55.122: E/AndroidRuntime(2847): FATAL EXCEPTION: main
03-07 02:24:55.122: E/AndroidRuntime(2847): Process: com.example.fileuploaddemo, PID: 2847
03-07 02:24:55.122: E/AndroidRuntime(2847): java.lang.NullPointerException
03-07 02:24:55.122: E/AndroidRuntime(2847): at android.content.ContextWrapper.getResources(ContextWrapper.java:89)
03-07 02:24:55.122: E/AndroidRuntime(2847): at android.view.ContextThemeWrapper.getResources(ContextThemeWrapper.java:78)
03-07 02:24:55.122: E/AndroidRuntime(2847): at android.widget.Toast.<init>(Toast.java:93)
03-07 02:24:55.122: E/AndroidRuntime(2847): at android.widget.Toast.makeText(Toast.java:241)
03-07 02:24:55.122: E/AndroidRuntime(2847): at com.example.fileuploaddemo.UploadToServer$9.run(UploadToServer.java:239)
03-07 02:24:55.122: E/AndroidRuntime(2847): at android.os.Handler.handleCallback(Handler.java:733)
03-07 02:24:55.122: E/AndroidRuntime(2847): at android.os.Handler.dispatchMessage(Handler.java:95)
03-07 02:24:55.122: E/AndroidRuntime(2847): at android.os.Looper.loop(Looper.java:137)
03-07 02:24:55.122: E/AndroidRuntime(2847): at android.app.ActivityThread.main(ActivityThread.java:4998)
03-07 02:24:55.122: E/AndroidRuntime(2847): at java.lang.reflect.Method.invokeNative(Native Method)
03-07 02:24:55.122: E/AndroidRuntime(2847): at java.lang.reflect.Method.invoke(Method.java:515)
03-07 02:24:55.122: E/AndroidRuntime(2847): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:777)
03-07 02:24:55.122: E/AndroidRuntime(2847): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:593)
03-07 02:24:55.122: E/AndroidRuntime(2847): at dalvik.system.NativeStart.main(Native Method)
03-07 02:24:58.642: I/Process(2847): Sending signal. PID: 2847 SIG: 9
And whenvever I comment the following part of code it works fine, no error, no unfortunately closing of app
Code:
Log.i("uploadFile", "HTTP Response is : "
+ serverResponseMessage + ": " + serverResponseCode);
if(serverResponseCode == 200)
{
runOnUiThread(new Runnable() {
public void run() {
String msg = "File Upload Completed.\n\n See uploaded file here : \n\n"
+" http://www.androidexample.com/media/uploads/"
+uploadFileName;
messageText.setText(msg);
Toast.makeText(UploadToServer.this, "File Upload Complete.",
Toast.LENGTH_SHORT).show();
}
});
}

"Unable to resume activity" after saving cropped image - Android

I want to load the image in ImageView after cropping the image and save it. But when it's resumes it gets crashed, but image is saving on selected location. I think the problem is in selectedImageUri. But I couldn't figure it out how to solve. Please someone help. Thanks in advance.
Code:
public class CatFragment extends Fragment implements OnClickListener{
private DBCreater dbCreate;
private static final int SELECT_PICTURE = 1;
private String selectedImagePath = "android.resource://com.example.abcd/" + R.drawable.pets;
private ImageView img;
//private Button imgBtn;
private Uri mCropImagedUri;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View gv = inflater.inflate(R.layout.new_pet, null);
Spinner sp = (Spinner) gv.findViewById(R.id.ETPetType);
// get reference
sp.setAdapter(new ArrayAdapter<String>(getActivity().getBaseContext(), android.R.layout.simple_spinner_dropdown_item, petType));
Button btnSubmit = (Button) gv.findViewById(R.id.ButtonNext);
btnSubmit.setOnClickListener(this);
img = (ImageView)gv.findViewById(R.id.ImageView01);
((Button) gv.findViewById(R.id.ETPetImg))
.setOnClickListener(new OnClickListener() {
public void onClick(View arg0) {
try {
Intent intent = new Intent();
intent.setType("image/*");
intent.setAction(Intent.ACTION_GET_CONTENT);
intent.putExtra("crop", "true");
intent.putExtra("aspectX", 0);
intent.putExtra("aspectY", 0);
intent.putExtra("outputX", 200);
intent.putExtra("outputY", 200);
intent.putExtra("return-data", false);
File f = createNewFile("CROP_");
try {
f.createNewFile();
} catch (IOException ex) {
Log.e("io", ex.getMessage());
}
mCropImagedUri = Uri.fromFile(f);
intent.putExtra(MediaStore.EXTRA_OUTPUT,
mCropImagedUri);
// start the activity - we handle returning in
// onActivityResult
startActivityForResult(intent, SELECT_PICTURE);
} catch (ActivityNotFoundException anfe) {
// display an error message
}
}
});
return gv;
}
private File createNewFile(String prefix){
if(prefix==null || "".equalsIgnoreCase(prefix)){
prefix="IMG_";
}
File newDirectory = new File(Environment.getExternalStorageDirectory()+"/test1/");
if(!newDirectory.exists()){
if(newDirectory.mkdir()){
Log.d(this.getClass().getName(), newDirectory.getAbsolutePath()+" directory created");
}
}
File file = new File(newDirectory,(prefix+System.currentTimeMillis()+".jpg"));
if(file.exists()){
//this wont be executed
file.delete();
try {
file.createNewFile();
} catch (IOException e) {
e.printStackTrace();
}
}
return file;
}
public void onActivityResult(int requestCode, int resultCode, Intent data) {
if (resultCode == Activity.RESULT_OK) {
if (requestCode == SELECT_PICTURE) {
Uri selectedImageUri = data.getData();
selectedImagePath = getPath(selectedImageUri); //To get image path
System.out.println("Image Path : " + selectedImagePath);
img.setImageURI(selectedImageUri);
}
}
}
public String getPath(Uri uri) {
String[] projection = { MediaStore.Images.Media.DATA };
//Cursor cursor = managedQuery(uri, projection, null, null, null);
Cursor cursor = getActivity().getContentResolver().query(uri, projection, null, null, null);
int column_index = cursor.getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
cursor.moveToFirst();
return cursor.getString(column_index);
}
#Override
public void onActivityCreated(Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
//access the database
dbCreate = new DBCreater(getActivity());
}
#Override
public void onClick(View v) {
displayNextAlert();
}
LogCat:
7214): FATAL EXCEPTION: main
11-15 07:15:38.215: E/AndroidRuntime(27214): java.lang.RuntimeException: Unable to resume activity {com.example.abcd/com.example.abcd.MainActivity}: java.lang.RuntimeException: Failure delivering result ResultInfo{who=android:fragment:0, request=1, result=-1, data=Intent { (has extras) }} to activity {com.example.abcd/com.example.abcd.MainActivity}: java.lang.NullPointerException
11-15 07:15:38.215: E/AndroidRuntime(27214): at android.app.ActivityThread.performResumeActivity(ActivityThread.java:2919)
11-15 07:15:38.215: E/AndroidRuntime(27214): at android.app.ActivityThread.handleResumeActivity(ActivityThread.java:2948)
11-15 07:15:38.215: E/AndroidRuntime(27214): at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2354)
11-15 07:15:38.215: E/AndroidRuntime(27214): at android.app.ActivityThread.access$700(ActivityThread.java:159)
11-15 07:15:38.215: E/AndroidRuntime(27214): at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1316)
11-15 07:15:38.215: E/AndroidRuntime(27214): at android.os.Handler.dispatchMessage(Handler.java:99)
11-15 07:15:38.215: E/AndroidRuntime(27214): at android.os.Looper.loop(Looper.java:176)
11-15 07:15:38.215: E/AndroidRuntime(27214): at android.app.ActivityThread.main(ActivityThread.java:5419)
11-15 07:15:38.215: E/AndroidRuntime(27214): at java.lang.reflect.Method.invokeNative(Native Method)
11-15 07:15:38.215: E/AndroidRuntime(27214): at java.lang.reflect.Method.invoke(Method.java:525)
11-15 07:15:38.215: E/AndroidRuntime(27214): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1046)
11-15 07:15:38.215: E/AndroidRuntime(27214): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:862)
11-15 07:15:38.215: E/AndroidRuntime(27214): at dalvik.system.NativeStart.main(Native Method)
11-15 07:15:38.215: E/AndroidRuntime(27214): Caused by: java.lang.RuntimeException: Failure delivering result ResultInfo{who=android:fragment:0, request=1, result=-1, data=Intent { (has extras) }} to activity {com.example.abcd/com.example.abcd.MainActivity}: java.lang.NullPointerException
11-15 07:15:38.215: E/AndroidRuntime(27214): at android.app.ActivityThread.deliverResults(ActivityThread.java:3500)
11-15 07:15:38.215: E/AndroidRuntime(27214): at android.app.ActivityThread.performResumeActivity(ActivityThread.java:2906)
11-15 07:15:38.215: E/AndroidRuntime(27214): ... 12 more
11-15 07:15:38.215: E/AndroidRuntime(27214): Caused by: java.lang.NullPointerException
11-15 07:15:38.215: E/AndroidRuntime(27214): at android.content.ContentResolver.acquireUnstableProvider(ContentResolver.java:1147)
11-15 07:15:38.215: E/AndroidRuntime(27214): at android.content.ContentResolver.query(ContentResolver.java:401)
11-15 07:15:38.215: E/AndroidRuntime(27214): at android.content.ContentResolver.query(ContentResolver.java:360)
11-15 07:15:38.215: E/AndroidRuntime(27214): at com.example.abcd.NewPetsFragment.getPath(NewPetsFragment.java:155)
11-15 07:15:38.215: E/AndroidRuntime(27214): at com.example.abcd.NewPetsFragment.onActivityResult(NewPetsFragment.java:143)
11-15 07:15:38.215: E/AndroidRuntime(27214): at android.app.Activity.dispatchActivityResult(Activity.java:5567)
11-15 07:15:38.215: E/AndroidRuntime(27214): at android.app.ActivityThread.deliverResults(ActivityThread.java:3496)
11-15 07:15:38.215: E/AndroidRuntime(27214): ... 13 more
Edited:
I changed OnActivityResult() like this:
if(data!=null) {
Bitmap thePic = (Bitmap) data.getExtras().get("data");
SharedPreferences preferences = PreferenceManager.getDefaultSharedPreferences(getActivity().getBaseContext());
String filename = preferences.getString("file_name", ""); // value to retrieve
String path = Environment.getExternalStorageDirectory()+"/PetSitter/Pet Images/" + filename;
img.setImageURI(Uri.parse(path.toString()));
} else {
// In createNewFile, make sure you already saved the filename (prefix+System.currentTimeMillis()+".jpg"), for example, to sharedpreferences then get the filename and apply in path
SharedPreferences preferences = PreferenceManager.getDefaultSharedPreferences(getActivity().getBaseContext());
String filename = preferences.getString("file_name", ""); // value to retrieve
String path = Environment.getExternalStorageDirectory()+"/PetSitter/Pet Images/" + filename;
BitmapFactory.Options bfo = new BitmapFactory.Options();
bfo.inSampleSize = 1;
Bitmap bmp = BitmapFactory.decodeFile(path, bfo);
img.setImageBitmap(bmp);
}
It's seems to be working with image preview and everything. But what do thing? Is it a good practice to do? and how will be the memory usage by using like this?
In OnActivityResult():
if(data!=null) {
Bitmap thePic = (Bitmap) data.getExtras().get("data");
img.setImageBitmap(thePic);
} else {
// In createNewFile, make sure you already saved the filename (prefix+System.currentTimeMillis()+".jpg"), for example, to sharedpreferences then get the filename and apply in path
SharedPreferences preferences = PreferenceManager.getDefaultSharedPreferences(getActivity().getBaseContext());
String filename = preferences.getString("file_name", ""); // value to retrieve
String path = Environment.getExternalStorageDirectory()+"/test1/" + filename;
BitmapFactory.Options bfo = new BitmapFactory.Options();
bfo.inSampleSize = 1;
Bitmap bmp = BitmapFactory.decodeFile(path, bfo);
img.setImageBitmap(bmp);
}
In createNewFile
private File createNewFile(String prefix){
if(prefix==null || "".equalsIgnoreCase(prefix)){
prefix="IMG_";
}
File newDirectory = new File(Environment.getExternalStorageDirectory()+"/test1/");
if(!newDirectory.exists()){
if(newDirectory.mkdir()){
Log.d(this.getClass().getName(), newDirectory.getAbsolutePath()+" directory created");
}
}
// modifications applied here
long mDate = System.currentTimeMillis();
File file = new File(newDirectory,(prefix+mDate+".jpg"));
String filename = prefix+mDate+".jpg";
SharedPreferences preferences = PreferenceManager.getDefaultSharedPreferences(getActivity().getBaseContext());
SharedPreferences.Editor editor = preferences.edit();
editor.putString("file_name", filename); // value to store
editor.commit();
if(file.exists()){
//this wont be executed
file.delete();
try {
file.createNewFile();
} catch (IOException e) {
e.printStackTrace();
}
}
return file;
}
Uri selectedImageURI = data.getData();
imageFile = new File(getRealPathFromURI(selectedImageURI));
And
private String getRealPathFromURI(Uri contentURI) {
Cursor cursor = getContentResolver().query(contentURI, null, null, null, null);
if (cursor == null) { // Source is Dropbox or other similar local file path
return contentURI.getPath();
} else {
cursor.moveToFirst();
int idx = cursor.getColumnIndex(MediaStore.Images.ImageColumns.DATA);
return cursor.getString(idx);
}
}
Try this in onActivityResult
Bitmap photo = (Bitmap) data.getExtras().get("data");
img.setImageBitmap(photo);
I changed OnActivityResult() like this:
if(data!=null) {
Bitmap thePic = (Bitmap) data.getExtras().get("data");
SharedPreferences preferences = PreferenceManager.getDefaultSharedPreferences(getActivity().getBaseContext());
String filename = preferences.getString("file_name", ""); // value to retrieve
String path = Environment.getExternalStorageDirectory()+"/PetSitter/Pet Images/" + filename;
img.setImageURI(Uri.parse(path.toString()));
} else {
// In createNewFile, make sure you already saved the filename (prefix+System.currentTimeMillis()+".jpg"), for example, to sharedpreferences then get the filename and apply in path
SharedPreferences preferences = PreferenceManager.getDefaultSharedPreferences(getActivity().getBaseContext());
String filename = preferences.getString("file_name", ""); // value to retrieve
String path = Environment.getExternalStorageDirectory()+"/PetSitter/Pet Images/" + filename;
BitmapFactory.Options bfo = new BitmapFactory.Options();
bfo.inSampleSize = 1;
Bitmap bmp = BitmapFactory.decodeFile(path, bfo);
img.setImageBitmap(bmp);
}
It's seems to be working with image preview and everything.

Fatal signal 11 (SIGSEGV) at 0x00000010 (code=1), thread 1894

private String recholder = "not";
#Override
public void onCreate(Bundle icicle) {
super.onCreate(icicle);
outputFile = Environment.getExternalStorageDirectory().
getAbsolutePath() + "/recordingnijez.mp3";
myRecorder = new MediaRecorder();
myRecorder.setAudioSource(MediaRecorder.AudioSource.DEFAULT);
myRecorder.setOutputFormat(MediaRecorder.OutputFormat.AMR_NB);
myRecorder.setAudioEncoder(MediaRecorder.AudioEncoder.AMR_NB);
myRecorder.setOutputFile(outputFile);
addListenerButton();
}
private void addListenerButton() {
recbtn = (Button)findViewById(R.id.recbut);
recbtn.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
start(v);
}
});
}
public void start(View view){
if ("recording".equals(recholder)){
try {
myRecorder.stop();
myRecorder.release();
//myRecorder = null;
recbtn.setText(getString(R.string.recBtn));
recholder="not";
Toast.makeText(getApplicationContext(), "Stop recording...",
Toast.LENGTH_SHORT).show();
} catch (IllegalStateException e) {
// it is called before start()
e.printStackTrace();
} catch (RuntimeException e) {
// no valid audio/video data has been received
e.printStackTrace();
}
}
else{
try {
File file = new File (Environment.getExternalStorageDirectory() + "/recordingnijez.mp3");
if (file.exists()){
file.delete();
myRecorder.prepare();
myRecorder.start();
recholder="recording";
recbtn.setText(getString(R.string.stopBtn));
}
else{
myRecorder.prepare();
myRecorder.start();
recholder="recording";
recbtn.setText(getString(R.string.stopBtn));
}
} catch (IllegalStateException e) {
// start:it is called before prepare()
// prepare: it is called after start() or before setOutputFormat()
e.printStackTrace();
} catch (IOException e) {
// prepare() fails
e.printStackTrace();
}
Toast.makeText(getApplicationContext(), "Start recording...",
Toast.LENGTH_SHORT).show();
}
}
it has problem when i try to record twice. i dont know how to fix it i tried everything
heres the logcat
02-12 09:33:50.471: A/libc(1894): Fatal signal 11 (SIGSEGV) at 0x00000010 (code=1), thread 1894 (.example.mixpad)
02-12 09:33:51.191: E/Trace(1961): error opening trace file: No such file or directory (2)
02-12 09:33:51.331: D/dalvikvm(1961): GC_FOR_ALLOC freed 43K, 3% free 8017K/8195K, paused 3ms, total 3ms
02-12 09:33:51.359: I/dalvikvm-heap(1961): Grow heap (frag case) to 10.785MB for 3067212-byte allocation
02-12 09:33:51.379: D/dalvikvm(1961): GC_CONCURRENT freed 1K, 2% free 11011K/11207K, paused 13ms+3ms, total 21ms
02-12 09:33:51.499: D/libEGL(1961): loaded /system/lib/egl/libEGL_emulation.so
02-12 09:33:51.507: D/(1961): HostConnection::get() New Host Connection established 0xb8b8a110, tid 1961
02-12 09:33:51.531: D/libEGL(1961): loaded /system/lib/egl/libGLESv1_CM_emulation.so
02-12 09:33:51.531: D/libEGL(1961): loaded /system/lib/egl/libGLESv2_emulation.so
02-12 09:33:51.611: W/EGL_emulation(1961): eglSurfaceAttrib not implemented
02-12 09:33:51.627: D/OpenGLRenderer(1961): Enabling debug mode 0
02-12 09:33:51.691: D/OpenGLRenderer(1961): TextureCache::get: create texture(0xb8b908e0): name, size, mSize = 1, 1048576, 1048576
02-12 09:33:51.735: D/OpenGLRenderer(1961): TextureCache::get: create texture(0xb8ba7d10): name, size, mSize = 2, 5184, 1053760
02-12 09:33:51.775: D/OpenGLRenderer(1961): TextureCache::get: create texture(0xb8bccaf8): name, size, mSize = 4, 20736, 1074496
02-12 09:33:51.839: D/OpenGLRenderer(1961): TextureCache::get: create texture(0xb8b8f730): name, size, mSize = 5, 3067200, 4141696
02-12 09:33:51.867: D/OpenGLRenderer(1961): TextureCache::get: create texture(0xb8be9798): name, size, mSize = 6, 7488, 4149184
02-12 09:33:51.871: D/OpenGLRenderer(1961): TextureCache::get: create texture(0xb8b88ff0): name, size, mSize = 7, 40984, 4190168
02-12 09:33:51.875: D/OpenGLRenderer(1961): TextureCache::get: create texture(0xb8b8f7c0): name, size, mSize = 8, 37412, 4227580
02-12 09:33:51.883: D/OpenGLRenderer(1961): TextureCache::get: create texture(0xb8ba8b60): name, size, mSize = 9, 33276, 4260856
02-12 09:33:51.887: D/OpenGLRenderer(1961): TextureCache::get: create texture(0xb8b9c0d8): name, size, mSize = 10, 32712, 4293568
02-12 09:33:51.891: D/OpenGLRenderer(1961): TextureCache::get: create texture(0xb8b8b840): name, size, mSize = 11, 2304, 4295872
I meet this problem too, please use myRecorder=null, I think that because myRecorder.release() has bug,
you can do that:
myRecorder.stop();
myRecorder.release();
myRecorder = null;
and other place append judgement
if(myRecorder != null){ ... }
Try adding this:
mediaRecorder.stop();
mediaRecorder.reset(); //instead of release() and =null
And then in
public void onStop() {
mediaRecorder.release();
mediaRecorder = null;
I have this...
if (recorder != null) {
recorder.stop();
recorder.reset();
recorder.release();
recorder = null;
}
... and works fine!
Try calling super first in your onCreate :
public void onCreate(Bundle icicle) {
super.onCreate(icicle);

Tesseract RECOGNITION fix?

I have been able to export my code into an application and use the Tess-Two file from this tutorial
to integrate the tesseract into it. But now I'm facing problems; when the picture is sent to the tesseract it just returns the same random characters each time: 'f' wig, W fin. A. " 5' ' ,{ >>zv' ' ~" > ';>'. What seems to be the problem?
ImageView iv;
TextView tv;
protected Bitmap _image;
protected Bitmap bmp;
public static String The_path = "/mnt/sdcard/DCIM/100MEDIA/TESS.jpg";
public static String lang = "eng";
public static final String DATA_PATH = Environment.getExternalStorageDirectory().toString() + "/SimpleAndroidOCR/";
private int pageSegmentationMode = TessBaseAPI.PageSegMode.PSM_AUTO;
#Override
public void onCreate(Bundle savedInstanceState) {
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 ((len = gin.read(buf)) > 0) {
while ((len = in.read(buf)) > 0) {
out.write(buf, 0, len);
}
in.close();
//gin.close();
out.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
};
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
iv = (ImageView) findViewById(R.id.imageView1);
tv = (TextView) findViewById(R.id.textView1);
Button but = (Button) findViewById(R.id.button1);
Button but2 = (Button) findViewById(R.id.button2);
but.setOnClickListener(new OnClickListener() {
public void onClick(View v){
//File file = new File( _path );
//Uri outputFileUri = Uri.fromFile( file );
Intent intent = new Intent(android.provider.MediaStore.ACTION_IMAGE_CAPTURE);
//intent.putExtra( MediaStore.EXTRA_OUTPUT, outputFileUri );
startActivityForResult(intent, 0);
}
});
but2.setOnClickListener(new OnClickListener() {
public void onClick(View v){
TessBaseAPI baseApi = new TessBaseAPI();
baseApi.setDebug(true);
baseApi.setPageSegMode(pageSegmentationMode);
baseApi.init(DATA_PATH, lang);
// DATA_PATH = Path to the storage
// lang for which the language data exists, usually "eng"
try {
baseApi.setImage(ReadFile.readBitmap(bmp));
String recognizedText = baseApi.getUTF8Text();
txt(recognizedText);
} catch(RuntimeException e) {
}
baseApi.end();
}
private void txt(String txt) {
// TODO Auto-generated method stub
tv.setText(txt);
}
});
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data){
super.onActivityResult(requestCode, resultCode, data);
BitmapFactory.Options options = new BitmapFactory.Options();
options.inPreferredConfig = Bitmap.Config.ARGB_8888;
options.inSampleSize = 4;
Bitmap bitmap = BitmapFactory.decodeFile(The_path, options);
try {
ExifInterface exif = new ExifInterface(The_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) {
// 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);
}
bitmap = toGrayscale(bitmap);
bitmap = bitmap.copy(Bitmap.Config.ARGB_8888, true);
} catch (IOException e) {
}
_image = (Bitmap) data.getExtras().get("data");
iv.setImageBitmap(_image);
bmp = bitmap;
} public static Bitmap toGrayscale(Bitmap bmpOriginal){
int width, height;
height = bmpOriginal.getHeight();
width = bmpOriginal.getWidth();
Bitmap bmpGrayscale = Bitmap.createBitmap(width, height, Bitmap.Config.RGB_565);
Canvas c = new Canvas(bmpGrayscale);
Paint paint = new Paint();
ColorMatrix cm = new ColorMatrix();
cm.setSaturation(0);
ColorMatrixColorFilter f = new ColorMatrixColorFilter(cm);
paint.setColorFilter(f);
c.drawBitmap(bmpOriginal, 0, 0, paint);
return bmpGrayscale;
}
here is the new log cat after adding the grayscale function:
(receiving a new set of reoccurring random characters)
01-26 10:21:36.973: D/libEGL(1389): loaded /system/lib/egl/libEGL_adreno200.so
01-26 10:21:36.973: D/libEGL(1389): loaded /system/lib/egl/libGLESv1_CM_adreno200.so
01-26 10:21:36.973: D/libEGL(1389): loaded /system/lib/egl/libGLESv2_adreno200.so
01-26 10:21:36.983: I/Adreno200-EGL(1389): <eglInitialize:269>: EGL 1.4 QUALCOMM build: Nondeterministic AU_full_mako_PARTNER-ANDROID/JB-MR1- DEV_CL2946718_release_AU (CL2946718)
01-26 10:21:36.983: I/Adreno200-EGL(1389): Build Date: 11/04/12 Sun
01-26 10:21:36.983: I/Adreno200-EGL(1389): Local Branch:
01-26 10:21:36.983: I/Adreno200-EGL(1389): Remote Branch: m/partner-android/jb-mr1-dev
01-26 10:21:36.983: I/Adreno200-EGL(1389): Local Patches: NONE
01-26 10:21:36.983: I/Adreno200-EGL(1389): Reconstruct Branch: NOTHING
01-26 10:21:37.043: D/OpenGLRenderer(1389): Enabling debug mode 0
01-26 10:21:45.502: E/BitmapFactory(1389): Unable to decode stream: java.io.FileNotFoundException: /mnt/sdcard/DCIM/100MEDIA/TESS.jpg: open failed: ENOENT (No such file or directory)
01-26 10:21:45.502: E/JHEAD(1389): can't open '/mnt/sdcard/DCIM/100MEDIA/TESS.jpg'
01-26 10:21:45.512: D/AndroidRuntime(1389): Shutting down VM
01-26 10:21:45.512: W/dalvikvm(1389): threadid=1: thread exiting with uncaught exception (group=0x417b0930)
01-26 10:21:45.522: E/AndroidRuntime(1389): FATAL EXCEPTION: main
01-26 10:21:45.522: E/AndroidRuntime(1389): java.lang.RuntimeException: Failure delivering result ResultInfo{who=null, request=0, result=-1, data=Intent { act=inline-data (has extras) }} to activity {com.cam.calc/cam.calc.Main}: java.lang.NullPointerException
01-26 10:21:45.522: E/AndroidRuntime(1389): at android.app.ActivityThread.deliverResults(ActivityThread.java:3319)
01-26 10:21:45.522: E/AndroidRuntime(1389): at android.app.ActivityThread.handleSendResult(ActivityThread.java:3362)
01-26 10:21:45.522: E/AndroidRuntime(1389): at android.app.ActivityThread.access$1100(ActivityThread.java:141)
01-26 10:21:45.522: E/AndroidRuntime(1389): at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1282)
01-26 10:21:45.522: E/AndroidRuntime(1389): at android.os.Handler.dispatchMessage(Handler.java:99)
01-26 10:21:45.522: E/AndroidRuntime(1389): at android.os.Looper.loop(Looper.java:137)
01-26 10:21:45.522: E/AndroidRuntime(1389): at android.app.ActivityThread.main(ActivityThread.java:5039)
01-26 10:21:45.522: E/AndroidRuntime(1389): at java.lang.reflect.Method.invokeNative(Native Method)
01-26 10:21:45.522: E/AndroidRuntime(1389): at java.lang.reflect.Method.invoke(Method.java:511)
01-26 10:21:45.522: E/AndroidRuntime(1389): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:793)
01-26 10:21:45.522: E/AndroidRuntime(1389): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:560)
01-26 10:21:45.522: E/AndroidRuntime(1389): at dalvik.system.NativeStart.main(Native Method)
01-26 10:21:45.522: E/AndroidRuntime(1389): Caused by: java.lang.NullPointerException
01-26 10:21:45.522: E/AndroidRuntime(1389): at cam.calc.Main.onActivityResult(Main.java:388)
01-26 10:21:45.522: E/AndroidRuntime(1389): at android.app.Activity.dispatchActivityResult(Activity.java:5293)
01-26 10:21:45.522: E/AndroidRuntime(1389): at android.app.ActivityThread.deliverResults(ActivityThread.java:3315)
01-26 10:21:45.522: E/AndroidRuntime(1389): ... 11 more
You need to process the images before OCR, at least convert the image to black&white (gray scale) can enhance the result :
bitmap = toGrayscale(bitmap);
bitmap = bitmap.copy(Bitmap.Config.ARGB_8888, true);
you can user OpenCV or any Image Processing Library, for for simple task like grayscale its enopugh to use
import android.graphics.*;
public static Bitmap toGrayscale(Bitmap bmpOriginal)
{
int width, height;
height = bmpOriginal.getHeight();
width = bmpOriginal.getWidth();
Bitmap bmpGrayscale = Bitmap.createBitmap(width, height, Bitmap.Config.RGB_565);
Canvas c = new Canvas(bmpGrayscale);
Paint paint = new Paint();
ColorMatrix cm = new ColorMatrix();
cm.setSaturation(0);
ColorMatrixColorFilter f = new ColorMatrixColorFilter(cm);
paint.setColorFilter(f);
c.drawBitmap(bmpOriginal, 0, 0, paint);
return bmpGrayscale;
}
Also if the image is too large you may need to crop the image and get the area that contain the characters & numbers you want to recognize, its also make OCR engine job more easier/more accuracy and sometimes its prevents you from OutOfMemoryException.

Categories