1

I have the following file upload function:

    public void uploadFile(Context context, File file) {
        String urlServer = "https://u-database.000webhostapp.com/recieve_file.php";
        if(file.isFile() && file.exists()) {
            String fileName = file.getAbsolutePath();
            try {
                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;
                Toast toastw = Toast.makeText(context, "Inside TRY", Toast.LENGTH_SHORT);
                toastw.show();

                FileInputStream fileInputStream = new FileInputStream(file);
                URL url = new URL(urlServer);

                // 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("textLog", fileName);

                dos = new DataOutputStream(conn.getOutputStream());

                dos.writeBytes(twoHyphens + boundary + lineEnd);
                dos.writeBytes("Content-Disposition: form-data; name=\"textLog\";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)
                int serverResponseCode = conn.getResponseCode();
                String serverResponseMessage = conn.getResponseMessage();
                Toast toast = Toast.makeText(context, "Uploading", Toast.LENGTH_SHORT);
                toast.show();

                if(serverResponseCode == 200){
                    file.delete();
                    Toast toasto = Toast.makeText(context, "success", Toast.LENGTH_SHORT);
                    toasto.show();
                }

                fileInputStream.close();
                dos.flush();
                dos.close();
            } catch (MalformedURLException ex) {
                Toast toast = Toast.makeText(context, "Malformed URL", Toast.LENGTH_SHORT);
                toast.show();
            } catch (Exception e) {
                Toast toast = Toast.makeText(context, "Exception", Toast.LENGTH_SHORT);
                toast.show();
            }
        }
    }

Each time it is executed, a toast appears stating Inside TRY and then another appears stating "Exception".

I have been debugging a lot and any kind of help would be really appreciated :)

UPDATE

When I did e.toString and printed it out to a toast, I got: android.os.NetworkOnMainThreadException

11
  • Well it would tell you more if you checked what ex has to offer (such as printStackTrace or something similar) Commented May 8, 2017 at 12:50
  • Well, @ItamarGreen thanks for looking, it's generally part of a BroadCastReciver so I can't debug it in AVD as it doesnot have any activity. So basically its hopeless. Do you know other ways to get stacktraces? Commented May 8, 2017 at 12:52
  • Well, to log the exception, you can refer to here: stackoverflow.com/questions/7841232/… Commented May 8, 2017 at 12:53
  • @ItamarGreen where? I dont see links there Commented May 8, 2017 at 12:54
  • 1
    Can't you edit the code and printout the toString() of the exception? Commented May 8, 2017 at 13:00

1 Answer 1

1

The answer is simple then. You should run your network calls on a background thread. You need to extend AsyncTask and move your code into it. Something like:

private class InitTask extends AsyncTask<Void, Void, Void>{
      protected Void doInBackground(Void... p){
         // Call upload file code here
      }
}
Sign up to request clarification or add additional context in comments.

5 Comments

Can it be a inner Class?
Sure. You can look at this tutorial for a lot more explanations and examples: androidkennel.org/android-networking-tutorial-with-asynctask .
Missing return statement @DoronYakovlev-Golani
Solved it by adding return null, testing it now. but I really cant display toasts there.
This is just a pseudo-code skeleton (I didn't compile it)... you have to fill in the details.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.