After some research I came across an open library for multipart file uploading. In my case I want to upload an Image using PUT request which the images are either choose from gallery or by camera. These are the resources I am using:
1. https://github.com/gotev/android-upload-service
2. https://www.simplifiedcoding.net/android-upload-image-to-server/#comment-9852
ProfileSetting.java
public class ProfileSetting extends AppCompatActivity implements AdapterView.OnItemSelectedListener {
private ImageView CustomerIcon;
private Button confirm_button;
//storage permission code
private static final int STORAGE_PERMISSION_CODE = 123;
//Bitmap to get image from gallery
private Bitmap bitmap;
//Uri to store the image uri
private Uri selectedImage;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_profile_setting);
//Requesting storage permission
requestStoragePermission();
confirm_button.setOnClickListener(new Button.OnClickListener(){
#Override
public void onClick(View view) {
uploadMultipart();
//PUT VOLLEY
//saveProfileAccount();
}
});
}
private void showPickImageDialog() {
AlertDialog.Builder builderSingle = new AlertDialog.Builder(ProfileSetting.this);
builderSingle.setTitle("Set Image ");
final ArrayAdapter<String> arrayAdapter = new ArrayAdapter<String>(
ProfileSetting.this,
android.R.layout.select_dialog_singlechoice);
arrayAdapter.add("Gallery");
arrayAdapter.add("Camera");
builderSingle.setNegativeButton(
"cancel",
new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
dialog.dismiss();
}
});
builderSingle.setAdapter(
arrayAdapter,
new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
switch (which) {
case 0:
Intent pickPhoto = new Intent(Intent.ACTION_PICK,
android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
startActivityForResult(pickPhoto, 1);
break;
case 1:
Intent takePicture = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
startActivityForResult(takePicture, 0);
break;
}
}
});
builderSingle.show();
}
protected void onActivityResult(int requestCode, int resultCode, Intent imageReturnedIntent) {
super.onActivityResult(requestCode, resultCode, imageReturnedIntent);
switch(requestCode) {
case 0:
if(resultCode == RESULT_OK){
selectedImage = imageReturnedIntent.getData();
//CustomerIcon.setImageURI(selectedImage);
try{
bitmap = MediaStore.Images.Media.getBitmap(getContentResolver(), selectedImage);
CustomerIcon.setImageBitmap(bitmap);
} catch (IOException e) {
e.printStackTrace();
}
}
break;
case 1:
if(resultCode == RESULT_OK){
Uri selectedImage = imageReturnedIntent.getData();
//CustomerIcon.setImageURI(selectedImage);
try{
bitmap = MediaStore.Images.Media.getBitmap(getContentResolver(), selectedImage);
//bitmap = bitmap.createScaledBitmap(bitmap, 150, 150, true);
CustomerIcon.setImageBitmap(bitmap);
} catch (IOException e) {
e.printStackTrace();
}
}
break;
}
}
/*
* This is the method responsible for image upload
* We need the full image path and the name for the image in this method
* */
public void uploadMultipart() {
//getting name for the image
String name = "customer_icon";
//getting the actual path of the image
String path = getPath(selectedImage);
//Uploading code
try {
String uploadId = UUID.randomUUID().toString();
//Creating a multi part request
new MultipartUploadRequest(this, uploadId, Constants.UPLOAD_URL)
.addFileToUpload(path, "image") //Adding file
.addParameter("name", name) //Adding text parameter to the request
.setNotificationConfig(new UploadNotificationConfig())
.setMaxRetries(2)
.startUpload(); //Starting the upload
} catch (Exception exc) {
Toast.makeText(this, exc.getMessage(), Toast.LENGTH_SHORT).show();
}
}
//method to get the file path from uri
public String getPath(Uri uri) {
Cursor cursor = getContentResolver().query(uri, null, null, null, null);
cursor.moveToFirst();
String document_id = cursor.getString(0);
document_id = document_id.substring(document_id.lastIndexOf(":") + 1);
cursor.close();
cursor = getContentResolver().query(
android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI,
null, MediaStore.Images.Media._ID + " = ? ", new String[]{document_id}, null);
cursor.moveToFirst();
String path = cursor.getString(cursor.getColumnIndex(MediaStore.Images.Media.DATA));
cursor.close();
return path;
}
//Requesting permission
private void requestStoragePermission() {
if (ContextCompat.checkSelfPermission(this, Manifest.permission.READ_EXTERNAL_STORAGE) == PackageManager.PERMISSION_GRANTED)
return;
if (ActivityCompat.shouldShowRequestPermissionRationale(this, Manifest.permission.READ_EXTERNAL_STORAGE)) {
//If the user has denied the permission previously your code will come to this block
//Here you can explain why you need this permission
//Explain here why you need this permission
}
//And finally ask for the permission
ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.READ_EXTERNAL_STORAGE}, STORAGE_PERMISSION_CODE);
}
//This method will be called when the user will tap on allow or deny
#Override
public void onRequestPermissionsResult(int requestCode, #NonNull String[] permissions, #NonNull int[] grantResults) {
//Checking the request code of our request
if (requestCode == STORAGE_PERMISSION_CODE) {
//If permission is granted
if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
//Displaying a toast
Toast.makeText(this, "Permission granted now you can read the storage", Toast.LENGTH_LONG).show();
} else {
//Displaying another toast if permission is not granted
Toast.makeText(this, "Oops you just denied the permission", Toast.LENGTH_LONG).show();
}
}
}
}
I am getting this error :
FATAL EXCEPTION: main
java.lang.NullPointerException: uri
Also I am not sure how to set headers for authorization in this method.
Please help, thank you!
String url = " http://server.yourserver.com/v1/example";
try {
String uploadId = UUID.randomUUID().toString();
//Creating a multi part request
MultipartUploadRequest request = new MultipartUploadRequest(this, uploadId, UPLOAD_URL);
request.addFileToUpload(images.getPath(), "image_url");
request.setNotificationConfig(new UploadNotificationConfig());
request.setMaxRetries(2);
request.startUpload(); //Starting the upload
} catch (Exception exc) {
Toast.makeText(this, exc.getMessage(), Toast.LENGTH_SHORT).show();
}
check following code.(I used okHttp library).
private int uploadFile(String imagePath) {
Log.i("PATH",imagePath);
OkHttpClient client = new OkHttpClient();
File fileSource = new File(imagePath);
if (fileSource.isFile()){
Log.i("EXIST","exist");
}else {
Log.i("NOT EXIST","not exist");
}
final MediaType MEDIA_TYPE;
String imageType;
if (imagePath.endsWith("png")){
MEDIA_TYPE = MediaType.parse("image/png");
imageType = ".png";
}else {
MEDIA_TYPE = MediaType.parse("image/jpeg");
imageType = ".jpg";
}
String timeStamp = new SimpleDateFormat("yyyyMMdd_HHmmss",Locale.US).format(new Date());
String fileName = "Prathap_"+timeStamp+imageType;
RequestBody requestBody = new MultipartBody.Builder()
.setType(MultipartBody.FORM) .addFormDataPart("file",fileName,RequestBody.create(MEDIA_TYPE,fileSource))
.build();
Request request = new Request.Builder()
.url(your url)//your webservice url
.post(requestBody)
.build();
try {
Response response = client.newCall(request).execute();
if (response.isSuccessful()){
Log.i("SUCC",""+response.message());
}
String resp = response.message();
Log.i("MSG",resp);
} catch (IOException e) {
e.printStackTrace();
}
return 0;
}
add the below line in build.gradle under app folder.
compile 'com.squareup.okhttp3:okhttp:3.5.0'
First in build.gradle add this:
implementation "net.gotev:uploadservice:4.7.0"
then in onCreate() add code as bellow:
UploadServiceConfig.initialize(this.getApplication(), "UploadJSON",true);
then make two functions as bellow:
public void uploadJSONFile(String filePath, String UPLOAD_URL){
try {
String uploadId = UUID.randomUUID().toString();
//Creating a multi part request
MultipartUploadRequest request = new MultipartUploadRequest(MainActivity.this, UPLOAD_URL);
request.setMethod("POST");
request.addParameter("par1","1");
request.addHeader("hed","val");
request.addFileToUpload(filePath, "image_url");
request.setNotificationConfig(createNotificationChannel());
//request.setMaxRetries(2);
request.startUpload(); //Starting the upload
} catch (Exception exc) {
Toast.makeText(this, exc.getMessage(), Toast.LENGTH_SHORT).show();
}
}
private Function2<? super Context, ? super String, UploadNotificationConfig> createNotificationChannel() {
Function2<? super Context, ? super String, UploadNotificationConfig> test = null;
// Create the NotificationChannel, but only on API 26+ because
// the NotificationChannel class is new and not in the support library
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
Toast.makeText(this, "Build.VERSION.SDK_INT : YES", Toast.LENGTH_SHORT).show();
CharSequence name = getString(R.string.channel_name);
String description = getString(R.string.channel_description);
int importance = NotificationManager.IMPORTANCE_DEFAULT;
NotificationChannel channel = new NotificationChannel("UploadJSON", name, importance);
channel.setDescription(description);
// Register the channel with the system; you can't change the importance
// or other notification behaviors after this
NotificationManager notificationManager = getSystemService(NotificationManager.class);
notificationManager.createNotificationChannel(channel);
UploadNotificationStatusConfig uploadNotificationStatusConfig = new UploadNotificationStatusConfig("Upload JSON",
"uploading...");
UploadNotificationStatusConfig uploadNotificationStatusConfigSucces = new UploadNotificationStatusConfig("Upload JSON",
"finished!");
UploadNotificationStatusConfig uploadNotificationStatusConfigError = new UploadNotificationStatusConfig("Upload JSON",
"Error!");
UploadNotificationStatusConfig uploadNotificationStatusConfigCancele = new UploadNotificationStatusConfig("Upload JSON",
"Canceled");
uploadNotificationConfig = new UploadNotificationConfig("UploadJSON",
true,
uploadNotificationStatusConfig,uploadNotificationStatusConfigSucces,
uploadNotificationStatusConfigError,
uploadNotificationStatusConfigCancele
);
test = new Function2<Context, String, UploadNotificationConfig>() {
#Override
public UploadNotificationConfig invoke(Context context, String s) {
return uploadNotificationConfig;
}
};
}else{
}
return test;
}
now call uploadJSONFile().
you can use retrofit's Multipart.Body for image uploading to server. This link will guide you how to upload files using multipart.
Related
I have a profile picture concept in my app. User has options to upload an image from camera or gallery in the app but the problem is the image is being uploaded to some devices not all. Mainly the problem occurs with Android version 8 & 9. I tried almost everything but failed to achieve. Please help.
Code:
dialog = new Dialog(getActivity());
dialog.setContentView(R.layout.dialog_image_upload);
dialog.setCanceledOnTouchOutside(false);
dialog.getWindow().setBackgroundDrawableResource(android.R.color.transparent);
TextView txtTakePhoto = (TextView) dialog.findViewById(R.id.txtTakePhoto);
TextView txtPictureFromGallery = (TextView) dialog.findViewById(R.id.txtPictureFromGallery);
ImageView imgClose = (ImageView) dialog.findViewById(R.id.imgClose);
imgClose.setOnClickListener(this);
txtTakePhoto.setOnClickListener(this);
txtPictureFromGallery.setOnClickListener(this)
Code for take photo from camera:
case R.id.txtTakePhoto:
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
if (ActivityCompat.checkSelfPermission(getActivity(), Manifest.permission.CAMERA) == PackageManager.PERMISSION_GRANTED) {
{
cameraIntent();
}
} else {
if (ActivityCompat.shouldShowRequestPermissionRationale(getActivity(), Manifest.permission.CAMERA)) {
Toast.makeText(getActivity(), "App requires Phone permission.\nPlease allow that in the device settings.", Toast.LENGTH_LONG).show();
}
ActivityCompat.requestPermissions(getActivity(), new String[]{Manifest.permission.CAMERA}, PHONE_PERMISSION_CODE);
}
} else {
cameraIntent();
}
break;
Code for take photo from gallery:
case R.id.txtPictureFromGallery:
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
if (ActivityCompat.checkSelfPermission(getActivity(), Manifest.permission.READ_EXTERNAL_STORAGE) == PackageManager.PERMISSION_GRANTED) {
{
imageBrowse();
}
} else {
if (ActivityCompat.shouldShowRequestPermissionRationale(getActivity(), Manifest.permission.READ_EXTERNAL_STORAGE)) {
Toast.makeText(getActivity(), "App requires Phone permission.\nPlease allow that in the device settings.", Toast.LENGTH_LONG).show();
}
ActivityCompat.requestPermissions(getActivity(), new String[]{Manifest.permission.READ_EXTERNAL_STORAGE}, PHONE_PERMISSION_CODE);
}
} else {
imageBrowse();
}
break;
Pending code for image uploading :
private void cameraIntent() {
Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
startActivityForResult(intent, REQUEST_CAMERA);
}
private void imageBrowse() {
Intent galleryIntent = new Intent(Intent.ACTION_PICK, MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
startActivityForResult(galleryIntent, PICK_IMAGE_REQUEST);
}
//handling the image chooser activity result
#Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (resultCode == RESULT_OK) {
if (requestCode == PICK_IMAGE_REQUEST) {
onSelectFromGalleryResult(data);
} else if (requestCode == REQUEST_CAMERA) {
onCaptureImageResult(data);
}
}
//
if (requestCode == 2 && resultCode == RESULT_OK && data != null && data.getData() != null) {
Uri DbsUri = data.getData();
fileDbs = FilePath.getPath(getActivity(), DbsUri);
File f1 = new File(fileDbs);
edtCertificatesValue.setText(f1.getName());
Log.e("tag", "filedbs" + fileDbs);
} else if (requestCode == 3 && resultCode == RESULT_OK && data != null && data.getData() != null) {
Uri picUri = data.getData();
filePath = FilePath.getPath(getActivity(), picUri);
File f2 = new File(filePath);
edtIdentityDocumentValue.setText(f2.getName());
Log.e("tag", "filePath" + filePath + " " + f2.getName());
} else if (requestCode == 4 && resultCode == RESULT_OK && data != null && data.getData() != null) {
Uri picUri = data.getData();
fileAddress = FilePath.getPath(getActivity(), picUri);
File f3 = new File(fileAddress);
edtProofOfAddressValue.setText(f3.getName());
Log.e("tag", "fileAddress" + fileAddress);
} else if (requestCode == 5 && resultCode == RESULT_OK && data != null && data.getData() != null) {
Uri CvUri = data.getData();
fileCvPath = FilePath.getPath(getActivity(), CvUri);
File f4 = new File(fileCvPath);
edtCurriculumVitaeValue.setText(f4.getName());
Log.e("tag", "fileCvPath" + fileCvPath);
//
}
//
// } else
}
#SuppressWarnings("deprecation")
private void onSelectFromGalleryResult(Intent data) {
bm = null;
File imageFile = getTempFile(getActivity());
if (data != null) {
try {
bm = MediaStore.Images.Media.getBitmap(getActivity().getContentResolver(), data.getData());
} catch (IOException e) {
e.printStackTrace();
}
}
boolean isCamera = (data == null ||
data.getData() == null ||
data.getData().toString().contains(imageFile.toString()));
if (isCamera) { /* CAMERA */
selectedImageUri = Uri.fromFile(imageFile);
} else { /* ALBUM */
selectedImageUri = data.getData();
}
bm = getImageResized(getActivity(), selectedImageUri);
int rotation = getRotation(getActivity(), selectedImageUri, isCamera);
bm = rotate(bm, rotation);
ByteArrayOutputStream bytes1 = new ByteArrayOutputStream();
bm.compress(Bitmap.CompressFormat.JPEG, 99, bytes1);
byte[] byteImage = bytes1.toByteArray();
encodeImage = Base64.encodeToString(byteImage, Base64.DEFAULT);
imgProfile.setImageBitmap(bm);
Uri picUri = data.getData();
Log.e("TAG", "onSelectFromGalleryResult: " + bm);
fileImagePath = getPath(picUri);
if (fileImagePath != null) {
try {
} catch (Exception e) {
e.printStackTrace();
}
} else {
Toast.makeText(getActivity(), R.string.some_error_occured, Toast.LENGTH_LONG).show();
}
dialog.dismiss();
}
private String getPath(Uri contentUri) {
String[] proj = {MediaStore.Images.Media.DATA};
CursorLoader loader = new CursorLoader(getActivity(), contentUri, proj, null, null, null);
Cursor cursor = loader.loadInBackground();
int column_index = cursor.getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
cursor.moveToFirst();
String result = cursor.getString(column_index);
cursor.close();
return result;
}
// new code
private static File getTempFile(Context context) {
File imageFile = new File(context.getExternalCacheDir(), TEMP_IMAGE_NAME);
imageFile.getParentFile().mkdirs();
return imageFile;
}
private void onCaptureImageResult(Intent data) {
Bitmap thumbnail = (Bitmap) data.getExtras().get("data");
ByteArrayOutputStream bytes1 = new ByteArrayOutputStream();
thumbnail.compress(Bitmap.CompressFormat.JPEG, 99, bytes1);
byte[] byteImage = bytes1.toByteArray();
encodeImage = Base64.encodeToString(byteImage, Base64.DEFAULT);
File destination = new File(Environment.getExternalStorageDirectory(),
System.currentTimeMillis() + ".jpg");
Log.d("TAG", "onActivityResult: " + Uri.fromFile(destination));
try {
rotateImageIfRequired(thumbnail, getActivity(), Uri.fromFile(destination));
} catch (Exception e) {
e.printStackTrace();
}
Log.d("TAG", "thumbnail: " + thumbnail);
imgProfile.setImageBitmap(thumbnail);
FileOutputStream fo;
try {
destination.createNewFile();
fo = new FileOutputStream(destination);
fo.write(bytes1.toByteArray());
fo.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
fileImagePath = destination.toString();
if (fileImagePath != null) {
try {
// execMultipartPost();
} catch (Exception e) {
e.printStackTrace();
}
} else {
Toast.makeText(getActivity(), getResources().getString(R.string.some_error_occured), Toast.LENGTH_LONG).show();
}
dialog.dismiss();
}
//This method will be called when the user will tap on allow or deny
#Override
public void onRequestPermissionsResult(int requestCode, #NonNull String[] permissions, #NonNull int[] grantResults) {
//Checking the request code of our request
if (requestCode == STORAGE_PERMISSION_CODE) {
//If permission is granted
if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
//Displaying a toast
Toast.makeText(getActivity(), "Permission granted now you can read the storage", Toast.LENGTH_LONG).show();
} else {
//Displaying another toast if permission is not granted
Toast.makeText(getActivity(), "Oops you just denied the permission", Toast.LENGTH_LONG).show();
}
}
}
API hit Code:
private void execMultipartPost() throws Exception {
RequestBody requestBody;
pBar.setVisibility(View.VISIBLE);
final HashMap<String, String> loggedDetail = sessionManager.getLoggedDetail();
HashMap<String, String> params = new HashMap<String, String>();
String api_token = loggedDetail.get("api_token");
if (filePath != null) {
File file = new File(filePath);
String contentType = file.toURL().openConnection().getContentType();
fileBody = RequestBody.create(MediaType.parse(contentType), file);
filename = "file_" + System.currentTimeMillis() / 1000L;
Log.e("TAG", "filename: " + filename);
requestBody = new MultipartBody.Builder()
.setType(MultipartBody.FORM)
.addFormDataPart("image_file", filename + ".jpg", fileBody)
.addFormDataPart("name", edtName.getText().toString())
.addFormDataPart("user_id", loggedDetail.get("id"))
.addFormDataPart("email", edtEmailValue.getText().toString())
.addFormDataPart("postal_code", edtPostCodeValue.getText().toString())
.addFormDataPart("phone", edtPhoneNumber.getText().toString())
.addFormDataPart("type", loggedDetail.get("type"))
.addFormDataPart("address", edtAddressValue.getText().toString())
.addFormDataPart("gender", edtGenderValue.getText().toString())
.addFormDataPart("skype_id", edtSkypeNameIdValue.getText().toString())
.build();
} else {
requestBody = new MultipartBody.Builder()
.setType(MultipartBody.FORM)
.addFormDataPart("image_file", "")
.addFormDataPart("name", edtName.getText().toString())
.addFormDataPart("user_id", loggedDetail.get("id"))
.addFormDataPart("email", edtEmailValue.getText().toString())
.addFormDataPart("postal_code", edtPostCodeValue.getText().toString())
.addFormDataPart("phone", edtPhoneNumber.getText().toString())
.addFormDataPart("type", loggedDetail.get("type"))
.addFormDataPart("address", edtAddressValue.getText().toString())
.addFormDataPart("gender", edtGenderValue.getText().toString())
.addFormDataPart("skype_id", edtSkypeNameIdValue.getText().toString())
.build();
}
okhttp3.Request request = new okhttp3.Request.Builder()
.url(Constants.EDIT_PROFILE_DATA)
.post(requestBody)
.addHeader("Authorization", "Bearer " + loggedDetail.get("api_token"))
.build();
OkHttpClient okHttpClient = new OkHttpClient.Builder()
.connectTimeout(150, TimeUnit.SECONDS)
.writeTimeout(10, TimeUnit.SECONDS)
.readTimeout(30, TimeUnit.SECONDS)
.build();
okHttpClient.newCall(request).enqueue(new Callback() {
#Override
public void onFailure(Call call, final IOException e) {
getActivity().runOnUiThread(new Runnable() {
#Override
public void run() {
pBar.setVisibility(View.GONE);
Toast.makeText(getActivity(), R.string.some_error_occured, Toast.LENGTH_SHORT).show();
e.printStackTrace();
}
});
}
#Override
public void onResponse(Call call, final okhttp3.Response response) throws IOException {
getActivity().runOnUiThread(new Runnable() {
#Override
public void run() {
Yes, you need to configure the FileProvider. In your app's manifest, add a provider to your application:
<application>
...
<provider
android:name="android.support.v4.content.FileProvider"
android:authorities="com.example.android.fileprovider"
android:exported="false"
android:grantUriPermissions="true">
<meta-data
android:name="android.support.FILE_PROVIDER_PATHS"
android:resource="#xml/file_paths"></meta-data>
</provider>
...
</application>
Make sure that the authorities string matches the second argument to getUriForFile(Context, String, File). In the meta-data section of the provider definition, you can see that the provider expects eligible paths to be configured in a dedicated resource file, res/xml/file_paths.xml. Here is the content required for this particular example:
<?xml version="1.0" encoding="utf-8"?>
<paths xmlns:android="http://schemas.android.com/apk/res/android">
<external-path name="my_images" path="Android/data/com.example.package.name/files/Pictures" />
</paths>
Read the android documentation https://developer.android.com/training/camera/photobasics
I have uploaded a PDF file to the server but I am not able to get the path from sd card in Marshmallow. Could someone help and figure out what the issue is?
but_browse is the button for browsing the files and after browsing I have given an upload button to upload the PDF to the server.
but_browse.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
//sets the select file to all types of files
Intent intent = new Intent(Intent.ACTION_GET_CONTENT);
intent.setType("*/*");
intent.addCategory(Intent.CATEGORY_OPENABLE);
intent.setType("application/pdf");
//intent.putExtra("browseCoa", itemToBrowse);
//Intent chooser = Intent.createChooser(intent, "Select a File to Upload");
try {
//startActivityForResult(chooser, FILE_SELECT_CODE);
startActivityForResult(Intent.createChooser(intent, "Select a File to Upload"), 1);
} catch (Exception ex) {
System.out.println("browseClick :" + ex);//android.content.ActivityNotFoundException ex
}
}
});
onActivityResult() method:
#Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (resultCode == RESULT_OK) {
// if (requestCode == 1) {
Uri uri = data.getData();
String uriString = uri.toString();
// uploadedFileName = file.getName().toString();
if (Build.VERSION.SDK_INT == Build.VERSION_CODES.M) {
File myFile = new File(uriString);
// selectedFilePath2 = PathUtils.getPath(getActivity(), uri );
System.out.println(">>>>>>>>>>>>>>>>>>>>selectedFilePath2"+ getApplicationContext().getFilesDir().getPath());
// System.out.println(">>>>>>>>>>>>>>>>>>>>file.getName()" + file.getName());
// file_name = file.getName();
// Log.i("", "File : " + file.getName());
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
File[] externalCacheDirs = getActivity().getExternalCacheDirs();
String[] f = getExternalStorageDirectories();
System.out.println(">>>>>>>>>>>>>>>>>>>>selectedFilePath3" + f );
for (File file : externalCacheDirs) {
if (Environment.isExternalStorageRemovable(file)) {
// Path is in format /storage.../Android....
// Get everything before /Android
selectedFilePath2 = file.getPath().split("/Android")[0];
System.out.println(">>>>>>>>>>>>>>>>>>>>selectedFilePath2" + selectedFilePath2 );
break;
}
}
selectedFilePath2 = myFile.getAbsolutePath();
System.out.println(">>>>>>>>>>>>>>>>>>>>selectedFilePath2" + selectedFilePath2 );
}
}
if (Build.VERSION.SDK_INT == Build.VERSION_CODES.N) {
File myFile = new File(uriString);
selectedFilePath2 = PathUtils.getPath(getActivity(), uri );
System.out.println(">>>>>>>>>>>>>>>>>>>>selectedFilePath2" + selectedFilePath2);
System.out.println(">>>>>>>>>>>>>>>>>>>>selectedFilePath2"+ getApplicationContext().getFilesDir().getPath());
// System.out.println(">>>>>>>>>>>>>>>>>>>>file.getName()" + file.getName());
// file_name= file.getName();
// Log.i("", "File : " + file.getName());
} else {
file = new File(uri.getPath().toString());
selectedFilePath2 = Vis_FilePath.getPath(getActivity(), uri) ;
System.out.println(">>>>>>>>>>>>>>>>>>>>file.getName()" + file.getName());
file_name= file.getName();
Log.i("", "File : " + file.getName());
}
}
}
Upload to server:
private void uploadpdf() throws IOException {
String charset = "UTF-8";
byte[] data = null;
File filessss = new File(selectedFilePath2);
try {
data = FileUtils.readFileToByteArray(filessss);
pdf = Base64.encodeToString(data, Base64.DEFAULT);
} catch (IOException e) {
e.printStackTrace();
}
final ProgressDialog loading = ProgressDialog.show(getActivity(),"Uploading...","Please wait...",false,false);
StringRequest stringRequest = new StringRequest(Request.Method.POST, Config.URL_CV,
new Response.Listener<String>() {
#Override
public void onResponse(String s) {
//Dismissing the progress dialog
loading.dismiss();
//Showing toast message of the response
Toast.makeText(getActivity(), s , Toast.LENGTH_LONG).show();
}
},
new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError volleyError) {
//Dismissing the progress dialog
loading.dismiss();
//Showing toast
Toast.makeText(getActivity(), volleyError.getMessage().toString(), Toast.LENGTH_LONG).show();
}
}){
#Override
protected Map<String, String> getParams() throws AuthFailureError {
//Converting Bitmap to String
//Creating parameters
Map<String,String> params = new Hashtable<String, String>();
SharedPreferences prefs = getActivity().getSharedPreferences(Config.SHARED_PREF_NAME, Context.MODE_PRIVATE);
String userid = prefs.getString("userId","");
//Adding parameters
params.put("user_id",userid);
params.put("attachment",pdf);
//returning parameters
return params;
}
};
//Creating a Request Queue
RequestQueue requestQueue = Volley.newRequestQueue(getActivity());
//Adding request to the queue
requestQueue.add(stringRequest);
}
Did you checked permission on manifest file? I had similar problem before because I didn't wrote these.
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
And used PackageManager to check required permission are granted.
I get some help from here : https://www.captechconsulting.com/blogs/runtime-permissions-best-practices-and-how-to-gracefully-handle-permission-removal
I am new to Android application development. Using iText I had done the PDF creation and write on that created file now I want to create image to PDF from my `ImageView. Here's my code :
public class PdfCreatorActivity extends AppCompatActivity {
private static final String TAG = "PdfCreatorActivity";
private EditText mContentEditText;
private Button mCreateButton;
private File pdfFile;
final private int REQUEST_CODE_ASK_PERMISSIONS = 111;
Intent intent;
Uri fileUri;
Button btn_choose_image;
ImageView imageView;
Bitmap bitmap, decoded;
public final int REQUEST_CAMERA = 0;
public final int SELECT_FILE = 1;
int bitmap_size = 40; // image quality 1 - 100;
int max_resolution_image = 800;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_pdfcreator);
btn_choose_image = (Button) findViewById(R.id.btn_choose_image);
imageView = (ImageView) findViewById(R.id.image_view);
btn_choose_image.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
selectImage();
}
});
mContentEditText = (EditText) findViewById(R.id.edit_text_content);
mCreateButton = (Button) findViewById(R.id.button_create);
mCreateButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (mContentEditText.getText().toString().isEmpty()){
mContentEditText.setError("Body is empty");
mContentEditText.requestFocus();
return;
}
try {
createPdfWrapper();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (DocumentException e) {
e.printStackTrace();
}
}
});
}
private void selectImage() {
imageView.setImageResource(0);
final CharSequence[] items = {"Take Photo", "Choose from Library", "Cancel"};
android.app.AlertDialog.Builder builder = new android.app.AlertDialog.Builder(PdfCreatorActivity.this);
builder.setTitle("Add Photo!");
builder.setIcon(R.mipmap.ic_launcher);
builder.setItems(items, new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int item) {
if (items[item].equals("Take Photo")) {
intent = new Intent(android.provider.MediaStore.ACTION_IMAGE_CAPTURE);
fileUri = getOutputMediaFileUri();
intent.putExtra(android.provider.MediaStore.EXTRA_OUTPUT, fileUri);
startActivityForResult(intent, REQUEST_CAMERA);
} else if (items[item].equals("Choose from Library")) {
intent = new Intent();
intent.setType("image/*");
intent.setAction(Intent.ACTION_GET_CONTENT);
startActivityForResult(Intent.createChooser(intent, "Select Picture"), SELECT_FILE);
} else if (items[item].equals("Cancel")) {
dialog.dismiss();
}
}
});
builder.show();
}
public void onActivityResult(int requestCode, int resultCode, Intent data) {
Log.e("onActivityResult", "requestCode " + requestCode + ", resultCode " + resultCode);
if (resultCode == Activity.RESULT_OK) {
if (requestCode == REQUEST_CAMERA) {
try {
Log.e("CAMERA", fileUri.getPath());
bitmap = BitmapFactory.decodeFile(fileUri.getPath());
setToImageView(getResizedBitmap(bitmap, max_resolution_image));
} catch (Exception e) {
e.printStackTrace();
}
} else if (requestCode == SELECT_FILE && data != null && data.getData() != null) {
try {
// mengambil gambar dari Gallery
bitmap = MediaStore.Images.Media.getBitmap(PdfCreatorActivity.this.getContentResolver(), data.getData());
setToImageView(getResizedBitmap(bitmap, max_resolution_image));
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
// Untuk menampilkan bitmap pada ImageView
private void setToImageView(Bitmap bmp) {
//compress image
ByteArrayOutputStream bytes = new ByteArrayOutputStream();
bmp.compress(Bitmap.CompressFormat.JPEG, bitmap_size, bytes);
decoded = BitmapFactory.decodeStream(new ByteArrayInputStream(bytes.toByteArray()));
//menampilkan gambar yang dipilih dari camera/gallery ke ImageView
imageView.setImageBitmap(decoded);
}
// Untuk resize bitmap
public Bitmap getResizedBitmap(Bitmap image, int maxSize) {
int width = image.getWidth();
int height = image.getHeight();
float bitmapRatio = (float) width / (float) height;
if (bitmapRatio > 1) {
width = maxSize;
height = (int) (width / bitmapRatio);
} else {
height = maxSize;
width = (int) (height * bitmapRatio);
}
return Bitmap.createScaledBitmap(image, width, height, true);
}
public Uri getOutputMediaFileUri() {
return Uri.fromFile(getOutputMediaFile());
}
private static File getOutputMediaFile() {
// External sdcard location
File mediaStorageDir = new File(Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES), "DeKa");
// Create the storage directory if it does not exist
if (!mediaStorageDir.exists()) {
if (!mediaStorageDir.mkdirs()) {
Log.e("Monitoring", "Oops! Failed create Monitoring directory");
return null;
}
}
// Create a media file name
String timeStamp = new SimpleDateFormat("yyyyMMdd_HHmmss", Locale.getDefault()).format(new Date());
File mediaFile;
mediaFile = new File(mediaStorageDir.getPath() + File.separator + "IMG_DeKa_" + timeStamp + ".jpg");
return mediaFile;
}
}
This Code for Create PDF
private void createPdfWrapper() throws FileNotFoundException,DocumentException{
int hasWriteStoragePermission = ActivityCompat.checkSelfPermission(this, Manifest.permission.WRITE_EXTERNAL_STORAGE);
if (hasWriteStoragePermission != PackageManager.PERMISSION_GRANTED) {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
if (!shouldShowRequestPermissionRationale(Manifest.permission.WRITE_CONTACTS)) {
showMessageOKCancel("You need to allow access to Storage",
new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
requestPermissions(new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE},
REQUEST_CODE_ASK_PERMISSIONS);
}
}
});
return;
}
requestPermissions(new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE},
REQUEST_CODE_ASK_PERMISSIONS);
}
return;
}else {
createPdf();
}
}
#Override
public void onRequestPermissionsResult(int requestCode, String[] permissions, int[] grantResults) {
switch (requestCode) {
case REQUEST_CODE_ASK_PERMISSIONS:
if (grantResults[0] == PackageManager.PERMISSION_GRANTED) {
// Permission Granted
try {
createPdfWrapper();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (DocumentException e) {
e.printStackTrace();
}
} else {
// Permission Denied
Toast.makeText(this, "WRITE_EXTERNAL Permission Denied", Toast.LENGTH_SHORT)
.show();
}
break;
default:
super.onRequestPermissionsResult(requestCode, permissions, grantResults);
}
}
private void showMessageOKCancel(String message, DialogInterface.OnClickListener okListener) {
new AlertDialog.Builder(this)
.setMessage(message)
.setPositiveButton("OK", okListener)
.setNegativeButton("Cancel", null)
.create()
.show();
}
private void createPdf() throws FileNotFoundException, DocumentException {
File docsFolder = new File(Environment.getExternalStorageDirectory() + "/Documents");
if (!docsFolder.exists()) {
docsFolder.mkdir();
Log.i(TAG, "Created a new directory for PDF");
}
pdfFile = new File(docsFolder.getAbsolutePath(),"HelloWorld.pdf");
OutputStream output = new FileOutputStream(pdfFile);
Document document = new Document();
PdfWriter.getInstance(document, output);
document.open();
document.add(new Paragraph(mContentEditText.getText().toString()));
document.close();
previewPdf();
}
private void previewPdf() {
PackageManager packageManager = getPackageManager();
Intent testIntent = new Intent(Intent.ACTION_VIEW);
testIntent.setType("application/pdf");
List list = packageManager.queryIntentActivities(testIntent, PackageManager.MATCH_DEFAULT_ONLY);
if (list.size() > 0) {
Intent intent = new Intent();
intent.setAction(Intent.ACTION_VIEW);
Uri uri = Uri.fromFile(pdfFile);
intent.setDataAndType(uri, "application/pdf");
startActivity(intent);
}else{
Toast.makeText(this,"Download a PDF Viewer to see the generated PDF",Toast.LENGTH_SHORT).show();
}
}
I don't know how to implement image can generates to PDF using iText,
Examples will be appreciable...
thanks in advance.
Use PdfDocument to generate pdf form View.
This class enables generating a PDF document from native Android content
Sample code:
// Create a new document
PdfDocument document = new PdfDocument();
// crate a page description
PageInfo pageInfo = new PageInfo.Builder(view.getWidth(), view.getHeight(), 1).create();
// start a page
Page page = document.startPage(pageInfo);
// draw on page
view.draw(page.getCanvas());
// finish the page
document.finishPage(page);
// generate pdf
new PdfGenerationTask().execute();
Use AsyncTask to generate pdf form document
private class PdfGenerationTask extends AsyncTask<Void, Void, File> {
#Override
protected void onPreExecute() {
super.onPreExecute();
}
#Override
protected File doInBackground(Void... params) {
return generatePdf();
}
#Override
protected void onPostExecute(File file) {
/* Dismiss the progress dialog after sharing */
}
}
generatePdf method
private File generatePdf(){
SimpleDateFormat sdf = new SimpleDateFormat("ddMMyyyyhhmmss");
String pdfName = "pdf"
+ sdf.format(Calendar.getInstance().getTime()) + ".pdf";
String path = Environment.getExternalStorageDirectory().getAbsolutePath() + "/Pdf";
File dir = new File(path);
if(!dir.exists())
dir.mkdirs();
File file = new File(dir, pdfName);
if( document != null ){
// write the document content
try {
OutputStream out = new FileOutputStream(file);
if( out != null ){
document.writeTo(out);
// close the document
document.close();
out.close();
}
} catch (IOException e) {
e.printStackTrace();
}
}
return file;
}
PdfDocument is easy and simple to use. PdfDocument required min sdk 19
Im getting this error, when click deny permission in "Allow app to access photos, media and files on your device ? "
FATAL EXCEPTION: main
Process: com.viantti.app, PID: 12349
java.lang.NullPointerException: file
at android.net.Uri.fromFile(Uri.java:452)
at com.viantti.app.ProfilePage.getOutputMediaFileUri(ProfilePage.java:1011)
at com.viantti.app.ProfilePage.takePicture(ProfilePage.java:996)
at com.viantti.app.ProfilePage.access$2800(ProfilePage.java:87)
at com.viantti.app.ProfilePage$25.onClick(ProfilePage.java:1522)
at android.view.View.performClick(View.java:5205)
at android.view.View$PerformClick.run(View.java:21162)
at android.os.Handler.handleCallback(Handler.java:739)
at android.os.Handler.dispatchMessage(Handler.java:95)
at android.os.Looper.loop(Looper.java:148)
at android.app.ActivityThread.main(ActivityThread.java:5468)
at java.lang.reflect.Method.invoke(Native Method)
atcom.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:781)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:671)
java error line,
public Uri getOutputMediaFileUri(int type) {
return Uri.fromFile(getOutputMediaFile(type));
}
When user denies the authorization, you cannot access the media files, you should use this code only if the authorization is accepted
Try the following code, since it will proceed only when all the required permissions has been allowed by the user.
#Override
public void onRequestPermissionsResult(int requestCode, String permissions[], int[] grantResults) {
switch (requestCode) {
case PERMISSION_REQUEST_CODE:
if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED && grantResults[1] == PackageManager.PERMISSION_GRANTED ) {
chooseimage();
} else {
finish();
}
break;
}
}
At first read about Android Runtime Permissions here .
If you deny your app from accessing media you won't be able to take photos.
java code here,
Img_profile_pic.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (Build.VERSION.SDK_INT >= 23) {
// Marshmallow+
if (!checkAccessFineLocationPermission() || !checkWriteExternalStoragePermission()) {
requestPermission();
} else {
chooseimage();
}
} else {
chooseimage();
}
}
});
}
private void takePicture() {
Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
camera_FileUri = getOutputMediaFileUri(1);
intent.putExtra(MediaStore.EXTRA_OUTPUT, camera_FileUri);
// start the image capture Intent
startActivityForResult(intent, REQUEST_TAKE_PHOTO);
}
private void openGallery() {
Intent intent = new Intent(Intent.ACTION_PICK, android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
startActivityForResult(intent, galleryRequestCode);
}
/**
* Creating file uri to store image/video
*/
public Uri getOutputMediaFileUri(int type) {
return Uri.fromFile(getOutputMediaFile(type));
}
/**
* returning image / video
*/
private static File getOutputMediaFile(int type) {
// External sdcard location
File mediaStorageDir = new File(
Environment
.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES), IMAGE_DIRECTORY_NAME);
// Create the storage directory if it does not exist
if (!mediaStorageDir.exists()) {
if (!mediaStorageDir.mkdirs()) {
Log.d(TAG, "Oops! Failed create "
+ IMAGE_DIRECTORY_NAME + " directory");
return null;
}
}
// Create a media file name
String timeStamp = new SimpleDateFormat("yyyyMMdd_HHmmss",
Locale.getDefault()).format(new Date());
File mediaFile;
if (type == 1) {
mediaFile = new File(mediaStorageDir.getPath() + File.separator
+ "IMG_" + timeStamp + ".jpg");
} else {
return null;
}
return mediaFile;
}
#Override
protected void onSaveInstanceState(Bundle outState) {
super.onSaveInstanceState(outState);
// save file url in bundle as it will be null on screen orientation
// changes
outState.putParcelable("file_uri", camera_FileUri);
}
#Override
protected void onRestoreInstanceState(Bundle savedInstanceState) {
super.onRestoreInstanceState(savedInstanceState);
// get the file url
camera_FileUri = savedInstanceState.getParcelable("file_uri");
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (resultCode == RESULT_OK) {
if (requestCode == REQUEST_TAKE_PHOTO || requestCode == UCrop.REQUEST_CROP) {
try {
if (requestCode == REQUEST_TAKE_PHOTO) {
BitmapFactory.Options options = new BitmapFactory.Options();
options.inSampleSize = 8;
final Bitmap bitmap = BitmapFactory.decodeFile(camera_FileUri.getPath(), options);
Bitmap thumbnail = bitmap;
final String picturePath = camera_FileUri.getPath();
// ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
File curFile = new File(picturePath);
try {
ExifInterface exif = new ExifInterface(curFile.getPath());
int rotation = exif.getAttributeInt(ExifInterface.TAG_ORIENTATION, ExifInterface.ORIENTATION_NORMAL);
int rotationInDegrees = exifToDegrees(rotation);
Matrix matrix = new Matrix();
if (rotation != 0f) {
matrix.preRotate(rotationInDegrees);
}
// thumbnail = Bitmap.createBitmap(thumbnail, 0, 0, thumbnail.getWidth(), thumbnail.getHeight(), matrix, true);
} catch (IOException ex) {
Log.e("TAG", "Failed to get Exif data", ex);
}
System.out.println("edit-----" + Iconstant.Edit_profile_image_url);
Uri picUri = Uri.fromFile(curFile);
UCrop.of(picUri, picUri)
.withAspectRatio(4, 4)
.withMaxResultSize(8000, 8000)
.start(ProfilePage.this);
}
} catch (Exception e) {
e.printStackTrace();
}
} else if (requestCode == galleryRequestCode) {
Uri selectedImage = data.getData();
if (selectedImage.toString().startsWith("content://com.sec.android.gallery3d.provider")) {
String[] filePath = {MediaStore.Images.Media.DATA};
Cursor c = getContentResolver().query(selectedImage, filePath, null, null, null);
c.moveToFirst();
int columnIndex = c.getColumnIndex(filePath[0]);
final String picturePath = c.getString(columnIndex);
c.close();
File curFile = new File(picturePath);
Picasso.with(ProfilePage.this).load(picturePath).resize(100, 100).into(new Target() {
#Override
public void onBitmapLoaded(Bitmap bitmap, Picasso.LoadedFrom from) {
Bitmap thumbnail = bitmap;
mSelectedFilePath = picturePath;
ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
thumbnail.compress(Bitmap.CompressFormat.JPEG, 70, byteArrayOutputStream);
}
#Override
public void onBitmapFailed(Drawable errorDrawable) {
}
#Override
public void onPrepareLoad(Drawable placeHolderDrawable) {
}
});
Uri picUri = Uri.fromFile(curFile);
UCrop.of(picUri, picUri)
.withAspectRatio(4, 4)
.withMaxResultSize(8000, 8000)
.start(ProfilePage.this);
} else {
String[] filePath = {MediaStore.Images.Media.DATA};
Cursor c = getContentResolver().query(selectedImage, filePath, null, null, null);
c.moveToFirst();
int columnIndex = c.getColumnIndex(filePath[0]);
final String picturePath = c.getString(columnIndex);
Bitmap bitmap = BitmapFactory.decodeFile(picturePath);
Bitmap thumbnail = bitmap; //getResizedBitmap(bitmap, 600);
ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
File curFile = new File(picturePath);
try {
ExifInterface exif = new ExifInterface(curFile.getPath());
int rotation = exif.getAttributeInt(ExifInterface.TAG_ORIENTATION, ExifInterface.ORIENTATION_NORMAL);
int rotationInDegrees = exifToDegrees(rotation);
Matrix matrix = new Matrix();
if (rotation != 0f) {
matrix.preRotate(rotationInDegrees);
}
thumbnail = Bitmap.createBitmap(thumbnail, 0, 0, thumbnail.getWidth(), thumbnail.getHeight(), matrix, true);
} catch (IOException ex) {
Log.e("TAG", "Failed to get Exif data", ex);
}
thumbnail.compress(Bitmap.CompressFormat.JPEG, 70, byteArrayOutputStream);
c.close();
Uri picUri = Uri.fromFile(curFile);
UCrop.of(picUri, picUri)
.withAspectRatio(4, 4)
.withMaxResultSize(8000, 8000)
.start(ProfilePage.this);
}
}
if ( requestCode == UCrop.REQUEST_CROP) {
final Uri resultUri = UCrop.getOutput(data);
try {
selectedBitmap = MediaStore.Images.Media.getBitmap(this.getContentResolver(), resultUri);
} catch (IOException e) {
e.printStackTrace();
}
ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
selectedBitmap.compress(Bitmap.CompressFormat.JPEG, 70, byteArrayOutputStream);
byteArray = byteArrayOutputStream.toByteArray();
Img_profile_pic.setImageBitmap(selectedBitmap);
Img_profile_pic.setImageURI(resultUri);
UploadDriverImage(Iconstant.Edit_profile_image_url);
} else if (resultCode == UCrop.RESULT_ERROR) {
final Throwable cropError = UCrop.getError(data);
System.out.println("========muruga cropError==========="+cropError);
}
}
}
private static int exifToDegrees(int exifOrientation) {
if (exifOrientation == ExifInterface.ORIENTATION_ROTATE_90) {
return 90;
} else if (exifOrientation == ExifInterface.ORIENTATION_ROTATE_180) {
return 180;
} else if (exifOrientation == ExifInterface.ORIENTATION_ROTATE_270) {
return 270;
}
return 0;
}
private void UploadDriverImage(String url) {
dialog = new Dialog(ProfilePage.this);
dialog.getWindow();
dialog.requestWindowFeature(Window.FEATURE_NO_TITLE);
dialog.setContentView(R.layout.custom_loading);
dialog.setCanceledOnTouchOutside(false);
dialog.show();
TextView dialog_title = (TextView) dialog.findViewById(R.id.custom_loading_textview);
dialog_title.setText(getResources().getString(R.string.action_loading));
VolleyMultipartRequest multipartRequest = new VolleyMultipartRequest(Request.Method.POST, url, new Response.Listener<NetworkResponse>() {
#Override
public void onResponse(NetworkResponse response) {
System.out.println("------------- image response-----------------"+response.data);
String resultResponse = new String(response.data);
System.out.println("------------- response-----------------"+resultResponse);
String sStatus = "", sResponse = "",SUser_image="",Smsg="";
try {
JSONObject jsonObject = new JSONObject(resultResponse);
sStatus = jsonObject.getString("status");
if (sStatus.equalsIgnoreCase("1")) {
// JSONObject responseObject = jsonObject.getJSONObject("response");
// SUser_image = jsonObject.getString("image");
Smsg = jsonObject.getString("image_url");
// Img_profile_pic.setImageBitmap(bitMapThumbnail);
session.setuser_image(Smsg);
Picasso.with(ProfilePage.this).load(Smsg).placeholder(R.drawable.no_user_image).into(Img_profile_pic);
NavigationDrawer.navigationNotifyChange();
Locale locale = null;
switch (language_code){
case "en":
locale = new Locale("en");
session.setlamguage("en","en");
break;
case "es":
locale = new Locale("es");
session.setlamguage("es","es");
// session.setlamguage("Ar",language_change.getSelectedItem().toString());
// System.out.println("========Arabic Language========"+language_change.getSelectedItem().toString()+"\t\tar");
// Intent i=new Intent(ProfilePage.this,NavigationDrawer.class);
// finish();
// startActivity(i);
// Intent bii = new Intent();
// bii.setAction("homepage");
// sendBroadcast(bii);
// finish();
break;
case "ta":
locale = new Locale("ta");
session.setlamguage("ta","ta");
// session.setlamguage("Ar",language_change.getSelectedItem().toString());
// System.out.println("========Arabic Language========"+language_change.getSelectedItem().toString()+"\t\tar");
// Intent i=new Intent(ProfilePage.this,NavigationDrawer.class);
// finish();
// startActivity(i);
// Intent bii = new Intent();
// bii.setAction("homepage");
// sendBroadcast(bii);
// finish();
break;
default:
locale = new Locale("en");
session.setlamguage("en","en");
break;
}
Locale.setDefault(locale);
Configuration config = new Configuration();
config.locale = locale;
getApplicationContext().getResources().updateConfiguration(config, getApplicationContext().getResources().getDisplayMetrics());
Alert(getResources().getString(R.string.action_success),getResources().getString(R.string.edit_profile_success_label));
} else {
sResponse = jsonObject.getString("response");
Alert(getResources().getString(R.string.my_rides_rating_header_sorry_textview), sResponse);
}
} catch (JSONException e) {
e.printStackTrace();
}
catch (Exception e) {
Toast.makeText(ProfilePage.this,"Something happened , try again",Toast.LENGTH_LONG).show();
e.printStackTrace();
}
dialog.dismiss();
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
dialog.dismiss();
NetworkResponse networkResponse = error.networkResponse;
String errorMessage = "Unknown error";
if (networkResponse == null) {
if (error.getClass().equals(TimeoutError.class)) {
errorMessage = "Request timeout";
} else if (error.getClass().equals(NoConnectionError.class)) {
errorMessage = "Failed to connect server";
}
} else {
String result = new String(networkResponse.data);
try {
JSONObject response = new JSONObject(result);
String status = response.getString("status");
String message = response.getString("message");
Log.e("Error Status", status);
Log.e("Error Message", message);
if (networkResponse.statusCode == 404) {
errorMessage = "Resource not found";
} else if (networkResponse.statusCode == 401) {
errorMessage = message + " Please login again";
} else if (networkResponse.statusCode == 400) {
errorMessage = message + " Check your inputs";
} else if (networkResponse.statusCode == 500) {
errorMessage = message + " Something is getting wrong";
}
} catch (JSONException e) {
e.printStackTrace();
}
}
Log.i("Error", errorMessage);
error.printStackTrace();
}
}) {
#Override
public Map<String, String> getHeaders() throws AuthFailureError {
System.out.println("------------Authkey------cabily---------" + Agent_Name);
System.out.println("------------userid----------cabily-----" + UserID);
System.out.println("------------apptoken----------cabily-----" + gcmID);
System.out.println("------------applanguage----------cabily-----" + language_code);
Map<String, String> headers = new HashMap<String, String>();
headers.put("Authkey", Agent_Name);
headers.put("isapplication",Iconstant.cabily_IsApplication);
headers.put("applanguage",language_code);
headers.put("apptype", Iconstant.cabily_AppType);
headers.put("userid",UserID);
headers.put("apptoken",gcmID);
/* System.out.println("servicereques apptype------------------"+Iconstant.cabily_AppType);
System.out.println("servicereques apptoken------------------"+gcmID);
System.out.println("servicereques userid------------------"+UserID);
Map<String, String> headers = new HashMap<String, String>();
headers.put("User-agent",Iconstant.cabily_userAgent);
headers.put("isapplication",Iconstant.cabily_IsApplication);
headers.put("applanguage",Iconstant.cabily_AppLanguage);
headers.put("apptype",Iconstant.cabily_AppType);
headers.put("apptoken",gcmID);
headers.put("userid",UserID);*/
return headers;
}
#Override
protected Map<String, String> getParams() {
Map<String, String> params = new HashMap<>();
params.put("user_id",UserID);
System.out.println("user_id---------------"+UserID);
return params;
}
#Override
protected Map<String, DataPart> getByteData() {
Map<String, DataPart> params = new HashMap<>();
params.put("user_image",new DataPart("cabily_user.jpg", byteArray));
System.out.println("user_image--------edit------"+byteArray);
return params;
}
};
//to avoid repeat request Multiple Time
DefaultRetryPolicy retryPolicy = new DefaultRetryPolicy(0, -1, DefaultRetryPolicy.DEFAULT_BACKOFF_MULT);
multipartRequest.setRetryPolicy(retryPolicy);
multipartRequest.setRetryPolicy(new DefaultRetryPolicy(60000,
DefaultRetryPolicy.DEFAULT_MAX_RETRIES,
DefaultRetryPolicy.DEFAULT_BACKOFF_MULT));
multipartRequest.setShouldCache(false);
AppController.getInstance().addToRequestQueue(multipartRequest);
}
// --------------------Method for choose image to edit profileimage--------------------
private void chooseimage() {
photo_dialog = new Dialog(ProfilePage.this);
photo_dialog.getWindow();
photo_dialog.requestWindowFeature(Window.FEATURE_NO_TITLE);
photo_dialog.setContentView(R.layout.image_upload_dialog);
photo_dialog.setCanceledOnTouchOutside(true);
photo_dialog.getWindow().getAttributes().windowAnimations = R.style.Animations_photo_Picker;
photo_dialog.show();
photo_dialog.getWindow().setGravity(Gravity.CENTER);
RelativeLayout camera = (RelativeLayout) photo_dialog
.findViewById(R.id.profilelayout_takephotofromcamera);
RelativeLayout gallery = (RelativeLayout) photo_dialog
.findViewById(R.id.profilelayout_takephotofromgallery);
camera.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
takePicture();
photo_dialog.dismiss();
}
});
gallery.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
openGallery();
photo_dialog.dismiss();
}
});
}
private boolean checkAccessFineLocationPermission() {
int result = ContextCompat.checkSelfPermission(this, Manifest.permission.CAMERA);
if (result == PackageManager.PERMISSION_GRANTED) {
return true;
} else {
return false;
}
}
private boolean checkAccessCoarseLocationPermission() {
int result = ContextCompat.checkSelfPermission(this, Manifest.permission.CAMERA);
if (result == PackageManager.PERMISSION_GRANTED) {
return true;
} else {
return false;
}
}
private boolean checkWriteExternalStoragePermission() {
int result = ContextCompat.checkSelfPermission(this, Manifest.permission.WRITE_EXTERNAL_STORAGE);
if (result == PackageManager.PERMISSION_GRANTED) {
return true;
} else {
return false;
}
}
private void requestPermission() {
ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.CAMERA,Manifest.permission.WRITE_EXTERNAL_STORAGE}, PERMISSION_REQUEST_CODE);
}
#Override
public void onRequestPermissionsResult(int requestCode, String permissions[], int[] grantResults) {
switch (requestCode) {
case PERMISSION_REQUEST_CODE:
if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED || grantResults[1] == PackageManager.PERMISSION_GRANTED ) {
chooseimage();
} else {
finish();
}
break;
}
}
I want to upload image into the database(c panel) in File format.For doing this at first I select an image from gallery or capture an image,set the image in an imageview and try to pass the image as an input parameter through api. But wont be able to send the image file.
Select image
#Override
public void onRequestPermissionsResult(int requestCode, String[] permissions, int[] grantResults) {
switch (requestCode) {
case Utility.MY_PERMISSIONS_REQUEST_READ_EXTERNAL_STORAGE:
if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
if(userChoosenTask.equals("Take Photo"))
cameraIntent();
else if(userChoosenTask.equals("Choose from Library"))
galleryIntent();
} else {
//code for deny
}
break;
}
}
private void selectImage() {
final CharSequence[] items = { "Take Photo", "Choose from Library", "Cancel" };
AlertDialog.Builder builder = new AlertDialog.Builder(ProfileActivity.this);
builder.setTitle("Add Photo!");
builder.setItems(items, new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int item) {
boolean result=Utility.checkPermission(ProfileActivity.this);
if (items[item].equals("Take Photo")) {
userChoosenTask ="Take Photo";
if(result)
cameraIntent();
} else if (items[item].equals("Choose from Library")) {
userChoosenTask ="Choose from Library";
if(result)
galleryIntent();
} else if (items[item].equals("Cancel")) {
dialog.dismiss();
}
}
});
builder.show();
}
private void galleryIntent()
{
Intent intent = new Intent();
intent.setType("image/*");
intent.setAction(Intent.ACTION_GET_CONTENT);
startActivityForResult(Intent.createChooser(intent, "Select File"),SELECT_FILE);
}
private void cameraIntent()
{
Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
startActivityForResult(intent, REQUEST_CAMERA);
}
#Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (resultCode == Activity.RESULT_OK) {
if (requestCode == SELECT_FILE)
onSelectFromGalleryResult(data);
else if (requestCode == REQUEST_CAMERA)
onCaptureImageResult(data);
}
}
private void onCaptureImageResult(Intent data) {
Bitmap thumbnail = (Bitmap) data.getExtras().get("data");
ByteArrayOutputStream bytes = new ByteArrayOutputStream();
thumbnail.compress(Bitmap.CompressFormat.JPEG, 90, bytes);
File destination = new File(Environment.getExternalStorageDirectory(),
System.currentTimeMillis() + ".jpg");
FileOutputStream fo;
try {
destination.createNewFile();
fo = new FileOutputStream(destination);
fo.write(bytes.toByteArray());
fo.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
iv_profile.setImageBitmap(thumbnail);
ProfileImageAPI api = new ProfileImageAPI(this,this);
api.processProfileImage(AppController.getInstance().userId,destination,"photo.jpg");
}
#SuppressWarnings("deprecation")
private void onSelectFromGalleryResult(Intent data) {
Bitmap bm=null;
if (data != null) {
try {
bm = MediaStore.Images.Media.getBitmap(getApplicationContext().getContentResolver(), data.getData());
} catch (IOException e) {
e.printStackTrace();
}
}
iv_profile.setImageBitmap(bm);
}
}
api.php
function process_updateUserProfileImage()
{
$user_id = isset($_REQUEST['user_id'])?$_REQUEST['user_id']:"";
if($user_id == "" ){
echo json_encode(array("error"=>"1", "error_type"=>"user updateUserProfile", "error_no" => "1009", "error_message" => "Input validation"));
exit;
}
$file_name = "";
$file_url = "";
if($_FILES["profile_image"]["name"]!="")
{
$file_name=time().$_FILES["profile_image"]["name"];
$tmp_name=$_FILES["profile_image"]["tmp_name"];
$file_type=$_FILES['profile_image']['type'];
$file_size=$_FILES['profile_image']['size'];
$upload_dir="../profile_image/";
fileUpload($upload_dir,$file_name,$tmp_name,$file_size,"image");
MakeThumbnail($upload_dir, $file_name ,100,100);
$file_url = SITE_URL.'profile_image/'.$file_name;
}
$sql = "update user set
`profile_image` = '".trim($file_url)."'
where user_id = '".$user_id."'
";
$rs = mysql_query($sql);
/*$userArr = array("success"=>"1", "sucess_type"=>"user registration", "success_message" => "User successfully registered");*/
$userInfo = mysql_fetch_array(mysql_query("select * from user where user_id = ".$user_id));
$userArr = array();
$userArr = array('user_id'=>$userInfo['user_id'],'profile_image'=>$userInfo['profile_image'],"success_message" => "profile image updated successfully");
echo json_encode($userArr);
exit();
}
ProfileImageApi class
public class ProfileImageAPI extends BaseAPI {
private Context mContext;
private NetworkCallback mCallback;
public ProfileImageAPI(Context context, NetworkCallback callback) {
super(context);
this.mContext = context;
this.mCallback = callback;
}
public void processProfileImage(final String userId, final File profileImg, final String imgName){
showProgressDialog();
StringRequest strReq = new StringRequest(Request.Method.POST,
ApiUtil.BASE_EDIT_PROFILE_IMAGE, new Response.Listener<String>() {
#Override
public void onResponse(String response) {
Log.d(ApiUtil.TAG_EDIT_PROFILE_IMAGE, response.toString());
mCallback.updateScreen(response,ApiUtil.TAG_EDIT_PROFILE_IMAGE);
hideProgressDialog();
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
VolleyLog.d(ApiUtil.TAG_EDIT_PROFILE_IMAGE, "Error: " + error.getMessage());
mCallback.updateScreen("ERROR",ApiUtil.TAG_EDIT_PROFILE_IMAGE);
hideProgressDialog();
}
}){
#Override
protected Map<String, String> getParams() {
Map<String, String> params = new HashMap<String, String>();
params.put(ApiUtil.PARAM_USER_ID,userId);
params.put(ApiUtil.PARAM_PROFILE_IMG,profileImg.toString());
params.put(ApiUtil.PARAM_IMG_NAME,imgName);
return params;
}
};
// Adding request to request queue
AppController ctrl = AppController.getInstance();
ctrl.addToRequestQueue(strReq, ApiUtil.TAG_EDIT_PROFILE_IMAGE);
}
}
Which library you have used for api calls.
1. Retrofit
2. Okhttp.
Retrofit MultiPartWebservice : "Retrofit" multiple images attached in one multipart request
OKHttp MultiPartWebservice :
how to use okhttp to upload a file?