Upload file to server using android - java

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

Related

android video mp4 upload to php server

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

to insert android data into mysql

I'm working on register and login activity.
when I type the name, username, and password, the informations accessed android application.
and the Toast show the 'Registration Success' message.
But the data didn't inserted in mysql DB.
How can I solve it? Please help me.
Following is LoginActivity.java
public class LoginActivity extends Activity {
EditText ET_NAME,ET_PASS;
String login_name,login_pass;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.login_main);
ET_NAME = (EditText)findViewById(R.id.user_name);
ET_PASS = (EditText)findViewById(R.id.user_pass);
}
public void userReg(View view)
{
startActivity(new Intent(this,RegisterActivity.class));
}
public void userLogin(View view)
{
login_name = ET_NAME.getText().toString();
login_pass = ET_PASS.getText().toString();
String method = "login";
BackgroundTask backgroundTask = new BackgroundTask(this);
backgroundTask.execute(method,login_name,login_pass);
Intent intent = new Intent(this, MainActivity.class);
intent.putExtra("ID", login_name);
intent.putExtra("PW", login_pass);
startActivity(intent);
finish();
}
}
This is BackgroundTask.java
public class BackgroundTask extends AsyncTask<String,Void,String> {
AlertDialog alertDialog;
Context ctx;
BackgroundTask(Context ctx) {
this.ctx = ctx;
}
#Override
protected void onPreExecute() {
alertDialog = new AlertDialog.Builder(ctx).create();
}
#Override
protected String doInBackground(String... params) {
String reg_url = "http://35.160.135.119/webapp/register.php";
String login_url = "http://35.160.135.119/webapp/login.php";
String method = params[0];
if (method.equals("register")) {
String name = params[1];
String user_name = params[2];
String user_pass = params[3];
try {
URL url = new URL(reg_url)
HttpURLConnection httpURLConnection = (HttpURLConnection) url.openConnection();
httpURLConnection.setRequestMethod("POST");
httpURLConnection.setDoOutput(true);
//httpURLConnection.setDoInput(true);
OutputStream OS = httpURLConnection.getOutputStream();
BufferedWriter bufferedWriter = new BufferedWriter(new OutputStreamWriter(OS, "UTF-8"));
String data = URLEncoder.encode("name", "UTF-8") + "=" + URLEncoder.encode(name, "UTF-8") + "&" +
URLEncoder.encode("user_name", "UTF-8") + "=" + URLEncoder.encode(user_name, "UTF-8") + "&" +
URLEncoder.encode("user_pass", "UTF-8") + "=" + URLEncoder.encode(user_pass, "UTF-8");
bufferedWriter.write(data);
bufferedWriter.flush();
bufferedWriter.close();
OS.close();
InputStream IS = httpURLConnection.getInputStream();
IS.close();
//httpURLConnection.connect();
httpURLConnection.disconnect();
return "Registration Success...";
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
} else if (method.equals("login")) {
String login_name = params[1];
String login_pass = params[2];
try {
URL url = new URL(login_url);
HttpURLConnection httpURLConnection = (HttpURLConnection) url.openConnection();
httpURLConnection.setRequestMethod("POST");
httpURLConnection.setDoOutput(true);
httpURLConnection.setDoInput(true);
OutputStream outputStream = httpURLConnection.getOutputStream();
BufferedWriter bufferedWriter = new BufferedWriter(new OutputStreamWriter(outputStream, "UTF-8"));
String data = URLEncoder.encode("login_name", "UTF-8") + "=" + URLEncoder.encode(login_name, "UTF-8") + "&" +
URLEncoder.encode("login_pass", "UTF-8") + "=" + URLEncoder.encode(login_pass, "UTF-8");
bufferedWriter.write(data);
bufferedWriter.flush();
bufferedWriter.close();
outputStream.close();
InputStream inputStream = httpURLConnection.getInputStream();
BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(inputStream, "iso-8859-1"));
String response = "";
String line = "";
while ((line = bufferedReader.readLine()) != null) {
response += line;
}
bufferedReader.close();
inputStream.close();
httpURLConnection.disconnect();
return response;
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
return null;
}
#Override
protected void onProgressUpdate(Void... values) {
super.onProgressUpdate(values);
}
#Override
protected void onPostExecute(String result) {
if (result.equals("Registration Success...")) {
Toast.makeText(ctx, result, Toast.LENGTH_LONG).show();
} else {
alertDialog.setMessage(result);
alertDialog.show();
}
}
}
And this is Register.java
public class RegisterActivity extends Activity {
EditText ET_NAME, ET_USER_NAME, ET_USER_PASS;
String name, user_name, user_pass;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.register_layout);
ET_NAME = (EditText)findViewById(R.id.name);
ET_USER_NAME = (EditText)findViewById(R.id.new_user_name);
ET_USER_PASS = (EditText)findViewById(R.id.new_user_pass);
}
public void userReg(View view)
{
name = ET_NAME.getText().toString();
user_name = ET_USER_NAME.getText().toString();
user_pass = ET_USER_PASS.getText().toString();
String method = "register";
BackgroundTask backgroundTask = new BackgroundTask(this);
backgroundTask.execute(method,name, user_name, user_pass);
finish();
}
}
This is debugging log.
$ adb shell am start -n "com.example.jina.a1105gmdemo/com.example.jina.a1105gmdemo.LoginActivity" -a android.intent.action.MAIN -c android.intent.category.LAUNCHER -D
Connecting to com.example.jina.a1105gmdemo
Connected to the target VM, address: 'localhost:8605', transport: 'socket'
I/System.out: Sending WAIT chunk
W/ActivityThread: Application com.example.jina.a1105gmdemo is waiting for the debugger on port 8100...
I/dalvikvm: Debugger is active
I/System.out: Debugger has connected
I/System.out: waiting for debugger to settle...
I/System.out: waiting for debugger to settle...
I/System.out: waiting for debugger to settle...
I/System.out: waiting for debugger to settle...
I/System.out: waiting for debugger to settle...
I/System.out: waiting for debugger to settle...
I/System.out: debugger has settled (1484)
I/MultiDex: VM with version 1.6.0 does not have multidex support
I/MultiDex: install
I/MultiDex: MultiDexExtractor.load(/data/app/com.example.jina.a1105gmdemo-46.apk, false)
I/MultiDex: Detected that extraction must be performed.
I/MultiDex: Trying to delete old file /data/data/com.example.jina.a1105gmdemo/code_cache/secondary-dexes/com.example.jina.a1105gmdemo-45.apk.classes2.dex of size 2898496
I/MultiDex: Deleted old file /data/data/com.example.jina.a1105gmdemo/code_cache/secondary-dexes/com.example.jina.a1105gmdemo-45.apk.classes2.dex
I/MultiDex: Trying to delete old file /data/data/com.example.jina.a1105gmdemo/code_cache/secondary-dexes/com.example.jina.a1105gmdemo-45.apk.classes2.zip of size 934986
I/MultiDex: Deleted old file /data/data/com.example.jina.a1105gmdemo/code_cache/secondary-dexes/com.example.jina.a1105gmdemo-45.apk.classes2.zip
I/MultiDex: Extraction is needed for file /data/data/com.example.jina.a1105gmdemo/code_cache/secondary-dexes/com.example.jina.a1105gmdemo-46.apk.classes2.zip
I/MultiDex: Extracting /data/data/com.example.jina.a1105gmdemo/code_cache/secondary-dexes/com.example.jina.a1105gmdemo-46.apk.classes2089171779.zip
I/MultiDex: Renaming to /data/data/com.example.jina.a1105gmdemo/code_cache/secondary-dexes/com.example.jina.a1105gmdemo-46.apk.classes2.zip
I/MultiDex: Extraction success - length /data/data/com.example.jina.a1105gmdemo/code_cache/secondary-dexes/com.example.jina.a1105gmdemo-46.apk.classes2.zip: 934986
I/MultiDex: load found 1 secondary dex files
D/dalvikvm: DexOpt: --- BEGIN 'com.example.jina.a1105gmdemo-46.apk.classes2.zip' (bootstrap=0) ---
D/dalvikvm: DexOpt: --- END 'com.example.jina.a1105gmdemo-46.apk.classes2.zip' (success) ---
D/dalvikvm: DEX prep '/data/data/com.example.jina.a1105gmdemo/code_cache/secondary-dexes/com.example.jina.a1105gmdemo-46.apk.classes2.zip': unzip in 66ms, rewrite 778ms
I/MultiDex: install done
I/FirebaseInitProvider: FirebaseApp initialization unsuccessful
I/Adreno-EGL: <qeglDrvAPI_eglInitialize:410>: EGL 1.4 QUALCOMM build: ()
OpenGL ES Shader Compiler Version: E031.24.00.08
Build Date: 03/21/14 Fri
Local Branch: AU200+patches_03212014
Remote Branch:
Local Patches:
Reconstruct Branch:
D/OpenGLRenderer: Enabling debug mode 0
D/OpenGLRenderer: GL error from OpenGLRenderer: 0x502
E/OpenGLRenderer: GL_INVALID_OPERATION
D/OpenGLRenderer: GL error from OpenGLRenderer: 0x502
E/OpenGLRenderer: GL_INVALID_OPERATION
D/dalvikvm: threadid=1: still suspended after undo (sc=1 dc=1)
D/dalvikvm: threadid=12: still suspended after undo (sc=1 dc=1)
D/dalvikvm: threadid=12: still suspended after undo (sc=1 dc=1)
D/dalvikvm: threadid=12: still suspended after undo (sc=1 dc=1)
D/dalvikvm: threadid=12: still suspended after undo (sc=1 dc=1)
D/dalvikvm: threadid=12: still suspended after undo (sc=1 dc=1)
D/dalvikvm: threadid=12: still suspended after undo (sc=1 dc=1)
D/dalvikvm: threadid=12: still suspended after undo (sc=1 dc=1)
D/dalvikvm: threadid=12: still suspended after undo (sc=1 dc=1)
I/System.out: Thread-1263(HTTPLog):isShipBuild true
I/System.out: Thread-1263(HTTPLog):SmartBonding Enabling is false, SHIP_BUILD is true, log to file is false, DBG is false
W/IInputConnectionWrapper: getTextBeforeCursor on inactive InputConnection
W/IInputConnectionWrapper: getSelectedText on inactive InputConnection
W/IInputConnectionWrapper: getTextBeforeCursor on inactive InputConnection
W/IInputConnectionWrapper: getTextAfterCursor on inactive InputConnection
W/IInputConnectionWrapper: getSelectedText on inactive InputConnection
W/IInputConnectionWrapper: getTextBeforeCursor on inactive InputConnection
W/IInputConnectionWrapper: getTextAfterCursor on inactive InputConnection
D/dalvikvm: threadid=12: still suspended after undo (sc=1 dc=1)
D/dalvikvm: threadid=1: still suspended after undo (sc=1 dc=1)
Disconnected from the target VM, address: 'localhost:8605', transport: 'socket'
put that code in post execute of async task that you want to execute after the async task complete.like..
finish();
and check your webservices for data that you recieved there and try to print the result in logcat what you got from your server script instead of static "success message".

How to solve OutOfMemory Exception when uploading image?

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.

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.

what the error in this code to get json data? [duplicate]

This question already has answers here:
How can I fix 'android.os.NetworkOnMainThreadException'?
(66 answers)
android.os.NetworkOnMainThreadException . Need to use async task?
(2 answers)
Closed 9 years ago.
What is the error in this code?
I would like to add a facebook page name and get its json data, but there is something error I cannot discover. These are all files I use and added logcat messages:
PagesActivity.java
package com.engahmedphp.facebookcollector;
import org.json.JSONException;
import org.json.JSONObject;
import android.os.Bundle;
import android.app.Activity;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.view.Menu;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
public class PagesActivity extends Activity {
DatabaseHandler db = new DatabaseHandler(this);
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_pages);
final Button button = (Button) findViewById(R.id.addPage);
button.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
AlertDialog.Builder alert = new AlertDialog.Builder(
PagesActivity.this);
alert.setTitle("Add New Page");
alert.setMessage("Enter Page Name OR Valid Facebook Link");
// Set an EditText view to get user input
final EditText input = new EditText(PagesActivity.this);
alert.setView(input);
alert.setPositiveButton("Ok",
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog,
int whichButton) {
String value = input.getText().toString();
// Do something with value!
String url = "http://graph.facebook.com/"
+ value + "/?fields=picture,name";
// Creating JSON Parser instance
JSONParser jParser = new JSONParser();
// getting JSON string from URL
JSONObject json = jParser.getJSONFromUrl(url);
try {
// Storing each json item in variable
String name = json.getString("name");
String fid = json.getString("id");
String picture = json
.getJSONObject("picture")
.getJSONObject("data")
.getString("url");
db.addPage(name, fid, picture);
} catch (JSONException e) {
e.printStackTrace();
}
// addPageData(value);
}
});
alert.setNegativeButton("Cancel",
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog,
int whichButton) {
// Canceled.
}
});
alert.show();
}
});
}
void addPageData(String pageName) {
String url = "http://graph.facebook.com/" + pageName
+ "/?fields=picture,name";
// Creating JSON Parser instance
JSONParser jParser = new JSONParser();
// getting JSON string from URL
JSONObject json = jParser.getJSONFromUrl(url);
try {
// Storing each json item in variable
String name = json.getString("name");
String fid = json.getString("id");
String picture = json.getJSONObject("picture")
.getJSONObject("data").getString("url");
db.addPage(name, fid, picture);
} catch (JSONException e) {
e.printStackTrace();
}
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.splash, menu);
return true;
}
}
JSONParser.java
package com.engahmedphp.facebookcollector;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.UnsupportedEncodingException;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.json.JSONException;
import org.json.JSONObject;
import android.util.Log;
public class JSONParser {
static InputStream is = null;
static JSONObject jObj = null;
static String json = "";
// constructor
public JSONParser() {
}
public JSONObject getJSONFromUrl(String url) {
// Making HTTP request
try {
// defaultHttpClient
DefaultHttpClient httpClient = new DefaultHttpClient();
HttpPost httpPost = new HttpPost(url);
HttpResponse httpResponse = httpClient.execute(httpPost);
HttpEntity httpEntity = httpResponse.getEntity();
is = httpEntity.getContent();
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
try {
BufferedReader reader = new BufferedReader(new InputStreamReader(
is, "iso-8859-1"), 8);
StringBuilder sb = new StringBuilder();
String line = null;
while ((line = reader.readLine()) != null) {
sb.append(line + "\n");
}
is.close();
json = sb.toString();
} catch (Exception e) {
Log.e("Buffer Error", "Error converting result " + e.toString());
}
// try parse the string to a JSON object
try {
jObj = new JSONObject(json);
} catch (JSONException e) {
Log.e("JSON Parser", "Error parsing data " + e.toString());
}
// return JSON String
return jObj;
}
}
LogCat
08-31 03:35:23.031: D/dalvikvm(15972): GC_FOR_ALLOC freed 39K, 6% free 2633K/2792K, paused 65ms, total 68ms
08-31 03:35:23.041: I/dalvikvm-heap(15972): Grow heap (frag case) to 3.767MB for 1136500-byte allocation
08-31 03:35:23.163: D/dalvikvm(15972): GC_FOR_ALLOC freed 2K, 5% free 3740K/3904K, paused 116ms, total 116ms
08-31 03:35:23.511: D/gralloc_goldfish(15972): Emulator without GPU emulation detected.
08-31 03:35:26.611: I/Choreographer(15972): Skipped 30 frames! The application may be doing too much work on its main thread.
08-31 03:39:40.903: D/dalvikvm(15972): GC_FOR_ALLOC freed 47K, 4% free 4013K/4180K, paused 48ms, total 81ms
08-31 03:39:40.903: I/dalvikvm-heap(15972): Grow heap (frag case) to 4.638MB for 635812-byte allocation
08-31 03:39:41.023: D/dalvikvm(15972): GC_FOR_ALLOC freed 2K, 4% free 4631K/4804K, paused 111ms, total 111ms
08-31 03:39:41.483: I/Choreographer(15972): Skipped 83 frames! The application may be doing too much work on its main thread.
08-31 03:39:48.701: D/AndroidRuntime(15972): Shutting down VM
08-31 03:39:48.701: W/dalvikvm(15972): threadid=1: thread exiting with uncaught exception (group=0x414c4700)
08-31 03:39:48.741: E/AndroidRuntime(15972): FATAL EXCEPTION: main
08-31 03:39:48.741: E/AndroidRuntime(15972): android.os.NetworkOnMainThreadException
08-31 03:39:48.741: E/AndroidRuntime(15972): at android.os.StrictMode$AndroidBlockGuardPolicy.onNetwork(StrictMode.java:1133)
08-31 03:39:48.741: E/AndroidRuntime(15972): at java.net.InetAddress.lookupHostByName(InetAddress.java:385)
08-31 03:39:48.741: E/AndroidRuntime(15972): at java.net.InetAddress.getAllByNameImpl(InetAddress.java:236)
08-31 03:39:48.741: E/AndroidRuntime(15972): at java.net.InetAddress.getAllByName(InetAddress.java:214)
08-31 03:39:48.741: E/AndroidRuntime(15972): at org.apache.http.impl.conn.DefaultClientConnectionOperator.openConnection(DefaultClientConnectionOperator.java:137)
08-31 03:39:48.741: E/AndroidRuntime(15972): at org.apache.http.impl.conn.AbstractPoolEntry.open(AbstractPoolEntry.java:164)
08-31 03:39:48.741: E/AndroidRuntime(15972): at org.apache.http.impl.conn.AbstractPooledConnAdapter.open(AbstractPooledConnAdapter.java:119)
08-31 03:39:48.741: E/AndroidRuntime(15972): at org.apache.http.impl.client.DefaultRequestDirector.execute(DefaultRequestDirector.java:360)
08-31 03:39:48.741: E/AndroidRuntime(15972): at org.apache.http.impl.client.AbstractHttpClient.execute(AbstractHttpClient.java:555)
08-31 03:39:48.741: E/AndroidRuntime(15972): at org.apache.http.impl.client.AbstractHttpClient.execute(AbstractHttpClient.java:487)
08-31 03:39:48.741: E/AndroidRuntime(15972): at org.apache.http.impl.client.AbstractHttpClient.execute(AbstractHttpClient.java:465)
08-31 03:39:48.741: E/AndroidRuntime(15972): at com.engahmedphp.facebookcollector.JSONParser.getJSONFromUrl(JSONParser.java:38)
08-31 03:39:48.741: E/AndroidRuntime(15972): at com.engahmedphp.facebookcollector.PagesActivity$1$1.onClick(PagesActivity.java:49)
08-31 03:39:48.741: E/AndroidRuntime(15972): at com.android.internal.app.AlertController$ButtonHandler.handleMessage(AlertController.java:166)
08-31 03:39:48.741: E/AndroidRuntime(15972): at android.os.Handler.dispatchMessage(Handler.java:99)
08-31 03:39:48.741: E/AndroidRuntime(15972): at android.os.Looper.loop(Looper.java:137)
08-31 03:39:48.741: E/AndroidRuntime(15972): at android.app.ActivityThread.main(ActivityThread.java:5103)
08-31 03:39:48.741: E/AndroidRuntime(15972): at java.lang.reflect.Method.invokeNative(Native Method)
08-31 03:39:48.741: E/AndroidRuntime(15972): at java.lang.reflect.Method.invoke(Method.java:525)
08-31 03:39:48.741: E/AndroidRuntime(15972): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:737)
08-31 03:39:48.741: E/AndroidRuntime(15972): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:553)
08-31 03:39:48.741: E/AndroidRuntime(15972): at dalvik.system.NativeStart.main(Native Method)
You are getting NetworkOnMainThreadException. See How to fix android.os.NetworkOnMainThreadException? . This exception is thrown when an application attempts to perform a networking operation on its main (UI) thread. Do the networking tasks using AsyncTask or inside a new thread. See the Android Documentation on NetworkOnMainThreadException for reasons of this Exception.
Here:
// getting JSON string from URL
JSONObject json = jParser.getJSONFromUrl(url);
you are doing network related stuff on main UI thread. Try to do this in a new thread.
The JSONParser make a HTTP connect in UI thread(The oneClick is invoked in UI thread)and it was fobidden now.
So you need move the network codes to other thread.
In case you have not noticed; StrictMode for network access results in a fatal error as for Android 3.0 (Honeycomb) or later, unless your app is targeting an API version before Honeycomb.
The right way of solving this is to use Android AsyncTask for network access.
The lazy way of handling this is to turn the check of:
StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitAll().build();
StrictMode.setThreadPolicy(policy);
As others mentioned, you shouldn't be doing networking on UI thread to make your app UI responsive.
Try this
public class JsonParser extends AsyncTask<String, Void, JSONObject> {
InputStream is = null;
JSONObject jObj = null;
String json = "";
#Override
protected JSONObject doInBackground(String... params) {
// Making HTTP request
try {
// defaultHttpClient
DefaultHttpClient httpClient = new DefaultHttpClient();
HttpPost httpPost = new HttpPost(params[0]);
HttpResponse httpResponse = httpClient.execute(httpPost);
HttpEntity httpEntity = httpResponse.getEntity();
is = httpEntity.getContent();
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
try {
BufferedReader reader = new BufferedReader(new InputStreamReader(is, "iso-8859-1"), 8);
StringBuilder sb = new StringBuilder();
String line = null;
while ((line = reader.readLine()) != null) {
sb.append(line + "\n");
}
is.close();
json = sb.toString();
} catch (Exception e) {
Log.e("Buffer Error", "Error converting result " + e.toString());
}
// try parse the string to a JSON object
try {
jObj = new JSONObject(json);
} catch (JSONException e) {
Log.e("JSON Parser", "Error parsing data " + e.toString());
}
// return JSON String
return jObj;
}
#Override
protected void onPostExecute(JSONObject json) {
try {
// Storing each json item in variable
String name = json.getString("name");
String fid = json.getString("id");
String picture = json
.getJSONObject("picture")
.getJSONObject("data")
.getString("url");
db.addPage(name, fid, picture);
} catch (JSONException e) {
e.printStackTrace();
}
}
}
Put the above class in your activity class, then use new JsonParser().execute(url); to fetch data and update the database.

Categories