I want to upload multiple image from gallery to server but getting only one image not multiple.
following is the code for it
FirstFragment.java
private void orderRequest() {
final OrderRequestModel model = basicInfiFragment.getData();
model.setSs(steelFragment.getProductInfo());
model.setAluminium(aluminiumFragment.getProductInfo());
SimpleMultiPartRequest orderRequest = new SimpleMultiPartRequest(Request.Method.POST,
Constance.baseURL + Constance.orderURL, new com.android.volley.Response.Listener<String>() {
#Override
public void onResponse(String response) {
DialogUtil.hideProgrss();
ProductModel mResponse = new Gson().fromJson(response, ProductModel.class);
if (mResponse.getStatus().equalsIgnoreCase(Constance.success)) {
Toast.makeText(getContext(), mResponse.getMessage(), Toast.LENGTH_SHORT).show();
Intent intent = new Intent(getContext(), MainActivity.class);
getContext().startActivity(intent);
getActivity().finish();
} else {
SnackUtil.mackText(mBinding.layoutRoot, mResponse.getMessage(), true);
}
L.e(response);
}
}, new com.android.volley.Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
L.e(error.toString());
DialogUtil.hideProgrss();
DialogUtil.someThingWentWrong(getContext());
}
});
Map<String, String> headerMap = new HashMap<>();
headerMap.put("token", SP.getString(SP.TOKEN));
for (ImageDetails imageDetails : model.getImageList()) {
orderRequest.addStringParam("json", new Gson().toJson(model));
orderRequest.addFile("siteImages",imageDetails.getPath());
orderRequest.addMultipartParam(imageDetails.getName(), getActivity().
getContentResolver().getType(imageDetails.getURI()), imageDetails.getPath());
orderRequest.setHeaders(headerMap);
}
DialogUtil.showProgress(getContext());
RequestQueue requestQueue = Volley.newRequestQueue(getContext());
requestQueue.add(orderRequest);
}
i tried a lot but it is uploading only one image please help me out of these getting stuck since last three days..
SecondFragment.java
public OrderRequestModel getData() {
OrderRequestModel model = new OrderRequestModel();
try {
model.setImageList(imageDetails);
} catch (Exception e) {
SnackUtil.mackText(mBinding.layoutRoot, getString(R.string.some_things_went_wrong), true);
L.e("date parse Error : " + e.getMessage());
}
return model;
}
#Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
switch (requestCode) {
case 122:
if (data != null) {
if (resultCode == Activity.RESULT_OK) {
Bitmap image = (Bitmap) data.getExtras().get("data");
String strData = String.valueOf(data.getData());
L.e("Camera : " + strData);
if (image != null) {
ImageDetails imgDetails = new ImageDetails();
imgDetails.setName(MyUtil.getFilename(Uri.parse(strData), getActivity()));
imgDetails.setBitmap(image);
imgDetails.setName("image" + new Random().nextInt(1000));
imageDetails.add(imgDetails);
}
}
adapterImages.notifyDataSetChanged();
}
break;
case 144:
if (data != null) {
if (resultCode == Activity.RESULT_OK) {
String strData = data.getDataString();
Uri[] resultFileChooser = null;
try {
if (data.getClipData() == null) {
L.e("data Clicp is Null");
}
resultFileChooser = new Uri[data.getClipData().getItemCount()];
for (int i = 0; i < data.getClipData().getItemCount(); i++) {
ImageDetails details = new ImageDetails();
details.setPath(getPath(data.getClipData().getItemAt(i).getUri()));
details.setURI(data.getClipData().getItemAt(i).getUri());
details.setName(MyUtil.getFilename(data.getClipData().getItemAt(i).getUri(), getActivity()));
imageDetails.add(details);
L.e("Uri : " + details.getPath());
}
} catch (NullPointerException e) {
if (strData != null) {
resultFileChooser = new Uri[]{Uri.parse(strData)};
ImageDetails imgDetails = new ImageDetails();
imgDetails.setName(MyUtil.getFilename(Uri.parse(strData), getActivity()));
imgDetails.setPath(getPath(Uri.parse(strData)));
imgDetails.setURI(Uri.parse(strData));
imageDetails.add(imgDetails);
L.e("Uri : " + imgDetails.getPath());
}
}
}
adapterImages.notifyDataSetChanged();
}
break;
}
}
this is the code which i am trying i paste my onActivity code and multipart code also.
you may want to enable multi-selection while selection and then syncing with the server.
Intent intent = new Intent(Intent.ACTION_OPEN_DOCUMENT);
intent.addCategory(Intent.CATEGORY_OPENABLE);
intent.putExtra(Intent.EXTRA_ALLOW_MULTIPLE, true);
intent.setType("image/*");
startActivityForResult(intent, READ_REQUEST_CODE);
you will receive multiple Uri in your onActivity from there use to get file objects and then sync with the server.
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
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?
I have some places in a listView. These are picked from a Google Map, for which I would like to take a picture. One for each. These photos should be available online, so I have searched for some proper solutions. I've choosed imgur's API.
Is it possible to link pictures with places? I would like to make mapping between uploaded pictures and listView items.
Photo picker and uploader class:
public class OAuthTestActivity extends Activity {
public static final int REQUEST_CODE_PICK_IMAGE = 1001;
private static final String AUTHORIZATION_URL = "https://api.imgur.com/oauth2/authorize";
private static final String CLIENT_ID = "CLIENT_ID";
private LinearLayout rootView;
private String accessToken;
private String refreshToken;
private String picturePath = "";
private Button send;
private String uploadedImageUrl = "";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
rootView = new LinearLayout(this);
rootView.setOrientation(LinearLayout.VERTICAL);
TextView tv = new TextView(this);
LinearLayout.LayoutParams llp = new LinearLayout.LayoutParams(
ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT);
tv.setLayoutParams(llp);
rootView.addView(tv);
setContentView(rootView);
String action = getIntent().getAction();
if (action == null || !action.equals(Intent.ACTION_VIEW)) { // We need access token to use Imgur's api
tv.setText("Start OAuth Authorization");
Uri uri = Uri.parse(AUTHORIZATION_URL).buildUpon()
.appendQueryParameter("client_id", CLIENT_ID)
.appendQueryParameter("response_type", "token")
.appendQueryParameter("state", "init")
.build();
Intent intent = new Intent();
intent.setData(uri);
intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
startActivity(intent);
finish();
} else { // Now we have the token, can do the upload
tv.setText("Got Access Token");
Uri uri = getIntent().getData();
Log.d("Got imgur's access token", uri.toString());
String uriString = uri.toString();
String paramsString = "http://callback?" + uriString.substring(uriString.indexOf("#") + 1);
Log.d("tag", paramsString);
List<NameValuePair> params = URLEncodedUtils.parse(URI.create(paramsString), "utf-8");
Log.d("tag", Arrays.toString(params.toArray(new NameValuePair[0])));
for (NameValuePair pair : params) {
if (pair.getName().equals("access_token")) {
accessToken = pair.getValue();
} else if (pair.getName().equals("refresh_token")) {
refreshToken = pair.getValue();
}
}
Log.d("tag", "access_token = " + accessToken);
Log.d("tag", "refresh_token = " + refreshToken);
Button chooseImage = new Button(this);
rootView.addView(chooseImage);
chooseImage.setText("Choose an image");
chooseImage.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent(Intent.ACTION_PICK, MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
startActivityForResult(intent, REQUEST_CODE_PICK_IMAGE);
}
});
send = new Button(this);
rootView.addView(send);
send.setText("send to imgur");
send.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (picturePath != null && picturePath.length() > 0 &&
accessToken != null && accessToken.length() > 0) {
(new UploadToImgurTask()).execute(picturePath);
}
}
});
}
}
#Override
protected void onResume() {
super.onResume();
if (send == null) return;
if (picturePath == null || picturePath.length() == 0) {
send.setVisibility(View.GONE);
} else {
send.setVisibility(View.VISIBLE);
}
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
Log.d("tag", "request code : " + requestCode + ", result code : " + resultCode);
if (data == null) {
Log.d("tag" , "data is null");
}
if (resultCode == Activity.RESULT_OK && requestCode == REQUEST_CODE_PICK_IMAGE && null != data) {
Uri selectedImage = data.getData();
String[] filePathColumn = { MediaStore.Images.Media.DATA };
Cursor cursor = getContentResolver().query(selectedImage,
filePathColumn, null, null, null);
cursor.moveToFirst();
int columnIndex = cursor.getColumnIndex(filePathColumn[0]);
picturePath = cursor.getString(columnIndex);
Log.d("tag", "image path : " + picturePath);
cursor.close();
}
super.onActivityResult(requestCode, resultCode, data);
}
// Here is the upload task
class UploadToImgurTask extends AsyncTask<String, Void, Boolean> {
#Override
protected Boolean doInBackground(String... params) {
final String upload_to = "https://api.imgur.com/3/upload";
HttpClient httpClient = new DefaultHttpClient();
HttpContext localContext = new BasicHttpContext();
HttpPost httpPost = new HttpPost(upload_to);
try {
HttpEntity entity = MultipartEntityBuilder.create()
.addPart("image", new FileBody(new File(params[0])))
.build();
httpPost.setHeader("Authorization", "Bearer " + accessToken);
httpPost.setEntity(entity);
final HttpResponse response = httpClient.execute(httpPost,
localContext);
final String response_string = EntityUtils.toString(response
.getEntity());
final JSONObject json = new JSONObject(response_string);
Log.d("tag", json.toString());
JSONObject data = json.optJSONObject("data");
uploadedImageUrl = data.optString("link");
Log.d("tag", "uploaded image url : " + uploadedImageUrl);
return true;
} catch (Exception e) {
e.printStackTrace();
}
return false;
}
#Override
protected void onPostExecute(Boolean aBoolean) {
super.onPostExecute(aBoolean);
if (aBoolean.booleanValue()) { // after sucessful uploading, show the image in web browser
Button openBrowser = new Button(OAuthTestActivity.this);
rootView.addView(openBrowser);
openBrowser.setText("Open Browser");
openBrowser.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent();
intent.setData(Uri.parse(uploadedImageUrl));
intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
startActivity(intent);
}
});
}
}
}
}
I use Fabric SDK to send tweets from my application.
I build a share dialog and send tweet from activity.
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
TwitterAuthConfig authConfig = new TwitterAuthConfig(CONSUMER_KEY, CONSUMER_SECRET);
Fabric.with(this, new TwitterCore(authConfig), new TweetComposer());
Bundle bundle = getIntent().getExtras().getBundle(SHARE_DATA);
String description = bundle.getString(SHARE_DESCRIPTION);
String title = bundle.getString(SHARE_TITLE);
String picture = bundle.getString(SHARE_PICTURE_LINK);
String link = bundle.getString(SHARE_LINK);
TweetComposer.Builder builder = null;
try {
InputStream in = new java.net.URL(picture).openStream();
Bitmap bitmap = BitmapFactory.decodeStream(in);
Uri yourUri = getImageUri(this,bitmap);
builder = new TweetComposer.Builder(this)
.text(title + "\n" + description)
.url(new URL(link))
.image(yourUri);
//??? IS THERE ANY LISTENER ???
builder.show();
} catch (IOException e1) {
e1.printStackTrace();
}
}
I want to know status of sharing, like an success or not, but i can't find any listener for this action. I missed something?
Instead of use builder.show(), you should use builder.createIntent() :
Intent intent = new TweetComposer.Builder(getActivity())
.text("TEXT")
.url("URL")
.createIntent();
startActivityForResult(intent, TWEET_COMPOSER_REQUEST_CODE);
To get the result feedback in onActivityResult() :
#Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if(requestCode == TWEET_COMPOSER_REQUEST_CODE) {
if(resultCode == Activity.RESULT_OK) {
onTwitterSuccess();
} else if(resultCode == Activity.RESULT_CANCELED) {
onTwitterCancel();
}
}
}
use below method to twitt via rest service and pass media id as null.i m successfully posting tweets from my app
public void postToTwitter(ArrayList<String>mediaIds) {
String message;
if(Validator.isNotNull(preferences.getFbShareMessage())){
message=preferences.getFbShareMessage()+" "+com.aimdek.healthwel.network.Request.HOST_URL + "/user-history/" + userHistory.getUserId() + "/" + userHistory.getId();
}
else {
message = getString(R.string.google_status, HWUtil.getFullName(preferences.getUserInfo().getFirstName(), preferences.getUserInfo().getLastName()), userHistory.getSportName(), HWUtil.secondToTime(userHistory.getDuration()))+" "+com.aimdek.healthwel.network.Request.HOST_URL + "/user-history/" + userHistory.getUserId() + "/" + userHistory.getId();
}
String mediaId;
if (Validator.isNotNull(mediaIds) && mediaIds.size() > 0) {
mediaId="";
for (int i = 0; i < mediaIds.size(); i++) {
if (i == 0) {
mediaId = mediaIds.get(i);
} else {
mediaId += "," + mediaIds.get(i);
}
}
}
else {
mediaId=null;
}
StatusesService statusesService = twitterApiClient.getStatusesService();
statusesService.update(message, null, null, null, null, null, null, null, mediaId, new Callback<Tweet>() {
#Override
public void success(Result<Tweet> result) {
dismissProgressDialog();
if(Validator.isNotNull(preferences.getImagePath()) && !preferences.getImagePath().isEmpty()) {
preferences.getImagePath().clear();
}
com.aimdek.healthwel.network.Request.getRequest().sendRequest(com.aimdek.healthwel.network.Request.SHARE_USER_HISTORY, TwitterIntegration.this, TwitterIntegration.this, RequestParameterBuilder.buildMapForShareUserHistory(userHistory.getId(), TwitterIntegration.this));
}
#Override
public void failure(TwitterException exception) {
if(Validator.isNotNull(preferences.getImagePath()) && !preferences.getImagePath().isEmpty()) {
preferences.getImagePath().clear();
}
dismissProgressDialog();
finish();
HWUtil.showToast(TwitterIntegration.this,exception.getMessage());
}
});
}