How to solve OutOfMemory Exception when uploading image? - java

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.

Related

java.lang.IllegalArgumentException: Failed to find configured root that contains /storage/emulated/0/

EDIT:Ok I have tried the suggestions and changed it to getExternalFilesDir() and am still getting the same error. Skip to the bottom where it says "EDITED CODE" to see what it is now. I also changed it so that the screenshot will save to the pictures directory instead of creating a new directory. (END EDIT)
I have an android app that contains a recyclerview. I have created a button that will export create a PNG of the recyclerview data, save it to the device, and then send it as an attachment to the email application so it can be emailed. I'm getting the exception " java.lang.IllegalArgumentException: Failed to find configured root that contains /storage/emulated/0/ExportedFlares/FlareData.png"
Here is the code for the function that saves the bitmap to the device:
private void saveBitmap(Bitmap bitmap){
if(bitmap!=null){
try {
FileOutputStream outputStream = null;
try {
String file_path = Environment.getExternalStorageDirectory().getAbsolutePath() +
"/ExportedFlares";
File dir = new File(file_path, "FlareData");
if(!dir.exists())
dir.mkdirs();
outputStream = new FileOutputStream(dir); //here is set your file path where you want to save or also here you can set file object directly
bitmap.compress(Bitmap.CompressFormat.PNG, 100, outputStream); // bitmap is your Bitmap instance, if you want to compress it you can compress reduce percentage
// PNG is a lossless format, the compression factor (100) is ignored
} catch (Exception e) {
e.printStackTrace();
} finally {
try {
if (outputStream != null) {
outputStream.flush();
outputStream.close();
}
} catch (IOException e) {
e.printStackTrace();
}
}
} catch (Exception e) {
e.printStackTrace();
}
}
}
And here is the onClick code for when the button is tapped:
public void onClick(View v) {
saveBitmap(getScreenshotFromRecyclerView(recyclerView));
String filename = "FlareData.png";
File fileLocation = new File(Environment.getExternalStorageDirectory().getAbsolutePath() +
"/ExportedFlares", filename);
Uri path = FileProvider.getUriForFile(FlareActivity.this, BuildConfig.APPLICATION_ID + ".provider",fileLocation);
Intent emailIntent = new Intent(Intent.ACTION_SEND);
emailIntent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
emailIntent .setType("vnd.android.cursor.dir/email");
String to[] = {"email#gmail.com"};
emailIntent .putExtra(Intent.EXTRA_EMAIL, to);
emailIntent .putExtra(Intent.EXTRA_STREAM, path);
emailIntent .putExtra(Intent.EXTRA_SUBJECT, "Subject");
startActivity(Intent.createChooser(emailIntent , "Send email..."));
The final line of the following code is what is throwing the exception:
File fileLocation = new File(Environment.getExternalStorageDirectory().getAbsolutePath() +
"/ExportedFlares", filename);
Uri path = FileProvider.getUriForFile(FlareActivity.this, BuildConfig.APPLICATION_ID + ".provider",fileLocation);
Here is the XML data, I have provider_paths.xml here:
<paths xmlns:android="http://schemas.android.com/apk/res/android">
<external-files-path name="FlareData.png" path="ExportedFlares/"/>
</paths>
And this is from the manifest:
enter code here
<provider
android:name="androidx.core.content.FileProvider"
android:authorities="${applicationId}.provider"
android:exported="false"
android:grantUriPermissions="true">
<meta-data
android:name="android.support.FILE_PROVIDER_PATHS"
android:resource="#xml/provider_paths"/>
</provider>
EDITED CODE:
emailFlaresButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Context context = getApplicationContext();
saveBitmap(context, getScreenshotFromRecyclerView(recyclerView));
String filename = "FlareData.png";
File fileLocation = new File(context.getExternalFilesDir(DIRECTORY_PICTURES).getAbsolutePath()
, filename);
Uri path = FileProvider.getUriForFile(FlareActivity.this, BuildConfig.APPLICATION_ID + ".provider",fileLocation);
Intent emailIntent = new Intent(Intent.ACTION_SEND);
emailIntent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
emailIntent .setType("vnd.android.cursor.dir/email");
String to[] = {"asd#gmail.com"};
emailIntent .putExtra(Intent.EXTRA_EMAIL, to);
emailIntent .putExtra(Intent.EXTRA_STREAM, path);
emailIntent .putExtra(Intent.EXTRA_SUBJECT, "Subject");
startActivity(Intent.createChooser(emailIntent , "Send
email..."));
// Intent intent = new Intent(FlareActivity.this,
AddFlareActivity.class);
//startActivityForResult(intent, ADD_FLARE_RESULT_CODE);
}
});
And here is the piece of code that the error is pointing to (the last line) :
Uri path = FileProvider.getUriForFile(FlareActivity.this, BuildConfig.APPLICATION_ID + ".provider",fileLocation);
I have tried it with the provider path being set to both external-files-path and external-path and it doesn't affect the issue
EDIT3: Full stack trace:
E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.android.fibrnah, PID: 22052
java.lang.IllegalArgumentException: Failed to find configured root that contains /storage/emulated/0/Android/data/com.android.fibrnah/files/Pictures/FlareData.png
at androidx.core.content.FileProvider$SimplePathStrategy.getUriForFile(FileProvider.java:739)
at androidx.core.content.FileProvider.getUriForFile(FileProvider.java:418)
at com.android.fibrnah.FlareActivity$2.onClick(FlareActivity.java:84)
at android.view.View.performClick(View.java:6274)
at android.view.View$PerformClick.run(View.java:24859)
at android.os.Handler.handleCallback(Handler.java:789)
at android.os.Handler.dispatchMessage(Handler.java:98)
at android.os.Looper.loop(Looper.java:164)
at android.app.ActivityThread.main(ActivityThread.java:6710)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.Zygote$MethodAndArgsCaller.run(Zygote.java:240)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:770)
Change external-files-path to external-path.
Or, put your files in getExternalFilesDir() (called on a Context). This is the better solution, as your current code will not work on Android Q (by default) and Android R+ (for all apps).

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();
}
});
}

Android Error while Uploading an image to server

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.

Dividing video into parts on Android

I am trying to send a video to an asp.net server on android. However, since the video size is about 26 MB I am not able to send the video? Is there a way to divide the video into parts and send them to the .net server via android by using java?
import java.io.DataOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import android.app.Activity;
import android.content.Intent;
import android.database.Cursor;
import android.net.Uri;
import android.os.Bundle;
import android.provider.MediaStore;
import android.util.Log;
public class VideoUploader extends Activity
{
/** Called when the activity is first created. */
public static final int SELECT_VIDEO=1;
public static final String TAG="UploadActivity";
String path="";
#Override
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
openGaleryVideo();
}
public void openGaleryVideo()
{
Intent intent=new Intent();
intent.setType("video/*");
intent.setAction(Intent.ACTION_GET_CONTENT);
startActivityForResult(Intent.createChooser(intent, "Select Video"),SELECT_VIDEO);
}
#Override
public void onActivityResult(int requestCode, int resultCode, Intent data)
{
super.onActivityResult(requestCode, resultCode, data);
if (resultCode == RESULT_OK) {
if (requestCode == SELECT_VIDEO) {
Uri videoUri = data.getData();
path= getPath(videoUri);
doFileUpload();
}
}
}
public String getPath(Uri uri)
{
String[] projection = { MediaStore.Video.Media.DATA};
Cursor cursor = managedQuery(uri, projection, null, null, null);
int column_index = cursor.getColumnIndexOrThrow(MediaStore.Video.Media.DATA);
cursor.moveToFirst();
return cursor.getString(column_index);
}
public void doFileUpload()
{
String pathToOurFile = path;//this will be the file path
String urlServer = "http://192.168.10.177/androidweb/default.aspx";
int bytesRead, bytesAvailable, bufferSize;
byte[] buffer;
int maxBufferSize = 2*1024* 1024;
try
{
FileInputStream fileInputStream = new FileInputStream(new File(pathToOurFile));
URL url = new URL(urlServer);
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
// Allow Inputs & Outputs
connection.setDoInput(true);
connection.setDoOutput(true);
connection.setUseCaches(false);
// Enable POST method
connection.setRequestMethod("POST");
connection.setRequestProperty("Connection", "Keep-Alive");
connection.setRequestProperty("Content-Type", "multipart/form-data");
connection.setRequestProperty("SD-FileName", "Chrysanthemum.JPEG");
DataOutputStream outputStream = new DataOutputStream(connection.getOutputStream());
bytesAvailable = fileInputStream.available();
bufferSize = Math.min(bytesAvailable, maxBufferSize);
buffer = new byte[bufferSize];
// Read file
bytesRead = fileInputStream.read(buffer, 0, bufferSize);
while (bytesRead > 0)
{
outputStream.write(buffer, 0, bufferSize);
bytesAvailable = fileInputStream.available();
bufferSize = Math.min(bytesAvailable, maxBufferSize);
bytesRead = fileInputStream.read(buffer, 0, bufferSize);
}//end of while statement
int serverResponseCode = connection.getResponseCode();
String serverResponseMessage = connection.getResponseMessage();
Log.d("ServerCode",""+serverResponseCode);
Log.d("serverResponseMessage",""+serverResponseMessage);
fileInputStream.close();
outputStream.flush();
outputStream.close();
}//end of try body
catch (Exception ex)
{
//ex.printStackTrace();
Log.e("Error: ", ex.getMessage());
}
}
}
First, if the video doesn't need to be playable until re-assembled, just send so many bytes in each piece and have the server re-assemble it. The rest of this will assume that you need to divide it into a number of videos which can be played individually.
You might look at the video editing example in the ICS, though depending on how it is implement that might confine you to the latest devices.
Otherwise:
Most compressed video formats can be thought of as a repeating sequence of absolute information (keyframe) followed by relative information for frames encoded relative to that base. If you learn about the details of the unspecified format you are using, you can probably learn how to identify a place near the size where you wish to cut where a new section begins with a full key frame. You would split the video there, creating any necessary file header in the new part, and adjusting any length information in the original header.
While doing this yourself would be educational, it would also be worth looking for existing solutions.

Categories