简体   繁体   中英

Uploading a file from android take ages before calling a function

I'm having a hard time with calling a function when I select on the files.

When I select on a file, it start to take like 10 seconds before it start to call the UploadFile function and then connect to the server, so when I select more files to add, it will take like a minute or so before it start to call the UploadFile function and connect to the server which is wrong. It should have start to call the UploadFile function instantly and connect to the server when I am adding more than one files.

Below is the full code:

public class ComposeActivity extends AppCompatActivity implements AdapterView.OnItemSelectedListener {

    private static final int CHOOSE_FILE_REQUESTCODE = 1;
    private RecyclerView mFilesDetailRecyclerView;
    private ArrayList<String> mSelectedFilesList = new ArrayList<>();

    @Override
    protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
super.onActivityResult(requestCode, resultCode, data);

        if (resultCode == RESULT_OK && requestCode == CHOOSE_FILE_REQUESTCODE) {
        try {
            Uri uri = data.getData();
            Cursor cursor = getContentResolver().query(uri, null, null, null, null);
            int index = cursor.getColumnIndex(OpenableColumns.DISPLAY_NAME);
            Context context = getApplicationContext();
            FilePath = RealPathUtil.getRealPath(context, uri);
            cursor.moveToFirst();
            //mSelectedFilesList.add(cursor.getString(index));
            mSelectedFilesList.add(FilePath);
            mAdapter.notifyItemInserted(mSelectedFilesList.size());

            Log.e("message.......", "caught this.....");

            upload_File = new File(FilePath);
            FileName = upload_File.getName();

            new UploadFile().execute();

        } catch (Exception e) {
            Toast.makeText(ComposeActivity.this, "Choose any other file", Toast.LENGTH_SHORT).show();
        }
    }
}

@SuppressLint("StaticFieldLeak")
private class UploadFile extends AsyncTask<Void, Void, Void> {
    @RequiresApi(api = Build.VERSION_CODES.O)
    @Override
    protected Void doInBackground(Void... params) {
        HttpURLConnection urlConnection = null;

        try {

            String twoHyphens = "--";
            String boundary = "*****" + System.currentTimeMillis() + "*****";
            String lineEnd = "\r\n";
            Log.e("message.......", "FileName...." + FileName);

            URL url = new URL("https://www.example.com/fileupload1.php");
            urlConnection = (HttpURLConnection) url.openConnection();
            urlConnection.setUseCaches(false);
            urlConnection.setDoOutput(true);
            urlConnection.setDoInput(true);

            urlConnection.setRequestMethod("POST");
            urlConnection.setConnectTimeout(200);
            urlConnection.setReadTimeout(200);

            urlConnection.setRequestProperty("Connection", "Keep-Alive");
            urlConnection.setRequestProperty("ENCTYPE", "multipart/form-data");
            urlConnection.setRequestProperty("Content-Type", "multipart/form-data;boundary=" + boundary);
            urlConnection.setRequestProperty("uploaded_file", FileName);
            FileInputStream fileInputStream = new FileInputStream(upload_File);
            DataOutputStream dataOutputStream = new DataOutputStream(urlConnection.getOutputStream());
            dataOutputStream.writeBytes(twoHyphens + boundary + lineEnd);
            dataOutputStream.writeBytes("Content-Disposition:  form-data; name=\"uploaded_file" +
                "\"; filename=\"" + FileName + "\"" + lineEnd);
            dataOutputStream.writeBytes(lineEnd);
            int bytesRead, bytesAvailable, bufferSize;
            byte[] buffer;
            int maxBufferSize = 1 * 1024 * 1024;
            Log.e("message.......", "FileName...." + FileName);

            //returns no. of bytes present in  fileInputStream
            bytesAvailable = fileInputStream.available();

            bufferSize = Math.min(bytesAvailable, maxBufferSize);
            buffer = new byte[bufferSize];
            bytesRead = fileInputStream.read(buffer, 0, bufferSize);
            //Thread.sleep(5000);

            while (bytesRead > 0) {
                //int percentage = (int)  ((bytesRead / (float) size) * 100);
                dataOutputStream.write(buffer, 0, bufferSize);
                //dataOutputStream.flush(); //doesn't  help
                bytesAvailable = fileInputStream.available();
                bytesRead = fileInputStream.read(buffer, 0, bufferSize);
            }

            dataOutputStream.writeBytes(lineEnd);
            dataOutputStream.writeBytes(twoHyphens + boundary + twoHyphens
                + lineEnd);
            int code = urlConnection.getResponseCode();
            StringBuilder result = new StringBuilder();

            if (code == 200) {
                InputStream in = new BufferedInputStream(urlConnection.getInputStream());
                BufferedReader reader = new BufferedReader(new InputStreamReader(in));
                String line;

                while ((line = reader.readLine()) != null) {
                    result.append(line);
                }
                upload_success = result.toString();
            }

        } catch(SocketTimeoutException e) {
            //e.printStackTrace();

            if (urlConnection != null) {
                urlConnection.disconnect();
                cancel(true);
            }
        }
        catch (UnsupportedEncodingException e) {
            e.printStackTrace();
            Log.e("message.......", "here....5");
        } catch (ClientProtocolException e) {
            e.printStackTrace();
            Log.e("message.......", "here....6");
        } catch (ConnectTimeoutException e) {
            e.printStackTrace();
            Log.e("message.......", "here....7");
        }
        catch (IOException ioException) {
            ioException.printStackTrace();
            Log.e("message.......", "here....2");
        }
        catch (Exception e) {
            e.printStackTrace();
            Log.e("message.......", "here....5");

            if (failtoupload == false) {
                failtoupload = true;
            }

            if (sendMail == true) {
                sendMail = false;
            }

            if (UpdateDraft == true) {
                UpdateDraft = false;
            }

            if (saveDraft == true) {
                saveDraft = false;
            }
            Date dt = new Date();
            SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
            String savedDate = dateFormat.format(dt);
            draftDB = new DraftDB(mContext);

            if (mSelectedFilesList.size() == 1) {
                attachments = join("", mSelectedFilesList);

                if (attachments.equals("")) {
                    attachments = null;
                }
            }
            else
            {
                attachments = join(", ", mSelectedFilesList);
            }


            if (attachments == null) {
                if (mSelectedFilesList.size() == 1) {
                    attachments = join("", mSelectedFilesList);
                }
                else
                {
                    attachments = join(", ", mSelectedFilesList);
                }
            }
            String isImportant = "true";
            String isRead = "unread";
            String UpdateDB = null;
            String draftID = null;



            if (to == null) {
                to = "";
            }

            if (bcc == null) {
                bcc = "";
            }

            if (cc == null) {
                cc = "";
            }

            if (subject == null) {
                subject = "";
            }

            if (message == null) {
                message = "";
            }

            if (draft_id != null) {
                draftID = draft_id;
                UpdateDB = "yes";
            }
            else
            {
                draftID = "";
                UpdateDB = "no";
            }


        
            if (draftDB_id == 0) {
                draftDB.insertDraft(from, to, cc, bcc, subject, message, attachments, isImportant, isRead, UpdateDB, draftID, savedDate);
                draftDB_id = draftDB.getID();
            }
            else
            {
                int id = draftDB_id;
                draftDB.updateDraft(id, from, to, cc, bcc, subject, message, attachments, isImportant, isRead, UpdateDB, draftID, savedDate);
            }

        else
        {
            int id = draftDB_id;
            draftDB.updateDraft(id, from, to, cc, bcc, subject, message, attachments, isImportant, isRead, UpdateDB, draftID, savedDate);

        } finally {
            if (urlConnection != null) {
                urlConnection.disconnect();
            }
        }
        return null;
    }

    @Override
    protected void onPostExecute(Void aVoid) {
        Log.e("message.......", "here....6");

        if (upload_success != null) {
            if (upload_success.equals("success")) {
                if (mSelectedFilesList.size() > 0) {
                    mSelectedFilesList.remove(0);

                    if (draft_id == null) {
                        new SaveDraft().execute();
                    }
                    else if (draft_id != null) {
                        if (attachment != null) {
                            if (mSelectedFilesList.size() >= 1) {
                                attid++;

                                for (int i = 0; i < mSelectedFilesList.size(); i++) {
                                    String path = mSelectedFilesList.get(0);
                                    FileName = path.substring(path.lastIndexOf("/") + 1);
                                    attachment += " attid: " + String.valueOf(attid) + " filename: " + FileName;
                                }
                            }
                        }
                        Log.e("message........", "attachment......" + attachment);
                        new UpdateDrafts().execute();
                    }


                    if (mSelectedFilesList.size() >= 1) {
                        FilePath = mSelectedFilesList.get(0);
                        upload_File = new File(FilePath);
                        FileName = upload_File.getName();
                        new UploadFile().execute();
                    }
                }

                //Now time to check the upload_File
                if (mSelectedFilesList.size() == 0) {
                    if (upload_File != null) {
                        upload_File = null;
                    }

                    if (FilePath != null) {
                        FilePath = null;
                    }
                    Log.e("message.......", "sendMail........." + sendMail);
                }

                if (upload_success != null) {
                    upload_success = null;
                }
            }
        }
    }

    @Override
    protected void onCancelled() {
        super.onCancelled();
        this.cancel(true);
    }
}

What I am trying to do is when I select on the file and add more files on my mobile app, I want to call the UploadFile function instantly and connect to my server to upload the file in each time when I select on the file. If the server do not response for 10 seconds and the server is offline, I want to store the data in the sqlite database.

I have been told that I should use multi thread and I should also use retrofit. I am not sure if it would be possible to use HttpUrlConnection method with multi thread to connect to the server and upload the files.

Can you please show me an example of what is the best way I could use to get instantly call to a function and connect to the server using with HttpUrlConnection if that is possible??

You start already wrong with trying to get a real path for an uri.

Remove that code.

Then instead of opening a FileInputStream open an InputStream for the uri

InputStream is = getContentResolvet().openInputStream(uri);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM