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)
Related
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();
}
});
}
I am able to upload to the server the image of file size less than probably 1Mb and will get the OutOfMemory error if i upload more than 1Mb. I have used the BitmapFactory to decode the file but still unable to upload large image files.
12-15 22:33:51.465: E/AndroidRuntime(11968): java.lang.OutOfMemoryError
12-15 22:33:51.465: E/AndroidRuntime(11968): at android.graphics.BitmapFactory.nativeDecodeStream(Native Method)
12-15 22:33:51.465: E/AndroidRuntime(11968): at android.graphics.BitmapFactory.decodeStream(BitmapFactory.java:652)
12-15 22:33:51.465: E/AndroidRuntime(11968): at android.graphics.BitmapFactory.decodeFile(BitmapFactory.java:391)
12-15 22:33:51.465: E/AndroidRuntime(11968): at android.graphics.BitmapFactory.decodeFile(BitmapFactory.java:451)
12-15 22:33:51.465: E/AndroidRuntime(11968): at sp.com.NewProductActivity.onActivityResult(NewProductActivity.java:137)
12-15 22:33:51.465: E/AndroidRuntime(11968): at android.app.Activity.dispatchActivityResult(Activity.java:5390)
12-15 22:33:51.465: E/AndroidRuntime(11968): at android.app.ActivityThread.deliverResults(ActivityThread.java:3201)
12-15 22:33:51.465: E/AndroidRuntime(11968): at android.app.ActivityThread.handleSendResult(ActivityThread.java:3248)
12-15 22:33:51.465: E/AndroidRuntime(11968): at android.app.ActivityThread.access$1200(ActivityThread.java:140)
12-15 22:33:51.465: E/AndroidRuntime(11968): at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1285)
12-15 22:33:51.465: E/AndroidRuntime(11968): at android.os.Handler.dispatchMessage(Handler.java:99)
12-15 22:33:51.465: E/AndroidRuntime(11968): at android.os.Looper.loop(Looper.java:137)
12-15 22:33:51.465: E/AndroidRuntime(11968): at android.app.ActivityThread.main(ActivityThread.java:4921)
12-15 22:33:51.465: E/AndroidRuntime(11968): at java.lang.reflect.Method.invokeNative(Native Method)
12-15 22:33:51.465: E/AndroidRuntime(11968): at java.lang.reflect.Method.invoke(Method.java:511)
12-15 22:33:51.465: E/AndroidRuntime(11968): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1027)
12-15 22:33:51.465: E/AndroidRuntime(11968): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:794)
12-15 22:33:51.465: E/AndroidRuntime(11968): at dalvik.system.NativeStart.main(Native Method)
NewProductActivity.java
public int uploadFile(final 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 {
// Edit Text
inputName = (EditText) findViewById(R.id.inputName);
inputLocation = (EditText) findViewById(R.id.inputLocation);
inputDesc = (EditText) findViewById(R.id.inputDesc);
//Radio Button
reportTypeGroup = (RadioGroup) findViewById(R.id.typeOfReport);
reportType = "";
switch (reportTypeGroup.getCheckedRadioButtonId()) {
case R.id.hazard:
reportType = "Hazard";
break;
case R.id.incident:
reportType = "Incident";
break;
default:
reportType = "Unknown";
break;
}
FileInputStream fileInputStream = new FileInputStream(sourceFile);
URL url = new URL(upLoadServerUri);
conn = (HttpURLConnection) url.openConnection();
conn.setDoInput(true); // Allow Inputs
conn.setDoOutput(true); // Allow Outputs
conn.setUseCaches(false); // Don't use a Cached Copy
// conn.setChunkedStreamingMode(1024);
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);
//Adding Parameters
dos = new DataOutputStream(conn.getOutputStream());
dos.writeBytes(twoHyphens + boundary + lineEnd);
dos.writeBytes("Content-Disposition: form-data; name=\"name\""
+ lineEnd);
dos.writeBytes(lineEnd);
dos.writeBytes(inputName.getText().toString());
dos.writeBytes(lineEnd);
dos.writeBytes(twoHyphens + boundary + lineEnd);
dos.writeBytes("Content-Disposition: form-data; name=location"
+ lineEnd);
dos.writeBytes(lineEnd);
dos.writeBytes(inputLocation.getText().toString());
dos.writeBytes(lineEnd);
dos.writeBytes(twoHyphens + boundary + lineEnd);
dos.writeBytes("Content-Disposition: form-data; name=description"
+ lineEnd);
dos.writeBytes(lineEnd);
dos.writeBytes(inputDesc.getText().toString());
dos.writeBytes(lineEnd);
dos.writeBytes(twoHyphens + boundary + lineEnd);
dos.writeBytes("Content-Disposition: form-data; name=type"
+ lineEnd);
dos.writeBytes(lineEnd);
dos.writeBytes(reportType.toString());
dos.writeBytes(lineEnd);
//Adding Parameter media file(audio,video and image)
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);
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"
+ "c:/wamp/www/echo/uploads";
messageText.setText(msg);
Toast.makeText(NewProductActivity.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(NewProductActivity.this,
"MalformedURLException", Toast.LENGTH_SHORT)
.show();
}
});
Log.e("Upload file to server", "error: " + ex.getMessage(), ex);
} catch (final Exception e) {
dialog.dismiss();
e.printStackTrace();
runOnUiThread(new Runnable() {
public void run() {
messageText.setText("Got Exception : "+e.toString());
Toast.makeText(NewProductActivity.this,
"Got Exception : see logcat ",
Toast.LENGTH_SHORT).show();
}
});
Log.e("Upload file to server Exception",
"Exception : " + e.getMessage(), e);
}
dialog.dismiss();
return serverResponseCode;
}
}
}
-------EDIT--------
After adding the below code, I do not get anymore OutOfMemory exception and it says "upload successful", but nothing was uploaded.
final BitmapFactory.Options options = new BitmapFactory.Options();
options.inSampleSize = 8;
Bitmap bm = BitmapFactory.decodeFile(strPath,options);
imageView.setImageBitmap(bm);
1. for out of memory error add below line to your Manifest file inside <application> tag-
`<application
...
android:largeHeap="true"
</application>`
2. Your way of programming is totally wrong for layout initialization like
inputName = (EditText) findViewById(R.id.inputName);
inputLocation = (EditText) findViewById(R.id.inputLocation);
inputDesc = (EditText) findViewById(R.id.inputDesc);
this should be in onCreate(Bundle arg0) for best practice
and one more for image uploading like process you have to use AsyncTask for ex : How can I use an Async Task to upload File and Resize your bitmap file to avoid such errors
3.for large image problem you have to change setting of php server.
by default http request allow to upload data upto 2 mb on a php server.if you want to increase upload limit then go to your php config file and set upload limit to what ever you want.
Use AsyncTask for uploading the image.. Because you cannot do upload and download task on the UI thread.
You need to resize bitmap to solve this problem but before that just try one thing, add largeHeap = true tag in Android manifest's application tag.
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.
It reads image from the channel and write it to card. the image in card is completely written and is fine. The only problem is thread in hanged and does not execute any line after that loop.
protected Bitmap doInBackground(String... arg0) {
// TODO Auto-generated method stub'
// Runtime.getRuntime().availableProcessors();
System.out.println("Inside doinback"+ RemoteScreen.out.toString());
try {
RemoteScreen.out.write(210);
//Home.threadloop = false;
Bitmap bitmap = null;
String baseDir = Environment.getExternalStorageDirectory().getAbsolutePath();
String fileName = "a.png";
String imageInSD = baseDir + File.separator + fileName;
System.out.println(imageInSD);
if (is!= null) {
FileOutputStream fos = null;
BufferedOutputStream bos = null;
try {
// Log.i("IMSERVICE", "FILERECCC-1");
//ContextWrapper context = null;
fos = new FileOutputStream(imageInSD);
bos = new BufferedOutputStream(fos);
byte[] aByte = new byte[1024];
int bytesRead;
//thread stuck in this loop and does not move forward
while ( (bytesRead = is.read(aByte)) > 0 ) {
if (bytesRead == 1)
break;
bos.write(aByte, 0, bytesRead);
System.out.println("Loop"+aByte);
}
bos.close();
Log.i("IMSERVICE", "out of loop");
java.io.FileInputStream in = new FileInputStream(imageInSD);
bitmap = BitmapFactory.decodeStream(in);
bitmap = BitmapFactory.decodeFile(imageInSD);
Log.i("IMSERVICE", "saved");
if (bitmap != null)
System.out.println(bitmap.toString());
} catch (IOException ex) {
// Do exception handling
// Log.i("IMSERVICE", "exception ");
}
}
publishProgress(b);
b = null;
ch = 4646;
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return null;
}
log trace shows following error.
05-10 20:34:42.715: E/AndroidRuntime(1135): FATAL EXCEPTION: AsyncTask #3
05-10 20:34:42.715: E/AndroidRuntime(1135): java.lang.RuntimeException: An error occured while executing doInBackground()
05-10 20:34:42.715: E/AndroidRuntime(1135): at android.os.AsyncTask$3.done(AsyncTask.java:299)
05-10 20:34:42.715: E/AndroidRuntime(1135): at java.util.concurrent.FutureTask.finishCompletion(FutureTask.java:352)
05-10 20:34:42.715: E/AndroidRuntime(1135): at java.util.concurrent.FutureTask.setException(FutureTask.java:219)
05-10 20:34:42.715: E/AndroidRuntime(1135): at java.util.concurrent.FutureTask.run(FutureTask.java:239)
05-10 20:34:42.715: E/AndroidRuntime(1135): at android.os.AsyncTask$SerialExecutor$1.run(AsyncTask.java:230)
05-10 20:34:42.715: E/AndroidRuntime(1135): at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1080)
05-10 20:34:42.715: E/AndroidRuntime(1135): at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:573)
05-10 20:34:42.715: E/AndroidRuntime(1135): at java.lang.Thread.run(Thread.java:856)
05-10 20:34:42.715: E/AndroidRuntime(1135): Caused by: java.lang.NullPointerException
05-10 20:34:42.715: E/AndroidRuntime(1135): at com.rms.remotedesktop1.screencahnge.doInBackground(screencahnge.java:43)
05-10 20:34:42.715: E/AndroidRuntime(1135): at com.rms.remotedesktop1.screencahnge.doInBackground(screencahnge.java:1)
05-10 20:34:42.715: E/AndroidRuntime(1135): at android.os.AsyncTask$2.call(AsyncTask.java:287)
05-10 20:34:42.715: E/AndroidRuntime(1135): at java.util.concurrent.FutureTask.run(FutureTask.java:234)
According to the logcat, the code is crashing at line 43 with a Null Pointer Exception, and I can't tell which line 43 is. However:
Have you checked that Environment.getExternalStorageDirectory().getAbsolutePath() is returning non null? It maybe that there is no external storage directory, or you don't have permission to know about it.
It is also worth reading the developer pages, http://developer.android.com/reference/android/os/Environment.html#getExternalStorageDirectory(), which note that you shouldn't write to that directory, which you seem to be doing.
I solved this problem by myself. There was error in static variable who was changing his value due to logical error in code.
I use the following code to copy a directory and some files to sdcard. The directory I copy is placed in the assets folder.
public class CopyAssets extends Activity{
Button btn;
File sdCard = Environment.getExternalStorageDirectory();
private CameraBaseActivity mCamBase;
protected static String copyStatus;
CopyAssets(String path){
//copyFileOrDir(path);
copyStatus = "loading";
mCamBase = CameraBaseActivity.getInstance();
if(isSdPresent())
new MoveDir().execute(path);
}
private class MoveDir extends AsyncTask<String, Void, String> {
#Override
protected String doInBackground(String... params) {
copyStatus = "loaded";
copyFileOrDir("edu.cmu.pocketsphinx");
return (copyStatus);
}
#Override
protected void onPostExecute(String result) {
//TextView txt = (TextView) findViewById(R.id.output);
//txt.setText("Executed"); // txt.setText(result);
// might want to change "executed" for the returned string passed
// into onPostExecute() but that is upto you
mCamBase.initARParams();
}
#Override
protected void onPreExecute() {
}
#Override
protected void onProgressUpdate(Void... values) {
}
}
private void copyFileOrDir(String path) {
AssetManager assetManager = this.getAssets();
String assets[] = null;
try {
assets = assetManager.list(path);
if (assets.length == 0) {
copyFile(path);
} else {
File dir = new File(sdCard.getAbsolutePath() + "/" + path);
if (!dir.exists()) {
System.out.println("Created directory"
+ sdCard.getAbsolutePath());
boolean result = dir.mkdir();
System.out.println("Result of directory creation" + result);
}
for (int i = 0; i < assets.length; ++i) {
copyFileOrDir(path + "/" + assets[i]);
}
}
} catch (IOException ex) {
System.out.println("Exception in copyFileOrDir" + ex);
}
}
private void copyFile(String filename) {
AssetManager assetManager = this.getAssets();
InputStream in = null;
OutputStream out = null;
try {
in = assetManager.open(filename);
// String newFileName = "/data/data/" + this.getPackageName() + "/"
// + filename;//path for storing internally to data/data
String newFileName = sdCard.getAbsolutePath() + "/" + filename;
out = new FileOutputStream(newFileName);
byte[] buffer = new byte[1024];
int read;
while ((read = in.read(buffer)) != -1) {
out.write(buffer, 0, read);
}
in.close();
in = null;
out.flush();
out.close();
out = null;
System.out.println("File created in path" + newFileName);
} catch (Exception e) {
System.out.println("Exception in copyFile" + e);
// System.out.println("Exception in copyFile"+e.print);
// Log.e("tag", e.printStackTrace());
}
}
public static boolean isSdPresent() {
return android.os.Environment.getExternalStorageState().equals(android.os.Environment.MEDIA_MOUNTED);
}
}
Exception is in doinbackground:
01-01 00:00:41.679: WARN/dalvikvm(1530): threadid=11: thread exiting with uncaught exception (group=0x40b3d1f8)
01-01 00:00:41.687: ERROR/CameraBaseActivity(1530): uncaughtException.
01-01 00:00:41.695: ERROR/CameraBaseActivity(1530): at android.os.AsyncTask$3.done(AsyncTask.java:278)
01-01 00:00:41.695: ERROR/CameraBaseActivity(1530): at java.util.concurrent.FutureTask$Sync.innerSetException(FutureTask.java:273)
01-01 00:00:41.695: ERROR/CameraBaseActivity(1530): at java.util.concurrent.FutureTask.setException(FutureTask.java:124)
01-01 00:00:41.703: ERROR/CameraBaseActivity(1530): at java.util.concurrent.FutureTask$Sync.innerRun(FutureTask.java:307)
01-01 00:00:41.703: INFO/ActivityManager(292): Start proc com.test.android.imageplugin for service com.test.android.imageplugin/.ImagePluginServer: pid=1549 uid=6062 gids={1015, 1023}
01-01 00:00:41.710: ERROR/LL_Core(1530): [LifeLogSecurityUtility]lifelogdb permission error
01-01 00:00:41.710: ERROR/CameraBaseActivity(1530): at java.util.concurrent.FutureTask.run(FutureTask.java:137)
01-01 00:00:41.710: ERROR/CameraBaseActivity(1530): at android.os.AsyncTask$SerialExecutor$1.run(AsyncTask.java:208)
01-01 00:00:41.710: ERROR/CameraBaseActivity(1530): at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1076)
01-01 00:00:41.710: ERROR/CameraBaseActivity(1530): at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:569)
01-01 00:00:41.710: ERROR/CameraBaseActivity(1530): at java.lang.Thread.run(Thread.java:856)
01-01 00:00:41.710: ERROR/CameraBaseActivity(1530): java.lang.RuntimeException: An error occured while executing doInBackground()
01-01 00:00:41.710: ERROR/CameraBaseActivity(1530): uncaughtException.
01-01 00:00:41.710: ERROR/CameraBaseActivity(1530): uncaughtException : other thread.
01-01 00:00:41.710: ERROR/CameraBaseActivity(1530): LLDB regist error. unregisted.
01-01 00:00:41.710: DEBUG/Camera(1530): Capture get() mIsExecuteRegistMenu=false
01-01 00:00:41.710: DEBUG/Camera(1530): onResumeImpl start
01-01 00:00:41.710: DEBUG/Camera(1530): execDisplayLayoutChangeNonSync start rotation:0
01-01 00:00:41.726: DEBUG/Camera(1530): onResumeImpl end
01-01 00:00:41.726: INFO/CameraBaseActivity(1530): onResume end
01-01 00:00:41.726: INFO/CameraBaseActivity(1530): onPostResume
01-01 00:00:41.890: INFO/CameraBaseActivity(1530): Camera.finish
I cannot find why it crashes unexpectedly in doinbackground as I cannot see any error with my code I posted here.Any help is much appreciated.
what is LifeLogSecurityUtility?
It is possible this line:
[LifeLogSecurityUtility]lifelogdb permission error
is telling you that you are missing a permission tag in your manifest. Though I am not familiar with this LifeLogSecurityUtility so I wouldn't know which permission that thing is wanting you to have.
If you have not done so already add the WRITE_EXTERNAL_STORAGE permission to your AndroidManifest.xml
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />