-1

i am trying to send an image to my php server but i am getting these errors

 android.os.NetworkOnMainThreadException
at android.os.StrictMode$AndroidBlockGuardPolicy.onNetwork(StrictMode.java:1144)
at java.net.InetAddress.lookupHostByName(InetAddress.java:385)
at java.net.InetAddress.getAllByNameImpl(InetAddress.java:236)
at java.net.InetAddress.getAllByName(InetAddress.java:214)
at libcore.net.http.HttpConnection.<init>(HttpConnection.java:70)
at libcore.net.http.HttpConnection.<init>(HttpConnection.java:50)
at libcore.net.http.HttpConnection$Address.connect(HttpConnection.java:340)

here is my code of sending image

public int uploadFile(String sourceFileUri) {
      System.out.println("file path is " + sourceFileUri); //here i am successfully   getting the image path
        String upLoadServerUri = "http://www";
        String fileName = sourceFileUri;
        int serverResponseCode = 0;
        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()) {
            Log.e("uploadFile", "Source File Does not exist");
            return 0;
        }
        try { // open a URL connection to the Servlet
            FileInputStream fileInputStream = new FileInputStream(sourceFile);
            URL url = new URL(upLoadServerUri);
            conn = (HttpURLConnection) url.openConnection(); // Open a HTTP
                                                                // connection to
                                                                // the URL
            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);

            bytesAvailable = fileInputStream.available(); // create a buffer of
                                                            // maximum size

            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) {
               System.out.println("server is ok");
            }

            // close the streams //
            fileInputStream.close();
            dos.flush();
            dos.close();

        } catch (MalformedURLException ex) {

            Log.e("Upload file to server", "error: " + ex.getMessage(), ex);
        } catch (Exception e) {
            e.printStackTrace();

            Log.e("Upload file to server Exception",
                    "Exception : " + e.getMessage(), e);
        }
        return serverResponseCode;
    }

i dont want to use async task. please give me some other way to send an image

hellosheikh
  • 2,929
  • 8
  • 49
  • 115
  • check this [link][1] it may help you... [1]: http://stackoverflow.com/questions/6976317/android-http-connection-exception – Anil kumar Feb 21 '14 at 13:33
  • 1
    Another NetworkOnMainThreadException question, really ? Next time, use Google ... – 2Dee Feb 21 '14 at 13:41

2 Answers2

1

Two way you can do that one using the Asyn Task

    public class MyUploadTask extends AsynTask<void,void,void>{
          void doInBackground(){
             //... do your upload task
            }
      }

The other is using a Thread

Thread myUploadTask = new Thread(new Runnable(){
              void run(){
                 //... do your upload task
              }
        });
myUploadTask.start();

if you want to post update to the UI in a normal Thread use android.os.Handler Object to send messages between you main thread and Worker Thread.

In your case: if i want to send image to the server in oncreate() method

public void onCreate(){
   super.onCreate();
     uploadToServer();
}
public void uploadToServer(){
Thread myUploadTask = new Thread (new Runnable(){
void run(){
    //Calling the upload Image method
  uploadFile("www.yourdomin.com/uploadFile");
   }
});
 myUploadTask.start();
}
u.jegan
  • 833
  • 6
  • 15
0

This exception is because you are uploading image on main thread... Instead use AsyncTask to upload image to server...

Looking Forward
  • 3,579
  • 8
  • 45
  • 65