Does anyone know how i can add a progress bar that tells me how much of the file has been uploaded. This is what i have managed to do in the code below, i have managed to pick a file from my phone and have also managed to send it, but the problem is if i am uploading a huge file i keep waiting not knowing when it will finish and that is why i need a progress bar that shows me how much has been transferred to the server. This is the code that i have i have tried different implementations but to no avail.
public class MainActivity extends AppCompatActivity {
private Button fileUploadBtn;
protected static String IPADDRESS = "http://10.42.0.1/hugefile/save_file.php";
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
fileUploadBtn = (Button) findViewById(R.id.btnFileUpload);
pickFile();
}
private void pickFile() {
fileUploadBtn.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
new MaterialFilePicker()
.withActivity(MainActivity.this)
.withRequestCode(10).start();
}
});
}
ProgressDialog progress;
@Override
protected void onActivityResult(int requestCode, int resultCode, final Intent data) {
progress = new ProgressDialog(MainActivity.this);
progress.setTitle("Uploading File(s)");
progress.setMessage("Please wait...");
progress.show();
if (requestCode == 10 && resultCode == RESULT_OK) {
Thread t = new Thread(new Runnable() {
@Override
public void run() {
File f = new File(data.getStringExtra(FilePickerActivity.RESULT_FILE_PATH));
String content_type = getMimeType(f.getPath());
String file_path = f.getAbsolutePath();
OkHttpClient client = new OkHttpClient();
RequestBody file_body = RequestBody.create(MediaType.parse(content_type), f);
RequestBody request_body = new MultipartBody.Builder()
.setType(MultipartBody.FORM)
.addFormDataPart("type", content_type)
.addFormDataPart("uploaded_file", file_path.substring(file_path.lastIndexOf("/") + 1), file_body).build();
Request request = new Request.Builder()
.url(IPADDRESS)
.post(request_body)
.build();
try {
Response response = client.newCall(request).execute();
Log.d("Server response", response.body().string());
if (!response.isSuccessful()) {
throw new IOException("Error : " + response);
}
progress.dismiss();
} catch (IOException e) {
e.printStackTrace();
}
}
});
t.start();
}
}
private String getMimeType(String path) {
String extension = MimeTypeMap.getFileExtensionFromUrl(path);
return MimeTypeMap.getSingleton().getMimeTypeFromExtension(extension);
}
}