Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I use an Async Task to upload a file to the server?

Tags:

java

android

Below is my code for uploading a file to the server. But I'm getting network exceptions even after several tries and even after adding strict mode.

I'm new to Android and don't know how can I use the async task, which many people advised for such kind of network operation. Could anyone tell me that where I'm wrong in the code and where should I use async task?

package de.fileuploader;

import java.io.BufferedReader;
import java.io.File;
import java.io.InputStreamReader;

import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.mime.HttpMultipartMode;
import org.apache.http.entity.mime.MultipartEntity;
import org.apache.http.entity.mime.content.ByteArrayBody;
import org.apache.http.entity.mime.content.FileBody;
import org.apache.http.entity.mime.content.StringBody;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.protocol.BasicHttpContext;
import org.apache.http.protocol.HttpContext;

import android.app.Activity;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.os.Bundle;
import android.os.StrictMode;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;

@SuppressWarnings("unused")
 public class Android_helloActivity extends Activity {

private String newName = "SMSBackup.txt";
private String uploadFile = "/mnt/sdcard/SMSBackup.txt";
private String actionUrl = "http://192.168.1.8:8080/admin/admin/uploads";
// private String
// actionUrl="http://upload-file.shcloudapi.appspot.com/upload";
private TextView mText1;
private TextView mText2;
private Button mButton;

@Override
public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
        StrictMode.setThreadPolicy(new StrictMode.ThreadPolicy.Builder()  
        .detectDiskReads()  
        .detectDiskWrites()  
        .detectNetwork()   // or .detectAll() for all detectable problems  
        .penaltyLog()  
        .build());  
       StrictMode.setVmPolicy(new StrictMode.VmPolicy.Builder()  
        .detectLeakedSqlLiteObjects()  
        .detectLeakedClosableObjects()  
        .penaltyLog()  
        .penaltyDeath()  
        .build()); 

        mText1 = (TextView) findViewById(R.id.myText2);
        mText1.setText("Upload\n" + uploadFile);
        mText2 = (TextView) findViewById(R.id.myText3);
        mText2.setText("To Server Location\n" + actionUrl);

        mButton = (Button) findViewById(R.id.myButton);
        mButton.setOnClickListener(new View.OnClickListener() {
                public void onClick(View v) {
                        /* uploadFile(); */
                        try {
                                HttpClient httpClient = new DefaultHttpClient();
                                HttpContext localContext = new BasicHttpContext();
                                HttpPost httpPost = new HttpPost(actionUrl);

                                MultipartEntity entity = new MultipartEntity(
                                                HttpMultipartMode.BROWSER_COMPATIBLE);
                                entity.addPart("name", new StringBody(newName));
                                File file=new File(uploadFile);
                                entity.addPart("file", new FileBody(file));
                                //entity.addPart("file", new
                                ByteArrayBody(data,"myImage.jpg"));
                                entity.addPart("gps", new StringBody("35.6,108.6"));
                                httpPost.setEntity(entity);
                                HttpResponse response = httpClient.execute(httpPost,
                                                localContext);
                                BufferedReader reader = new BufferedReader(
                                                new  
                               InputStreamReader(response.getEntity().getContent(), 
                                 "UTF-8"));

                                String sResponse = reader.readLine();
                                Log.i("info", "test");
                                  } catch (Exception e) {
                                // Log.e("exception", e.printStackTrace());
                                 e.printStackTrace();
                                showDialog("" + e);
                               } 
                               }
                               });
                               }


                          private void showDialog(String mess) {
                new AlertDialog.Builder(Android_helloActivity.this).setTitle("Message")
                         .setMessage(mess)
                        .setNegativeButton("Exit", new  DialogInterface.OnClickListener() {
                                public void onClick(DialogInterface dialog, int which)      {
                                }
                        }).show();
 }
}
like image 667
IMRAN Avatar asked Oct 07 '22 16:10

IMRAN


1 Answers

mButton.setOnClickListener(new View.OnClickListener() {
                public void onClick(View v) {

new UploadImageTask().execute(); // initialize asynchronous task

}});

//Now implement Asynchronous Task


public class Get_User_Data extends AsyncTask<Void, Void, Void> {

            private final ProgressDialog dialog = new ProgressDialog(
            MyActivity.this);

    protected void onPreExecute() {
        this.dialog.setMessage("Loading...");
        this.dialog.setCancelable(false);
        this.dialog.show();
    }
        @Override
        protected Void doInBackground(Void... params) {

                    uploadImage(); // inside the method paste your file uploading code
            return null;
        }

        protected void onPostExecute(Void result) {

            // Here if you wish to do future process for ex. move to another activity do here

            if (dialog.isShowing()) {
                dialog.dismiss();
            }

        }
    }

For more information refer this link http://vikaskanani.wordpress.com/2011/01/29/android-image-upload-activity/

like image 124
Aerrow Avatar answered Oct 10 '22 07:10

Aerrow