Skip to content

Instantly share code, notes, and snippets.

@shihabmi7
Created June 24, 2019 08:30
Show Gist options
  • Save shihabmi7/7f22f7bebe820d61e6453facf183882f to your computer and use it in GitHub Desktop.
Save shihabmi7/7f22f7bebe820d61e6453facf183882f to your computer and use it in GitHub Desktop.
Multiple Image Upload by @shih@b_Uddin
package com.khudrosoft.vision.activity;
import android.Manifest;
import android.app.Activity;
import android.app.AlertDialog;
import android.content.ActivityNotFoundException;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.graphics.drawable.BitmapDrawable;
import android.media.MediaScannerConnection;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.os.Environment;
import android.provider.MediaStore;
import android.support.annotation.NonNull;
import android.support.v4.app.ActivityCompat;
import android.support.v4.app.NavUtils;
import android.support.v4.content.ContextCompat;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.support.v7.widget.Toolbar;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.WindowManager;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;
import com.khudrosoft.vision.R;
import com.khudrosoft.vision.adapter.MyRecAdapter;
import com.khudrosoft.vision.model.AddOrcefResponse;
import com.khudrosoft.vision.network.ApiClient;
import com.khudrosoft.vision.network.ApiInterface;
import com.khudrosoft.vision.utility.ApplicationData;
import com.khudrosoft.vision.utility.Connectivity;
import com.khudrosoft.vision.utility.FileUtils;
import com.khudrosoft.vision.utility.ImagePicker;
import com.khudrosoft.vision.utility.LogMe;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Objects;
import okhttp3.MediaType;
import okhttp3.MultipartBody;
import okhttp3.RequestBody;
import okhttp3.ResponseBody;
import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;
public class AddOrcefRxActivity extends BaseActivity implements View.OnClickListener {
private static final int MY_PERMISSIONS_REQUEST_READ_PICTURES = 5252;
private static final int PICK_IMAGE_ID = 234;
private static final int REQUEST_CODE = 6384;
private static final int REQUEST_CODE_ASK_PERMISSIONS = 124;
public static final String LONG_DATE_FORMAT = "dd-MM-yyyy";
private String TAG = "AddOrcefRx";
TextView editTextDate;
private Activity activity;
ImageView imageViewRxPic;
Button btnSubmitRx;
RelativeLayout rlImage;
private Bitmap bitmap;
Bitmap latestBitmap;
ImageView ivZoom;
private RecyclerView listView;
public static ArrayList<Uri> URL_List = new ArrayList<>();
MyRecAdapter mAdapter;
void clearData() {
URL_List.clear();
mAdapter.notifyDataSetChanged();
}
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_sumit_orcef_rx);
getWindow().addFlags
(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
activity = this;
editTextDate = findViewById(R.id.txtDate);
editTextDate.setEnabled(false);
imageViewRxPic = findViewById(R.id.imageViewRxPic);
//imageViewChoosePicture = findViewById(R.id.imageViewChoosePicture);
//imageViewChoosePicture.setOnClickListener(this);
btnSubmitRx = findViewById(R.id.btnSubmitOrcefRx);
btnSubmitRx.setOnClickListener(this);
rlImage = findViewById(R.id.rlPhoto);
rlImage.setOnClickListener(this);
//imageHint = findViewById(R.id.imageHint);
//Arafat
ivZoom = findViewById(R.id.ivZoom);
ivZoom.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
showZoom();
}
});
SimpleDateFormat sdf = new SimpleDateFormat(LONG_DATE_FORMAT);
String currentDateandTime = sdf.format(new Date());
editTextDate.setText(currentDateandTime);
bitmap = ((BitmapDrawable) imageViewRxPic.getDrawable()).getBitmap();
listView = findViewById(R.id.listView);
listView.setLayoutManager(new LinearLayoutManager(this, LinearLayoutManager.VERTICAL, false));
mAdapter = new MyRecAdapter(AddOrcefRxActivity.this, URL_List);
listView.setAdapter(mAdapter);
if (Connectivity.isConnected(activity)) {
} else {
showAlertForInternet(this);
}
}
public static RequestBody getRequestBody(String type, String content) {
return RequestBody.create(MediaType.parse(type), content);
}
@NonNull
private RequestBody createPartFromString(String descriptionString) {
return RequestBody.create(
okhttp3.MultipartBody.FORM, descriptionString);
}
@NonNull
private MultipartBody.Part prepareFilePart(String partName, Uri fileUri) {
// https://github.com/iPaulPro/aFileChooser/blob/master/aFileChooser/src/com/ipaulpro/afilechooser/utils/FileUtils.java
// use the FileUtils to get the actual file by uri
// File file = FileUtils.getFile(this, fileUri);
File file = new File(getPath(fileUri));
/*// create RequestBody instance from file
RequestBody requestFile =
RequestBody.create(
MediaType.parse(Objects.requireNonNull(getContentResolver().getType(fileUri))),
file
);*/
RequestBody requestFile = RequestBody.create(MediaType.parse("image/*"), file);
// MultipartBody.Part is used to send also the actual file name
return MultipartBody.Part.createFormData(partName, file.getName(), requestFile);
}
@Override
public void onClick(View v) {
if (v == btnSubmitRx) {
if (Connectivity.isConnected(activity)) {
//submitOrCefFormSubmit();
submitOrCefFormSubmitAnother();
} else {
showAlertForInternet(activity);
}
} else if (v == rlImage) {
/*if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M
&& ContextCompat.checkSelfPermission(this, Manifest.permission.READ_EXTERNAL_STORAGE) !=
PackageManager.PERMISSION_GRANTED) {
askPermission();
} else {
onPickImage();
}*/
if (askForPermission())
showChooser();
}
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
// Respond to the action bar's Up/Home button
case android.R.id.home:
NavUtils.navigateUpFromSameTask(this);
return true;
}
return super.onOptionsItemSelected(item);
}
@Override
public void onRequestPermissionsResult(int requestCode,
String permissions[], int[] grantResults) {
switch (requestCode) {
case MY_PERMISSIONS_REQUEST_READ_PICTURES: {
// If request is cancelled, the result arrays are empty.
if (grantResults.length > 0
&& grantResults[0] == PackageManager.PERMISSION_GRANTED) {
// permission was granted, yay! Do the
// contacts-related task you need to do.
//onPickImage();
showChooser();
} else {
// permission denied, boo! Disable the
// functionality that depends on this permission.
showToastMessage("Accept permission to pick picture");
}
return;
}
// other 'case' lines to check for other
// permissions this app might request
}
}
public void onPickImage() {
Intent chooseImageIntent = ImagePicker.getPickImageIntent(this);
chooseImageIntent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
startActivityForResult(chooseImageIntent, PICK_IMAGE_ID);
}
public String getPath(Uri uri) {
String[] projection = {MediaStore.Images.Media.DATA};
Cursor cursor = managedQuery(uri, projection, null, null, null);
if (cursor != null) {
//HERE YOU WILL GET A NULLPOINTER IF CURSOR IS NULL
//THIS CAN BE, IF YOU USED OI FILE MANAGER FOR PICKING THE MEDIA
int column_index = cursor
.getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
cursor.moveToFirst();
return cursor.getString(column_index);
} else return null;
}
public Uri getImageUri(Context inContext, Bitmap inImage) {
ByteArrayOutputStream bytes = new ByteArrayOutputStream();
inImage.compress(Bitmap.CompressFormat.JPEG, 100, bytes);
String path = MediaStore.Images.Media.insertImage(inContext.getContentResolver(), inImage, "Title", null);
return Uri.parse(path);
}
public String getRealPathFromURI(Uri uri) {
Cursor cursor = getContentResolver().query(uri, null, null, null, null);
cursor.moveToFirst();
int idx = cursor.getColumnIndex(MediaStore.Images.ImageColumns.DATA);
return cursor.getString(idx);
}
void showMessage(String message, String title) {
android.support.v7.app.AlertDialog.Builder builder1;
builder1 = new android.support.v7.app.AlertDialog.Builder(activity);
builder1.setMessage(message);
builder1.setCancelable(false);
builder1.setTitle(title);
builder1.setPositiveButton("Ok",
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
//imageViewRxPic.setImageBitmap(null);
dialog.dismiss();
}
});
// builder1.setNegativeButton("No",
// new DialogInterface.OnClickListener() {
// public void onClick(DialogInterface dialog, int id) {
// ((Activity) LogInActivity.this).finish();
// }
// });
android.support.v7.app.AlertDialog alert11 = builder1.create();
alert11.show();
}
public void callBroadCast() {
if (Build.VERSION.SDK_INT >= 14) {
Log.e("-->", " >= 14");
MediaScannerConnection.scanFile(this, new String[]{Environment.getExternalStorageDirectory().toString()}, null, new MediaScannerConnection.OnScanCompletedListener() {
/*
* (non-Javadoc)
* @see android.media.MediaScannerConnection.OnScanCompletedListener#onScanCompleted(java.lang.String, android.net.Uri)
*/
public void onScanCompleted(String path, Uri uri) {
Log.e("ExternalStorage", "Scanned " + path + ":");
Log.e("ExternalStorage", "-> uri=" + uri);
}
});
} else {
Log.e("-->", " < 14");
sendBroadcast(new Intent(Intent.ACTION_MEDIA_MOUNTED,
Uri.parse("file://" + Environment.getExternalStorageDirectory())));
}
}
private void showZoom() {
final AlertDialog.Builder dialogBuilder = new AlertDialog.Builder(this);
LayoutInflater inflater = this.getLayoutInflater();
View dialogView = inflater.inflate(R.layout.dialog_image_zoom_layout, null);
dialogBuilder.setView(dialogView);
ImageView ivCloseDialog = dialogView.findViewById(R.id.ivCloseDialog);
ImageView iv = dialogView.findViewById(R.id.myZoomageView);
iv.setImageBitmap(latestBitmap);
final AlertDialog alertDialog = dialogBuilder.create();
ivCloseDialog.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
alertDialog.cancel();
}
});
alertDialog.show();
}
private void showChooser() {
// Use the GET_CONTENT intent from the utility class
Intent target = FileUtils.createGetContentIntent();
// Create the chooser Intent
Intent intent = Intent.createChooser(
target, getString(R.string.chooser_title));
try {
startActivityForResult(intent, REQUEST_CODE);
} catch (ActivityNotFoundException e) {
// The reason for the existence of aFileChooser
}
}
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
switch (requestCode) {
case REQUEST_CODE:
// If the file selection was successful
if (resultCode == RESULT_OK) {
if (data.getClipData() != null) {
int count = data.getClipData().getItemCount();
int currentItem = 0;
while (currentItem < count) {
Uri imageUri = data.getClipData().getItemAt(currentItem).getUri();
//do something with the image (save it to some directory or whatever you need to do with it here)
currentItem = currentItem + 1;
Log.d("Uri Selected", imageUri.toString());
try {
// Get the file path from the URI
String path = FileUtils.getPath(this, imageUri);
Log.d(TAG, "" + path);
URL_List.add(imageUri);
} catch (Exception e) {
Log.e(TAG, "File select error", e);
continue;
}
}
mAdapter.notifyDataSetChanged();
//listView.setAdapter(mAdapter);
} else if (data.getData() != null) {
//do something with the image (save it to some directory or whatever you need to do with it here)
final Uri uri = data.getData();
Log.i(TAG, "Uri = " + uri.toString());
try {
// Get the file path from the URI
final String path = FileUtils.getPath(this, uri);
Log.d("Single File Selected", path);
URL_List.add(uri);
mAdapter.notifyDataSetChanged();
} catch (Exception e) {
Log.e(TAG, "File select error", e);
}
}
}
break;
}
super.onActivityResult(requestCode, resultCode, data);
}
/**
* Runtime Permission
*/
private boolean askForPermission() {
int currentAPIVersion = Build.VERSION.SDK_INT;
if (currentAPIVersion >= Build.VERSION_CODES.M) {
int hasCallPermission = ContextCompat.checkSelfPermission(AddOrcefRxActivity.this,
Manifest.permission.READ_EXTERNAL_STORAGE);
if (hasCallPermission != PackageManager.PERMISSION_GRANTED) {
// Ask for permission
// need to request permission
if (ActivityCompat.shouldShowRequestPermissionRationale(AddOrcefRxActivity.this,
Manifest.permission.READ_EXTERNAL_STORAGE)) {
// explain
showMessageOKCancel(
new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialogInterface, int i) {
ActivityCompat.requestPermissions(AddOrcefRxActivity.this,
new String[]{android.Manifest.permission.READ_EXTERNAL_STORAGE},
REQUEST_CODE_ASK_PERMISSIONS);
}
});
// if denied then working here
} else {
// Request for permission
ActivityCompat.requestPermissions(AddOrcefRxActivity.this,
new String[]{android.Manifest.permission.READ_EXTERNAL_STORAGE},
REQUEST_CODE_ASK_PERMISSIONS);
}
return false;
} else {
// permission granted and calling function working
return true;
}
} else {
return true;
}
}
private void showMessageOKCancel(DialogInterface.OnClickListener okListener) {
android.support.v7.app.AlertDialog.Builder builder = new android.support.v7.app.AlertDialog.Builder(AddOrcefRxActivity.this);
final android.support.v7.app.AlertDialog dialog = builder.setMessage("You need to grant access to Read External Storage")
.setPositiveButton("OK", okListener)
.setNegativeButton("Cancel", null)
.create();
dialog.setOnShowListener(new DialogInterface.OnShowListener() {
@Override
public void onShow(DialogInterface arg0) {
dialog.getButton(android.support.v7.app.AlertDialog.BUTTON_POSITIVE).setTextColor(
ContextCompat.getColor(AddOrcefRxActivity.this, android.R.color.holo_blue_light));
dialog.getButton(android.support.v7.app.AlertDialog.BUTTON_NEGATIVE).setTextColor(
ContextCompat.getColor(AddOrcefRxActivity.this, android.R.color.holo_red_light));
}
});
dialog.show();
}
@Override
protected void onDestroy() {
URL_List.clear();
super.onDestroy();
}
private void submitOrCefFormSubmitAnother() {
try {
showNotCancalableProgress();
ApplicationData.hideKeyboard(activity);
ApiInterface apiService = ApiClient.getClient().create(ApiInterface.class);
MultipartBody.Builder builder = new MultipartBody.Builder();
builder.setType(MultipartBody.FORM);
builder.addFormDataPart("user_id", prefsValues.getUser_id());
builder.addFormDataPart("token", prefsValues.getToken());
builder.addFormDataPart("n_date", editTextDate.getText().toString());
// Map is used to multipart the file using okhttp3.RequestBody
// Multiple Images
for (int i = 0; i < URL_List.size(); i++) {
// File file = new File(getPath(URL_List.get(i)));
File file = FileUtils.getFile(this, URL_List.get(i));
builder.addFormDataPart("file[]", file.getName(), RequestBody.create(MediaType.parse("multipart/form-data"), file));
}
MultipartBody requestBody = builder.build();
Call<AddOrcefResponse> call = apiService.addOrcefRxAnother(requestBody);
call.enqueue(new Callback<AddOrcefResponse>() {
@Override
public void onResponse(Call<AddOrcefResponse> call, Response<AddOrcefResponse> response) {
//Toast.makeText(AddOrcefRxActivity.this, "Success " + response.message(), Toast.LENGTH_LONG).show();
try {
hideNonCancalableProgressDialog();
AddOrcefResponse entryRxObj = response.body();
if (entryRxObj.getStatus().equalsIgnoreCase("success")) {
showMessage("Rx Submitted Successfully", "Success!");
clearData();
} else {
showMessage("Rx not Submitted Successfully. " + entryRxObj.getStatus(), "Failed!");
}
} catch (Exception e) {
e.printStackTrace();
hideNonCancalableProgressDialog();
showMessage("Rx not Submitted Successfully. " +
"An Exception occured." + e.getMessage(), "Failed!");
}
}
@Override
public void onFailure(Call<AddOrcefResponse> call, Throwable t) {
Log.d(TAG, "Error " + t.getMessage());
}
});
} catch (Exception e) {
e.printStackTrace();
}
}
/*private void submitOrCefFormSubmit() {
try {
showNotCancalableProgress();
ApplicationData.hideKeyboard(activity);
/* create list of file parts (photo, video, ...)
List<MultipartBody.Part> parts = new ArrayList<>();
if (URL_List.size() > 0) {
// create part for file (photo, video, ...)
for (int i = 0; i < URL_List.size(); i++) {
parts.add(prepareFilePart("image" + i, URL_List.get(i)));
LogMe.i(TAG, "PART ADDED...");
}
}
MultipartBody.Part[] imagePart = new MultipartBody.Part[URL_List.size()];
for (int i = 0; i < URL_List.size(); i++) {
LogMe.e(TAG, "image " + i + " " + getPath(URL_List.get(i)));
imagePart[i] = prepareFilePart("file" + i, URL_List.get(i));
}
RequestBody id = getRequestBody("text/plain", prefsValues.getUser_id());
RequestBody token = getRequestBody("text/plain", prefsValues.getToken());
RequestBody date = getRequestBody("text/plain", editTextDate.getText().toString());
ApiInterface apiService = ApiClient.getClient().create(ApiInterface.class);
Call<AddOrcefResponse> call = apiService.addOrcefRx(
id, token, date, imagePart);
call.enqueue(new Callback<AddOrcefResponse>() {
@Override
public void onResponse(Call<AddOrcefResponse> call, Response<AddOrcefResponse> response) {
try {
hideNonCancalableProgressDialog();
AddOrcefResponse entryRxObj = response.body();
if (entryRxObj.getStatus().equalsIgnoreCase("success")) {
showMessage("Rx Submitted Successfully", "Success!");
clearData();
} else {
showMessage("Rx not Submitted Successfully. " + entryRxObj.getStatus(), "Failed!");
//imageViewRxPic.setImageDrawable(resources.getDrawable(R.drawable.placeholder_imageview));
}
} catch (Exception e) {
e.printStackTrace();
hideNonCancalableProgressDialog();
showMessage("Rx not Submitted Successfully. " +
"An Exception occured." + e.getMessage(), "Failed!");
}
}
@Override
public void onFailure(Call<AddOrcefResponse> call, Throwable t) {
// Log error here since request failed
LogMe.e(TAG, t.toString());
hideNonCancalableProgressDialog();
showToastMessage(t.toString());
}
});
} catch (Exception e) {
e.printStackTrace();
}
}*/
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment