How to await OnActivityResult in Xamarin C# on Android - android

I'm using MvvmCross on Android via Xamarin and i got a problem. I created a core service interface called IFileExplorerService.
This interface goal is to open a open file dialog and select a file whatever the device is (Windows or android).
On android i managed easly to do this without my interface via view by just using the OnActivityResult and Intents.
But i just cannot make it work from my view, as the interface implementation is a singleton registered in the setup, when i call it from my viewmodel there is absolutely no one to handle the OnActivityResult.
I tried to make my FileExplorer implmentation to inherit from Activity or MvxActivity, for this way my FileExplorer could override OnActivityResult, but this fails.
I tried to use StartActivity(typeof(FileExplorer)) but this obviously would fails anyway as it wouldn't be the singleton registered in MvvmCross that would be started.
Does anyone has any idea/comment/question/suggestion to help me on this?
Here is my code so far :
public class FileExplorerService : IFileExplorerServiceMock
{
string _addedFileName;
public static int REQUEST_FILE_CAPTURE = 2;
private bool _hasMediaBeenAdded;
private TaskCompletionSource<String> GetFileTask;
public Activity activity;
public FileExplorerService()
{
GetFileTask = new TaskCompletionSource<string>();
}
private void DispatchSelectFileIntent()
{
Intent Intent = new Intent();
Intent.SetType("*/*");
Intent.SetAction(Intent.ActionGetContent);
activity.StartActivityForResult(Intent.CreateChooser(Intent, "Select File"), REQUEST_FILE_CAPTURE);
}
public void OnActivityResult(int requestCode, [GeneratedEnum] Result resultCode, Intent data)
{
//
if (resultCode == Result.Ok)
{
if (data != null)
{
bool isFileCopied = CopySelectedFileToAddedFilesDirectory(data.Data);
if (isFileCopied)
{
//everything went well
ShowSuccesAlertDialog();
GetFileTask.SetResult(_addedFileName);
}
else
{
ShowFailureAlertDialog();
//oops something crashed
//Log
}
}
}
else
{
_addedFileName = String.Empty;
}
}
private void ShowFailureAlertDialog()
{
AlertDialog.Builder builder = new AlertDialog.Builder(activity);
AlertDialog alertDialog = builder.Create();
alertDialog.SetTitle("Oops... something went wrong");
alertDialog.SetIcon(Android.Resource.Drawable.IcDialogAlert);
alertDialog.SetMessage("Something went rong when adding a media");
alertDialog.SetButton("Ok", (s, ev) =>
{
});
alertDialog.Show();
}
private void ShowSuccesAlertDialog()
{
AlertDialog.Builder builder = new AlertDialog.Builder(activity);
AlertDialog alertDialog = builder.Create();
alertDialog.SetTitle("Media added with succes !");
alertDialog.SetIcon(Android.Resource.Drawable.IcDialogAlert);
alertDialog.SetMessage("Your media has been added with succes");
alertDialog.SetButton("Ok", (s, ev) =>
{
_hasMediaBeenAdded = true;
});
alertDialog.Show();
}
private void DeletePreviousAddedFile()
{
//todo delete file only if selected rex type is the same
if (_hasMediaBeenAdded)
{
MsFile.Delete(_addedFileName);
_addedFileName = string.Empty;
_hasMediaBeenAdded = false;
}
}
private static string GetRealPathFromURI(Context _context, Android.Net.Uri contentUri)
{
string[] projection = new string[] { MediaStore.MediaColumns.Data };
ContentResolver cr = _context.ContentResolver;
Android.Database.ICursor cursor = cr.Query(contentUri, projection, null, null, null);
if (cursor != null && cursor.Count > 0)
{
cursor.MoveToFirst();
int index = cursor.GetColumnIndex(Android.Provider.MediaStore.MediaColumns.Data);
return cursor.GetString(index);
}
return "";
}
private bool CopySelectedFileToAddedFilesDirectory(Android.Net.Uri data)
{
var dir = new Java.IO.File(Android.OS.Environment.ExternalStorageDirectory.AbsolutePath + "/Medias/AddedMedias/Files/");
if (!dir.Exists())
dir.Mkdirs();
string path = Android.OS.Environment.ExternalStorageDirectory.AbsolutePath + "/Medias/AddedMedias/Files/";
JavaFile file = new Java.IO.File(path);
string realPath = GetRealPathFromURI(activity.ApplicationContext, data);
string FileName = realPath.Split('/').Last();
_addedFileName = Path.Combine(dir + "/" + FileName);
if (!string.IsNullOrEmpty(realPath))
{
//todo manage errors
using (FileStream fs = new FileStream(realPath, FileMode.Open))
{
byte[] datas = new byte[fs.Length];
int numberBytesToRead = (int)fs.Length;
int numBytesRead = 0;
while (numberBytesToRead > 0)
{
int n = fs.Read(datas, numBytesRead, numberBytesToRead);
if (n == 0)
{
break;
}
numBytesRead += n;
numberBytesToRead -= n;
}
using (FileStream fs2 = System.IO.File.OpenWrite(Path.Combine(dir + "/" + FileName)))
{
fs2.Write(datas, 0, datas.Length);
}
}
return true;
}
return false;
}
public List<FileType> FileTypes
{
get
{
return new List<FileType>();
}
}
public async Task<string> Show(string fiel)
{
if (activity != null)
{
DeletePreviousAddedFile();
DispatchSelectFileIntent();
return GetFileTask.Task.Result;
}
else
{
return String.Empty;
}
}
And in my view :
protected override void OnCreate(Bundle bundle)
{
base.OnCreate(bundle);
SetContentView(Resource.Layout.RexView);
_addMediaController = new AddMediaController(this, (RexViewModel)base.ViewModel);
_flyoutMenuAnimator = new FlyoutMenuAnimator(this);
var t= Mvx.Resolve<IFileExplorerServiceMock>() as FileExplorerService;
t.activity = this;
}
protected override void OnActivityResult(int requestCode, Result resultCode, Intent data)
{
var t = Mvx.Resolve<IFileExplorerServiceMock>() as FileExplorerService;
t.OnActivityResult(requestCode, resultCode, data);
base.OnActivityResult(requestCode, resultCode, data);
}
With this everything work except that OnActivityResult is never called in my view

Okay i solved it ! Thanks to this link https://forums.xamarin.com/discussion/45691/pass-data-from-android-project-to-pcl
I had to rewrite start activity to give it a callback as an argument, the callback being my OnActivityResult in my file Explorer.
Here is my the code for anyone needing it :
in MyView:
private Action<int, Result, Intent> _resultCallback;
public void StartActivity(Intent intent,int resultCode, Action<int, Result, Intent> resultCallback)
{
_resultCallback = resultCallback;
StartActivityForResult(intent, resultCode);
}
protected override void OnActivityResult(int requestCode, Result resultCode, Intent data)
{
base.OnActivityResult(requestCode, resultCode, data);
if (_resultCallback != null)
{
_resultCallback(requestCode, resultCode, data);
_resultCallback = null;
}
}
and in my file Explorer :
string _addedFileName;
public static int REQUEST_FILE_CAPTURE = 2;
private bool _hasMediaBeenAdded;
private TaskCompletionSource<String> GetFileTask;
public RexView activity;
public FileExplorerService()
{
}
private void DispatchSelectFileIntent()
{
Intent intent = new Intent();
intent.SetType("*/*");
intent.SetAction(Intent.ActionGetContent);
GetFileTask = new TaskCompletionSource<string>();
activity.StartActivity(Intent.CreateChooser(intent, "Select File"), REQUEST_FILE_CAPTURE, OnActivityResult);
// activity.StartActivityForResult(Intent.CreateChooser(intent, "Select File"), REQUEST_FILE_CAPTURE);
}
public void OnActivityResult(int requestCode, [GeneratedEnum] Result resultCode, Intent data)
{
//
if (resultCode == Result.Ok)
{
if (data != null)
{
bool isFileCopied = CopySelectedFileToAddedFilesDirectory(data.Data);
if (isFileCopied)
{
//everything went well
ShowSuccesAlertDialog();
GetFileTask.SetResult(_addedFileName);
}
else
{
ShowFailureAlertDialog();
//oops something crashed
//Log
}
}
}
else
{
_addedFileName = String.Empty;
}
}
private void ShowFailureAlertDialog()
{
AlertDialog.Builder builder = new AlertDialog.Builder(activity);
AlertDialog alertDialog = builder.Create();
alertDialog.SetTitle("Oops... something went wrong");
alertDialog.SetIcon(Android.Resource.Drawable.IcDialogAlert);
alertDialog.SetMessage("Something went rong when adding a media");
alertDialog.SetButton("Ok", (s, ev) =>
{
});
alertDialog.Show();
}
private void ShowSuccesAlertDialog()
{
AlertDialog.Builder builder = new AlertDialog.Builder(activity);
AlertDialog alertDialog = builder.Create();
alertDialog.SetTitle("Media added with succes !");
alertDialog.SetIcon(Android.Resource.Drawable.IcDialogAlert);
alertDialog.SetMessage("Your media has been added with succes");
alertDialog.SetButton("Ok", (s, ev) =>
{
_hasMediaBeenAdded = true;
});
alertDialog.Show();
}
private void DeletePreviousAddedFile()
{
//todo delete file only if selected rex type is the same
if (_hasMediaBeenAdded)
{
MsFile.Delete(_addedFileName);
_addedFileName = string.Empty;
_hasMediaBeenAdded = false;
}
}
private static string GetRealPathFromURI(Context _context, Android.Net.Uri contentUri)
{
string[] projection = new string[] { MediaStore.MediaColumns.Data };
ContentResolver cr = _context.ContentResolver;
Android.Database.ICursor cursor = cr.Query(contentUri, projection, null, null, null);
if (cursor != null && cursor.Count > 0)
{
cursor.MoveToFirst();
int index = cursor.GetColumnIndex(Android.Provider.MediaStore.MediaColumns.Data);
return cursor.GetString(index);
}
return "";
}
private bool CopySelectedFileToAddedFilesDirectory(Android.Net.Uri data)
{
var dir = new Java.IO.File(Android.OS.Environment.ExternalStorageDirectory.AbsolutePath + "/Medias/AddedMedias/Files/");
if (!dir.Exists())
dir.Mkdirs();
string path = Android.OS.Environment.ExternalStorageDirectory.AbsolutePath + "/Medias/AddedMedias/Files/";
JavaFile file = new Java.IO.File(path);
string realPath = GetRealPathFromURI(activity.ApplicationContext, data);
string FileName = realPath.Split('/').Last();
_addedFileName = Path.Combine(dir + "/" + FileName);
if (!string.IsNullOrEmpty(realPath))
{
//todo manage errors
using (FileStream fs = new FileStream(realPath, FileMode.Open))
{
byte[] datas = new byte[fs.Length];
int numberBytesToRead = (int)fs.Length;
int numBytesRead = 0;
while (numberBytesToRead > 0)
{
int n = fs.Read(datas, numBytesRead, numberBytesToRead);
if (n == 0)
{
break;
}
numBytesRead += n;
numberBytesToRead -= n;
}
using (FileStream fs2 = System.IO.File.OpenWrite(Path.Combine(dir + "/" + FileName)))
{
fs2.Write(datas, 0, datas.Length);
}
}
return true;
}
return false;
}
public List<FileType> FileTypes
{
get
{
return new List<FileType>();
}
}
public async Task<string> Show(string fiel)
{
if (activity != null)
{
DeletePreviousAddedFile();
DispatchSelectFileIntent();
return await GetFileTask.Task;
}
else
{
return String.Empty;
}
}
}
And in my view model
private async void BrowseMedias()
{
var fileExplorerService = Mvx.Resolve<IFileExplorerServiceMock>();
fileExplorerService.FileTypes.Add(FileType.Picture);
string fileSavedPath = await fileExplorerService.Show(DatabaseContentPath);
/* file managment*/
}

Related

How to set sourceImagePath, outputFile in Image Editor

I am using a library implementation com.github.iamutkarshtiwari:Ananas:1.2.3. Everything is working fine but I am facing two errors sourceImagePath, outputFilePath. How can I solve it and remove log e and use camera to run app?
MainActivity
public class MainActivity extends AppCompatActivity implements View.OnClickListener {
public static final int REQUEST_PERMISSON_SORAGE = 1;
public static final int REQUEST_PERMISSON_CAMERA = 2;
public static final int SELECT_GALLERY_IMAGE_CODE = 7;
public static final int TAKE_PHOTO_CODE = 8;
public static final int ACTION_REQUEST_EDITIMAGE = 9;
private ImageView imgView;
private Bitmap mainBitmap;
private Dialog loadingDialog;
private int imageWidth, imageHeight;
private String path;
private Uri photoURI = null;
private final int PHOTO_EDITOR_REQUEST_CODE = 123;
private CompositeDisposable compositeDisposable = new CompositeDisposable();
private Object BaseActivity;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
initView();
}
#Override
protected void onPause() {
compositeDisposable.clear();
super.onPause();
}
#Override
protected void onDestroy() {
compositeDisposable.dispose();
super.onDestroy();
}
private void initView() {
DisplayMetrics metrics = getResources().getDisplayMetrics();
imageWidth = metrics.widthPixels;
imageHeight = metrics.heightPixels;
imgView = findViewById(R.id.img);
View selectAlbum = findViewById(R.id.select_album);
View editImage = findViewById(R.id.edit_image);
selectAlbum.setOnClickListener(this);
editImage.setOnClickListener(this);
View takenPhoto = findViewById(R.id.take_photo);
takenPhoto.setOnClickListener(this);
loadingDialog = BaseActivity.getLoadingDialog(this, R.string.iamutkarshtiwari_github_io_ananas_loading,
false);
}
#Override
public void onClick(View v) {
switch (v.getId()) {
case R.id.take_photo:
takePhotoClick();
break;
case R.id.edit_image:
editImageClick();
break;
case R.id.select_album:
selectFromAblum();
break;
}
}
protected void takePhotoClick() {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.P) {
requestTakePhotoPermissions();
} else {
launchCamera();
}
}
private void requestTakePhotoPermissions() {
if (ActivityCompat.checkSelfPermission(this, Manifest.permission.CAMERA)
!= PackageManager.PERMISSION_GRANTED) {
ActivityCompat.requestPermissions(this,
new String[]{Manifest.permission.CAMERA, Manifest.permission.READ_EXTERNAL_STORAGE},
REQUEST_PERMISSON_CAMERA);
return;
}
launchCamera();
}
public void launchCamera() {
Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
if (Build.VERSION.SDK_INT < Build.VERSION_CODES.P) {
Uri outputFileUri = Uri.fromFile(FileUtils.genEditFile());
intent.putExtra(MediaStore.EXTRA_OUTPUT, outputFileUri);
} else {
File file = FileUtils.genEditFile();
Uri photoUri = FileProvider.getUriForFile(getApplicationContext(), getApplicationContext().getPackageName() + ".provider", file);
intent.putExtra(MediaStore.EXTRA_OUTPUT, photoUri);
}
intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
if (intent.resolveActivity(getApplicationContext().getPackageManager()) != null) {
startActivityForResult(intent, TAKE_PHOTO_CODE);
}
}
Facing Problem Here
private void editImageClick() {
File outputFile = FileUtils.genEditFile();
try {
Intent intent = new ImageEditorIntentBuilder(this, sourceImagePath, outputFilePath)
.withAddText() // Add the features you need
.withPaintFeature()
.withFilterFeature()
.withRotateFeature()
.withCropFeature()
.withBrightnessFeature()
.withSaturationFeature()
.withBeautyFeature()
.withStickerFeature()
.forcePortrait(true) // Add this to force portrait mode (It's set to false by default)
.build();
EditImageActivity.start(BaseActivity, intent, PHOTO_EDITOR_REQUEST_CODE);
} catch (Exception e) {
Log.e("Demo App", e.getMessage()); // This could throw if either `sourcePath` or `outputPath` is blank or Null
}
}
private void selectFromAblum() {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
openAblumWithPermissionsCheck();
} else {
openAlbum();
}
}
private void openAlbum() {
MainActivity.this.startActivityForResult(new Intent(
MainActivity.this, SelectPictureActivity.class),
SELECT_GALLERY_IMAGE_CODE);
}
private void openAblumWithPermissionsCheck() {
if (ActivityCompat.checkSelfPermission(this, Manifest.permission.READ_EXTERNAL_STORAGE)
!= PackageManager.PERMISSION_GRANTED) {
ActivityCompat.requestPermissions(this,
new String[]{Manifest.permission.READ_EXTERNAL_STORAGE},
REQUEST_PERMISSON_SORAGE);
return;
}
openAlbum();
}
#Override
public void onRequestPermissionsResult(int requestCode, #NonNull String[] permissions, #NonNull int[] grantResults) {
if (requestCode == REQUEST_PERMISSON_SORAGE
&& grantResults.length > 0
&& grantResults[0] == PackageManager.PERMISSION_GRANTED) {
openAlbum();
} else if (requestCode == REQUEST_PERMISSON_CAMERA
&& grantResults.length > 0
&& grantResults[0] == PackageManager.PERMISSION_GRANTED) {
launchCamera();
}
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == PHOTO_EDITOR_REQUEST_CODE) { // same code you used while starting
String newFilePath = data.getStringExtra(EditImageActivity.OUTPUT_PATH);
boolean isImageEdit = data.getBooleanExtra(EditImageActivity.IMAGE_IS_EDIT, false);
}
if (resultCode == RESULT_OK) {
switch (requestCode) {
case SELECT_GALLERY_IMAGE_CODE:
handleSelectFromAblum(data);
break;
case TAKE_PHOTO_CODE:
handleTakePhoto();
break;
case ACTION_REQUEST_EDITIMAGE:
handleEditorImage(data);
break;
}
}
}
private void handleTakePhoto() {
if (photoURI != null) {
path = photoURI.getPath();
loadImage(path);
}
}
private void handleEditorImage(Intent data) {
String newFilePath = data.getStringExtra(ImageEditorIntentBuilder.OUTPUT_PATH);
boolean isImageEdit = data.getBooleanExtra(EditImageActivity.IS_IMAGE_EDITED, false);
if (isImageEdit) {
Toast.makeText(this, getString(R.string.save_path, newFilePath), Toast.LENGTH_LONG).show();
} else {
newFilePath = data.getStringExtra(ImageEditorIntentBuilder.SOURCE_PATH);
}
loadImage(newFilePath);
}
private void handleSelectFromAblum(Intent data) {
path = data.getStringExtra("imgPath");
loadImage(path);
}
private void loadImage(String imagePath) {
compositeDisposable.clear();
Disposable applyRotationDisposable = loadBitmapFromFile(imagePath)
.subscribeOn(Schedulers.io())
.observeOn(AndroidSchedulers.mainThread())
.doOnSubscribe(subscriber -> loadingDialog.show())
.doFinally(() -> loadingDialog.dismiss())
.subscribe(
this::setMainBitmap,
e -> Toast.makeText(
this, R.string.iamutkarshtiwari_github_io_ananas_load_error, Toast.LENGTH_SHORT).show()
);
compositeDisposable.add(applyRotationDisposable);
}
private void setMainBitmap(Bitmap sourceBitmap) {
if (mainBitmap != null) {
mainBitmap.recycle();
mainBitmap = null;
System.gc();
}
mainBitmap = sourceBitmap;
imgView.setImageBitmap(mainBitmap);
}
private Single<Bitmap> loadBitmapFromFile(String filePath) {
return Single.fromCallable(() ->
BitmapUtils.getSampledBitmap(
filePath,
imageWidth / 4,
imageHeight / 4
)
);
}
}

UCrop from a fragment no requestCode being sent

I am trying to use Ucrop from a fragment. The issue I am facing is that onActivityresult is not receiving requestCode == UCrop.REQUEST_CROP thus not performing the actions I need to do with the image. I have searched around for tutorials but I haven't managed to find any.
The following is the code of the fragment that is using UCrop:
public class FragmentSettingsTabImage extends Fragment {
private String TAG = "----->";
Tools t;
private String currentPhotoPath;
private final int REQUEST_TAKE_PHOTO = 1;
private final int CAMERA_PERMISSIONS = 2;
private ImageView imgTabImageDriver;
private Button btnSettingsSaveImage;
#Override
public void onRequestPermissionsResult(int requestCode, #NonNull String[] permissions, #NonNull int[] grantResults) {
if (requestCode == CAMERA_PERMISSIONS) {
if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
// All good so launch take picture from here
dispatchTakePictureIntent();
} else {
// Permission denied. Warn the user and kick out of app
AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());
builder.setTitle(R.string.permsDeniedCameraTitle);
builder.setMessage(R.string.permsDeniedCameraMessage);
builder.setCancelable(false);
builder.setPositiveButton(R.string.close, new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
Objects.requireNonNull(getActivity()).finishAffinity();
}
});
builder.create().show();
}
}
}
#Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
if (requestCode == REQUEST_TAKE_PHOTO && resultCode == Activity.RESULT_OK) {
Uri starturi = Uri.fromFile(new File(currentPhotoPath));
Uri destinationuri = Uri.fromFile(new File(currentPhotoPath));
UCrop.Options options = AppConstants.makeUcropOptions(Objects.requireNonNull(getActivity()));
UCrop.of(starturi, destinationuri).withOptions(options).start(getActivity());
}
Log.d(TAG, "onActivityResult: CCCCCCC" + resultCode + " " + requestCode);
// On result from cropper add to imageview
getActivity();
if (resultCode == Activity.RESULT_OK && requestCode == UCrop.REQUEST_CROP) {
final Uri resultUri = UCrop.getOutput(data);
assert resultUri != null;
File imgFile = new File(resultUri.getPath());
Picasso.Builder builder = new Picasso.Builder(Objects.requireNonNull(getActivity()));
builder.listener(new Picasso.Listener() {
#Override
public void onImageLoadFailed(Picasso picasso, Uri uri, Exception exception) {
exception.printStackTrace();
}
});
builder.build().load(imgFile).into(imgTabImageDriver, new Callback() {
#Override
public void onSuccess() {
btnSettingsSaveImage.setEnabled(true);
}
#Override
public void onError(Exception e) {
e.printStackTrace();
}
});
}
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
}
#Override
public View onCreateView(#NonNull LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
SharedPreferences preferences = Objects.requireNonNull(this.getActivity()).getSharedPreferences("mykago-driver", Context.MODE_PRIVATE);
final SharedPreferences.Editor editor = preferences.edit();
View view = inflater.inflate(R.layout.fragment_settings_tab_image, container, false);
imgTabImageDriver= view.findViewById(R.id.imgTabImageDriver);
ImageView imgTakeSettingsDriverPicture = view.findViewById(R.id.imgTakeSettingsDriverPicture);
btnSettingsSaveImage = view.findViewById(R.id.btnSettingsSaveImage);
imgTakeSettingsDriverPicture.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
dispatchTakePictureIntent();
}
});
imgTabImageDriver.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
dispatchTakePictureIntent();
}
});
btnSettingsSaveImage.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
editor.putString("driver_picture", currentPhotoPath);
editor.apply();
}
});
Picasso.Builder builder = new Picasso.Builder(Objects.requireNonNull(getContext()));
builder.listener(new Picasso.Listener() {
#Override
public void onImageLoadFailed(Picasso picasso, Uri uri, Exception exception) {
exception.printStackTrace();
}
});
Log.d(TAG, "onCreateView: " + preferences.getString("driver_picture", ""));
builder.build().load(new File(preferences.getString("id_picture", ""))).into(imgTabImageDriver);
return view;
}
private void dispatchTakePictureIntent() {
Intent takePictureIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
// Ensure that there's a camera activity to handle the intent
if (takePictureIntent.resolveActivity(Objects.requireNonNull(getActivity()).getPackageManager()) != null) {
// Create the File where the photo should go
File photoFile = null;
try {
photoFile = createImageFile();
} catch (IOException ex) {
// Error occurred while creating the File
Log.d("IMAGE CREATION", ex.toString());
}
// Continue only if the File was successfully created
if (photoFile != null) {
Uri photoURI = FileProvider.getUriForFile(getActivity(),
"com.mytestapp.fileprovider",
photoFile);
takePictureIntent.putExtra(MediaStore.EXTRA_OUTPUT, photoURI);
startActivityForResult(takePictureIntent, REQUEST_TAKE_PHOTO);
}
}
}
private File createImageFile() throws IOException {
// Create an image file name
String timeStamp = new SimpleDateFormat("yyyyMMdd_HHmmss", Locale.US).format(new Date());
String imageFileName = "didimage_" + timeStamp + "_";
File storageDir = Objects.requireNonNull(getActivity()).getExternalFilesDir(Environment.DIRECTORY_PICTURES);
File image = File.createTempFile(
imageFileName,
".png",
storageDir
);
// Save a file: path for use with ACTION_VIEW intents
currentPhotoPath = image.getAbsolutePath();
return image;
}
}
The same code from a normal activity works without any issues. Any help appreciated.
Managed to solve the issue. To pass the result of the UCrop activity to the fragment and not to the hosting activity you need to call the UCrop....start() method as follows:
UCrop.of(starturi, destinationuri).withOptions(options).start(getActivity().getApplicationContext(), getFragmentManager().findFragmentByTag("your_fragment_tag"));
so
.start(Context, Fragment)
This will make sure that the onActivityResult of the fragment gets called and not the one of the hosting activity.
This works also:
UCrop.of(sourceUri,destinationUri)
.withOptions(options)
.start(getActivity(),YourFragment.this);
If you want to start uCrop activity from Fragment use this.
UCrop.of(uri, destinationFileName)
.withAspectRatio(1, 1)
.start(getContext(), this, UCrop.REQUEST_CROP);

Is disappearing after going to another activity but showing uploading to server Glide and volley

I have created two functionality for photo uploading in my app. The first one is for capture image and the second one is for pick image from gallery. Now I have a photo API as URL. By using this API I have to upload the image at first to server and from server it will be available throught the app. Now I can successfully uploaded the picture in server and in the server side shows the picture. But in the imageview of app does not show that image. Whenever I go to another activity and then come back to image activity the imageview is empty. I have used shared preference to keep the image at image view, but that does not work.
Here is my code for photo activity
public class ViewProfileFragment extends Fragment implements
View.OnClickListener{
private static final int CODE_GALLERY_REQUEST =999 ;
private static final int MY_CAMERA_REQUEST_CODE = 100;
private ImageView image;
private int REQUEST_CAMERA = 0, SELECT_FILE = 1;
private String userChoosenTask;
Bitmap bm;
private String UPLOAD_URL = Constants.HTTP.PHOTO_URL;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
View rootView = inflater.inflate(R.layout.fragment_view_profile,
container, false);
.........
image=(ImageView)rootView.findViewById(R.id.profile_pic);
saveData();
return rootView;
}
public void saveData(){
Log.d( "----ViewProfile-Email", "mEmail" );
GlobalClass globalClass = new GlobalClass();
String mEmail = globalClass.getEmail_info();
Realm profileRealm;
profileRealm = Realm.getDefaultInstance();
RealmResults<MyColleagueModel> results =
profileRealm.where(MyColleagueModel.class).equalTo("mail",
mEmail).findAll();
//fetching the data
results.load();
if (results.size() > 0) {
......
SharedPreferences preferences =
PreferenceManager.getDefaultSharedPreferences(getActivity());
String mImageUri = preferences.getString("image", null);
if (mImageUri != null) {
image.setImageURI(Uri.parse(mImageUri));
} else {
Glide.with( this )
.load(Constants.HTTP.PHOTO_URL+mail)
.thumbnail(0.5f)
.override(200,200)
.diskCacheStrategy( DiskCacheStrategy.ALL)
.into( image);
}
}
}
#Override
public void onRequestPermissionsResult(int requestCode, String[]
permissions, int[] grantResults) {
if(requestCode==CODE_GALLERY_REQUEST){
if(grantResults.length>0 && grantResults[0]==
PackageManager.PERMISSION_GRANTED){
galleryIntent();
}
else {
Toast.makeText( getActivity().getApplicationContext(),"You
don't have permission to access gallery",Toast.LENGTH_LONG ).show();
}
return;
}
if(requestCode==MY_CAMERA_REQUEST_CODE){
if(grantResults.length>0 && grantResults[0]==
PackageManager.PERMISSION_GRANTED){
cameraIntent();
}
else {
Toast.makeText( getActivity().getApplicationContext(),"You
don't have permission to access gallery",Toast.LENGTH_LONG ).show();
}
return;
}
super.onRequestPermissionsResult( requestCode, permissions,grantResults );
}
public void showDialog(){
//Create a new builder and get the layout.
final AlertDialog.Builder builder = new
AlertDialog.Builder(this.getActivity());
.....
}
});
alertListView.setOnItemClickListener(new
AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
// ListViekw Clicked item index
if (position == 0) {
userChoosenTask ="Take Photo";
alert.dismiss();
if(isPermissionGrantedCamera()) {
cameraIntent();
}
}
else if (position == 1){
userChoosenTask ="Choose from Library";
alert.dismiss();
if(isPermissionGrantedGallery()) {
galleryIntent();
}
}
}
});
}
public boolean isPermissionGrantedGallery() {
if (Build.VERSION.SDK_INT >= 23) {
if
(getActivity().checkSelfPermission(android.Manifest.permission.READ_EXTERNAL_STORAGE)
== PackageManager.PERMISSION_GRANTED) {
Log.v("TAG","Permission is granted");
return true;
} else {
Log.v("TAG","Permission is revoked");
ActivityCompat.requestPermissions(this.getActivity(), new
String[]{Manifest.permission.READ_EXTERNAL_STORAGE}, 1);
return false;
}
}
else { //permission is automatically granted on sdk<23 upon
installation
Log.v("TAG","Permission is granted");
return true;
}
}
public boolean isPermissionGrantedCamera() {
if (Build.VERSION.SDK_INT >= 23) {
if
(getActivity().checkSelfPermission(android.Manifest.permission.CAMERA)
== PackageManager.PERMISSION_GRANTED) {
Log.v("TAG","Permission is granted");
return true;
} else {
Log.v("TAG","Permission is revoked");
ActivityCompat.requestPermissions(this.getActivity(), new
String[]{Manifest.permission.CAMERA}, 0);
return false;
}
}
else { //permission is automatically granted on sdk<23 upon
installation
Log.v("TAG","Permission is granted");
return true;
}
}
private void galleryIntent()
{
Intent intent = new Intent(Intent.ACTION_PICK);
intent.setType("image/*");
startActivityForResult(Intent.createChooser(intent, "Select
File"),SELECT_FILE);
}
public void cameraIntent() {
Intent takePictureIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
if
(takePictureIntent.resolveActivity(getActivity().getPackageManager()) != null)
{
File cameraFolder;
if
(Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)) {
cameraFolder = new
File(Environment.getExternalStorageDirectory(), "image/");
} else {
cameraFolder = getActivity().getCacheDir();
}
if (!cameraFolder.exists()) {
cameraFolder.mkdirs();
}
String imageFileName = System.currentTimeMillis() + ".jpg";File photoFile = new File(cameraFolder + imageFileName);
currentPhotoPath = photoFile.getAbsolutePath();
if (photoFile != null) {
takePictureIntent.putExtra(MediaStore.EXTRA_OUTPUT,
Uri.fromFile(photoFile));
startActivityForResult(takePictureIntent, REQUEST_CAMERA);
}
}
}
#Override
public void onActivityResult(int requestCode, int resultCode, Intent data)
{
super.onActivityResult(requestCode, resultCode, data);
if (resultCode == RESULT_OK) {
if (requestCode == SELECT_FILE && data!=null){
onSelectFromGalleryResult(data);
}
else if (requestCode == REQUEST_CAMERA ) {
if(!TextUtils.isEmpty(currentPhotoPath)) {
try {
galleryAddPic();
onCaptureImageResult();
}
catch (Exception e){
}
}
}
}
}
private void galleryAddPic() {
Intent mediaScanIntent = new
Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE);
File f = new File(currentPhotoPath);
Uri contentUri = Uri.fromFile(f);
mediaScanIntent.setData(contentUri);
this.getActivity().sendBroadcast(mediaScanIntent);
}
private void onCaptureImageResult() {
Bitmap bitmap = getBitmapFromPath(currentPhotoPath, 200, 200);
image.setImageBitmap(bitmap);
compressBitMap(bitmap);
}
private void onSelectFromGalleryResult(Intent data) {
Uri uri = data.getData();
String[] projection = {MediaStore.Images.Media.DATA};
Cursor cursor = getContext().getContentResolver().query(uri,
projection, null, null, null);
if (cursor != null) {
int column_index =
cursor.getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
cursor.moveToFirst();
currentPhotoPath = cursor.getString(column_index);
cursor.close();
} else {
currentPhotoPath = uri.getPath();
}// Saves image URI as string to Default Shared Preferences
SharedPreferences preferences =
PreferenceManager.getDefaultSharedPreferences(getActivity());
SharedPreferences.Editor editor = preferences.edit();
editor.putString("image", String.valueOf(uri));
editor.commit();
try {
Bitmap bitmap = MediaStore.Images.Media.getBitmap(getActivity().getContentResolver(), uri);
image.setImageBitmap(bitmap);
} catch (IOException e) {
e.printStackTrace();
}
bm = BitmapFactory.decodeFile(currentPhotoPath);
compressBitMap(bm);
}
private void compressBitMap(Bitmap bitmap) {
ImageConversion imageConversion = new ImageConversion();
byte[] bytesArray;
int maxSize = 10 * 1024;
int imageMaxQuality = 50;
int imageMinQuality = 5;
bytesArray = imageConversion.convertBitmapToByteArray(bitmap,
imageMaxQuality, imageMinQuality, maxSize);
File destination = new
File(getContext().getApplicationContext().getFilesDir(),
System.currentTimeMillis() + ".jpg");
FileOutputStream fo;
try {
destination.createNewFile();
fo = new FileOutputStream(destination);
fo.write(bytesArray);
fo.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
currentPhotoPath = destination.getPath();
uploadImage(bytesArray);
}
private void uploadImage(final byte[] bytesArray){
.....
}
}
Please don't use
image.setImageURI(uri);
image.invalidate();
Please use this code below instead of that :
try {
Bitmap bitmap = MediaStore.Images.Media.getBitmap(getActivity().getContentResolver(), uri);
image.setImageBitmap(bitmap);
} catch (IOException e) {
e.printStackTrace();
}

resultCode always 0/RESULT_CANCELED on startActivityForResult when Take a Picture

I want to take a picture without crop and I follow tutorial from Developer Android. This is my class:
Fisrt, I make dialog to show and to get the picture.
public void uploadPO() {
final Dialog d = new Dialog(TransDetailActivity.this);
d.requestWindowFeature(Window.FEATURE_NO_TITLE);
d.getWindow().setBackgroundDrawable(new ColorDrawable((Color.TRANSPARENT)));
d.setContentView(R.layout.upload_po);
final ImageView ivImage1 = (ImageView) d.findViewById(R.id.iv_image1);
final ImageView ivImage2 = (ImageView) d.findViewById(R.id.iv_image2);
final ImageView ivImage3 = (ImageView) d.findViewById(R.id.iv_image3);
final ImageView ivImage4 = (ImageView) d.findViewById(R.id.iv_image4);
ivImage1.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
selectImagePO();
statusOnUpload = 1;
}
});
ivImage2.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
selectImagePO();
statusOnUpload = 2;
}
});
ivImage3.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
selectImagePO();
statusOnUpload = 3;
}
});
ivImage4.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
selectImagePO();
statusOnUpload = 4;
}
});
d.show();
}
Next, i make method for chosing take a photo or choose from gallery.
private void selectImagePO() {
final CharSequence[] options = {"Take Photo", "Choose from Gallery", "Cancel"};
AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setTitle("Add Photo PO!");
builder.setItems(options, new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int item) {
if (options[item].equals("Take Photo")) {
selectFrom(PICK_FROM_CAMERA);
/*Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
File f = new File(android.os.Environment.getExternalStorageDirectory(), "temp.jpg");
intent.putExtra(MediaStore.EXTRA_OUTPUT, Uri.fromFile(f));
startActivityForResult(intent, 1);*/
} else if (options[item].equals("Choose from Gallery")) {
selectFrom(PICK_FROM_GALLERY);
/*Intent intent = new Intent(Intent.ACTION_PICK,android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
startActivityForResult(intent, 2);*/
} else if (options[item].equals("Cancel")) {
dialog.dismiss();
}
}
});
builder.show();
}
Next, based on previous selection, I made a function in accordance with the selection.
private void selectFrom(int from) {
if (from == PICK_FROM_CAMERA) {
Intent takePictureIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
if (takePictureIntent.resolveActivity(getPackageManager()) != null) {
startActivityForResult(takePictureIntent, PICK_FROM_CAMERA);
}
} else {
if(Build.VERSION.SDK_INT <19) {
Intent intent = new Intent();
intent.setType("image/*");
intent.setAction(Intent.ACTION_GET_CONTENT);
startActivityForResult(Intent.createChooser(intent, "Complete action using"), from);
}else{
Intent intent = new Intent();
intent.setType("image/*");
intent.setAction(Intent.ACTION_PICK);
startActivityForResult(Intent.createChooser(intent, "Complete action using"), from);
}
}
}
And, i get the error in this class.
#Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
//Toast.makeText(getActivity(),""+resultCode+"", Toast.LENGTH_SHORT).show();
if (resultCode == RESULT_OK) {
if (requestCode == PICK_FROM_CAMERA) {
Bundle extras = data.getExtras();
if (extras != null) {
Bitmap imageBitmap = (Bitmap) extras.get("data");
/*Picasso.with(this)
.load()
.transform(new CircleTransform())
.into(imageProfile);*/
if(statusOnUpload == 1){
ivImage1.setImageBitmap(imageBitmap);
} else if(statusOnUpload == 2){
ivImage2.setImageBitmap(imageBitmap);
}else if(statusOnUpload == 3){
ivImage3.setImageBitmap(imageBitmap);
}else{
ivImage4.setImageBitmap(imageBitmap);
}
ByteArrayOutputStream baos = new ByteArrayOutputStream();
imageBitmap.compress(Bitmap.CompressFormat.JPEG, 80, baos);
byte[] b = baos.toByteArray();
if (statusOnUpload == 1) {
encodedImageString1 = Base64.encodeToString(b, Base64.NO_WRAP);
Log.d(TAG, encodedImageString1.toString());
} else if (statusOnUpload == 2) {
encodedImageString2 = Base64.encodeToString(b, Base64.NO_WRAP);
} else if (statusOnUpload == 3) {
encodedImageString3 = Base64.encodeToString(b, Base64.NO_WRAP);
} else if (statusOnUpload == 4) {
encodedImageString4 = Base64.encodeToString(b, Base64.NO_WRAP);
}
//Log.i("")
//Toast.makeText(getApplicationContext(),""+encodedImageString+"",Toast.LENGTH_SHORT).show();
//DialogDeal dialogDeal=new DialogDeal(EditProfileActivity.this,"imageBase64",encodedImageString,"Cancel");
//dialogDeal.show();
} else {
//LogManager.logI("extras == null");
}
} else if (requestCode == PICK_FROM_GALLERY) {
mImageCaptureUri = data.getData();
doCrop();
}
}
}
What's the problem of my development?
First make sure you the correct permissions in your manifest. I know you're using a camera app as a service, but I think you may need:
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>
<uses-permission android:name="android.permission.CAMERA"/>
If that doesn't help you may want to try using this class below. Dealing with hardware like camera is never simple. I suggest using this base activity. I found it somewhere a long time ago here on SO. It handles some fragmentation issues.
import android.app.Activity;
import android.content.ActivityNotFoundException;
import android.content.ContentValues;
import android.content.Intent;
import android.database.Cursor;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.provider.MediaStore;
import android.support.annotation.NonNull;
import android.util.Log;
import android.widget.Toast;
import java.io.File;
import java.util.Date;
import java.util.Locale;
public abstract class BaseCameraIntentActivity extends BaseActivity
{
private static final String PACKAGE_NAME = "com.your.package";
private static final String DATE_CAMERA_INTENT_STARTED_STATE =
PACKAGE_NAME+"dateCameraIntentStarted";
private static final String CAMERA_PIC_URI_STATE =
PACKAGE_NAME+"CAMERA_PIC_URI_STATE";
private static final String PHOTO_URI_STATE =
PACKAGE_NAME+"PHOTO_URI_STATE";
private static final String ROTATE_X_DEGREES_STATE =
PACKAGE_NAME+"ROTATE_X_DEGREES_STATE";
/**
* Date and time the camera intent was started.
*/
protected static Date dateCameraIntentStarted = null;
/**
* Default location where we want the photo to be ideally stored.
*/
protected static Uri preDefinedCameraUri = null;
/**
* Potential 3rd location of photo data.
*/
protected static Uri photoUriIn3rdLocation = null;
/**
* Retrieved location of the photo.
*/
protected static Uri photoUri = null;
/**
* Orientation of the retrieved photo.
*/
protected static int rotateXDegrees = 0;
private final static int CAPTURE_IMAGE_ACTIVITY_REQUEST_CODE = 100;
/**
* Saves the current state of the activity.
*/
#Override
protected void onSaveInstanceState(Bundle savedInstanceState)
{
super.onSaveInstanceState(savedInstanceState);
if (dateCameraIntentStarted != null) {
savedInstanceState.putString(
DATE_CAMERA_INTENT_STARTED_STATE,
DateHelper.dateToString(dateCameraIntentStarted));
}
if (preDefinedCameraUri != null) {
savedInstanceState.putString(
CAMERA_PIC_URI_STATE,
preDefinedCameraUri.toString());
}
if (photoUri != null) {
savedInstanceState.putString(
PHOTO_URI_STATE,
photoUri.toString());
}
savedInstanceState.putInt(
ROTATE_X_DEGREES_STATE,
rotateXDegrees);
}
/**
* Re-initializes a saved state of the activity.
*/
#Override
protected void onRestoreInstanceState(#NonNull Bundle savedInstanceState)
{
super.onRestoreInstanceState(savedInstanceState);
if (savedInstanceState.containsKey(DATE_CAMERA_INTENT_STARTED_STATE)) {
dateCameraIntentStarted = DateHelper.stringToDate(
savedInstanceState.getString(DATE_CAMERA_INTENT_STARTED_STATE));
}
if (savedInstanceState.containsKey(CAMERA_PIC_URI_STATE)) {
preDefinedCameraUri = Uri.parse(savedInstanceState.getString(CAMERA_PIC_URI_STATE));
}
if (savedInstanceState.containsKey(PHOTO_URI_STATE)) {
photoUri = Uri.parse(savedInstanceState.getString(PHOTO_URI_STATE));
}
rotateXDegrees = savedInstanceState.getInt(ROTATE_X_DEGREES_STATE);
}
/**
* Starts the camera intent depending on the device configuration.
* <p/>
* <b>for Samsung and Sony devices:</b>
* We call the camera activity with the method call to startActivityForResult.
* We only set the constant CAPTURE_IMAGE_ACTIVITY_REQUEST_CODE. We do NOT set any other intent extras.
* <p/>
* <b>for all other devices:</b>
* We call the camera activity with the method call to startActivityForResult as previously.
* This time, however, we additionally set the intent extra MediaStore.EXTRA_OUTPUT
* and provide an URI, where we want the image to be stored.
* <p/>
* In both cases we remember the time the camera activity was started.
*/
public void startCameraIntent()
{
if (Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)) {
try {
// NOTE: Do NOT SET: intent.putExtra(MediaStore.EXTRA_OUTPUT, cameraPicUri)
// on Samsung Galaxy S2/S3/.. for the following reasons:
// 1.) it will break the correct picture orientation
// 2.) the photo will be stored in two locations (the given path and, additionally, in the MediaStore)
String manufacturer = android.os.Build.MANUFACTURER.toLowerCase(Locale.ENGLISH);
String model = android.os.Build.MODEL.toLowerCase(Locale.ENGLISH);
String buildType = android.os.Build.TYPE.toLowerCase(Locale.ENGLISH);
String buildDevice = android.os.Build.DEVICE.toLowerCase(Locale.ENGLISH);
String buildId = android.os.Build.ID.toLowerCase(Locale.ENGLISH);
// String sdkVersion = android.os.Build.VERSION.RELEASE.toLowerCase(Locale.ENGLISH);
boolean setPreDefinedCameraUri = false;
if (!(manufacturer.contains("samsung")) && !(manufacturer.contains("sony"))) {
setPreDefinedCameraUri = true;
}
if (manufacturer.contains("samsung") && model.contains("galaxy nexus")) { //TESTED
setPreDefinedCameraUri = true;
}
if (manufacturer.contains("samsung") && model.contains("gt-n7000") && buildId.contains("imm76l")) { //TESTED
setPreDefinedCameraUri = true;
}
if (buildType.contains("userdebug") && buildDevice.contains("ariesve")) { //TESTED
setPreDefinedCameraUri = true;
}
if (buildType.contains("userdebug") && buildDevice.contains("crespo")) { //TESTED
setPreDefinedCameraUri = true;
}
if (buildType.contains("userdebug") && buildDevice.contains("gt-i9100")) { //TESTED
setPreDefinedCameraUri = true;
}
///////////////////////////////////////////////////////////////////////////
// TEST
if (manufacturer.contains("samsung") && model.contains("sgh-t999l")) { //T-Mobile LTE enabled Samsung S3
setPreDefinedCameraUri = true;
}
if (buildDevice.contains("cooper")) {
setPreDefinedCameraUri = true;
}
if (buildType.contains("userdebug") && buildDevice.contains("t0lte")) {
setPreDefinedCameraUri = true;
}
if (buildType.contains("userdebug") && buildDevice.contains("kot49h")) {
setPreDefinedCameraUri = true;
}
if (buildType.contains("userdebug") && buildDevice.contains("t03g")) {
setPreDefinedCameraUri = true;
}
if (buildType.contains("userdebug") && buildDevice.contains("gt-i9300")) {
setPreDefinedCameraUri = true;
}
if (buildType.contains("userdebug") && buildDevice.contains("gt-i9195")) {
setPreDefinedCameraUri = true;
}
if (buildType.contains("userdebug") && buildDevice.contains("xperia u")) {
setPreDefinedCameraUri = true;
}
///////////////////////////////////////////////////////////////////////////
dateCameraIntentStarted = new Date();
Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
if (setPreDefinedCameraUri) {
// String filename = ImageConfig.getTempFileName();
String filename = System.currentTimeMillis() + ".jpg";
ContentValues values = new ContentValues();
values.put(MediaStore.Images.Media.TITLE, filename);
preDefinedCameraUri = getContentResolver().insert(
MediaStore.Images.Media.EXTERNAL_CONTENT_URI,
values);
intent.putExtra(MediaStore.EXTRA_OUTPUT, preDefinedCameraUri);
}
startActivityForResult(intent, CAPTURE_IMAGE_ACTIVITY_REQUEST_CODE);
} catch (ActivityNotFoundException e) {
logException(e);
onCouldNotTakePhoto();
}
} else {
onSdCardNotMounted();
}
}
/**
* Receives all activity results and triggers onCameraIntentResult if
* the requestCode matches.
*/
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent intent)
{
super.onActivityResult(requestCode, resultCode, intent);
switch (requestCode) {
case CAPTURE_IMAGE_ACTIVITY_REQUEST_CODE: {
onCameraIntentResult(requestCode, resultCode, intent);
break;
}
}
}
/**
* On camera activity result, we try to locate the photo.
* <p/>
* <b>Mediastore:</b>
* First, we try to read the photo being captured from the MediaStore.
* Using a ContentResolver on the MediaStore content, we retrieve the latest image being taken,
* as well as its orientation property and its timestamp.
* If we find an image and it was not taken before the camera intent was called,
* it is the image we were looking for.
* Otherwise, we dismiss the result and try one of the following approaches.
* <b>Intent extra:</b>
* Second, we try to get an image Uri from intent.getData() of the returning intent.
* If this is not successful either, we continue with step 3.
* <b>Default photo Uri:</b>
* If all of the above mentioned steps did not work, we use the image Uri we passed to the camera activity.
*
* #param requestCode
* #param resultCode
* #param intent
*/
protected void onCameraIntentResult(int requestCode, int resultCode, Intent intent)
{
if (resultCode == RESULT_OK) {
Cursor myCursor = null;
Date dateOfPicture = null;
try {
// Create a Cursor to obtain the file Path for the large image
String[] largeFileProjection = {MediaStore.Images.ImageColumns._ID,
MediaStore.Images.ImageColumns.DATA,
MediaStore.Images.ImageColumns.ORIENTATION,
MediaStore.Images.ImageColumns.DATE_TAKEN};
String largeFileSort = MediaStore.Images.ImageColumns._ID + " DESC";
myCursor = getContentResolver().query(
MediaStore.Images.Media.EXTERNAL_CONTENT_URI,
largeFileProjection,
null, null,
largeFileSort);
myCursor.moveToFirst();
if (!myCursor.isAfterLast()) {
// This will actually give you the file path location of the image.
String largeImagePath = myCursor.getString(
myCursor.getColumnIndexOrThrow(MediaStore.Images.ImageColumns.DATA)
);
photoUri = Uri.fromFile(new File(largeImagePath));
if (photoUri != null) {
dateOfPicture = new Date(
myCursor.getLong(
myCursor.getColumnIndexOrThrow(
MediaStore.Images.ImageColumns.DATE_TAKEN)));
if (dateOfPicture != null && dateOfPicture.after(dateCameraIntentStarted)) {
rotateXDegrees = myCursor.getInt(myCursor
.getColumnIndexOrThrow(MediaStore.Images.ImageColumns.ORIENTATION));
} else {
photoUri = null;
}
}
if (myCursor.moveToNext() && !myCursor.isAfterLast()) {
String largeImagePath3rdLocation = myCursor.getString(myCursor
.getColumnIndexOrThrow(MediaStore.Images.ImageColumns.DATA));
Date dateOfPicture3rdLocation = new Date(
myCursor.getLong(myCursor.getColumnIndexOrThrow(
MediaStore.Images.ImageColumns.DATE_TAKEN))
);
if (dateOfPicture3rdLocation != null && dateOfPicture3rdLocation.after(dateCameraIntentStarted)) {
photoUriIn3rdLocation = Uri.fromFile(new File(largeImagePath3rdLocation));
}
}
}
} catch (Exception e) {
logException(e);
} finally {
if (myCursor != null && !myCursor.isClosed()) {
myCursor.close();
}
}
if (photoUri == null) {
try {
photoUri = intent.getData();
} catch (Exception e) {
}
}
if (photoUri == null) {
photoUri = preDefinedCameraUri;
}
try {
if (photoUri != null && new File(photoUri.getPath()).length() <= 0) {
if (preDefinedCameraUri != null) {
Uri tempUri = photoUri;
photoUri = preDefinedCameraUri;
preDefinedCameraUri = tempUri;
}
}
} catch (Exception e) {
}
photoUri = getFileUriFromContentUri(photoUri);
preDefinedCameraUri = getFileUriFromContentUri(preDefinedCameraUri);
try {
if (photoUriIn3rdLocation != null) {
if (photoUriIn3rdLocation.equals(photoUri)
|| photoUriIn3rdLocation.equals(preDefinedCameraUri)) {
photoUriIn3rdLocation = null;
} else {
photoUriIn3rdLocation = getFileUriFromContentUri(photoUriIn3rdLocation);
}
}
} catch (Exception e) {
}
if (photoUri != null) {
onPhotoUriFound();
} else {
onPhotoUriNotFound();
}
} else if (resultCode == Activity.RESULT_CANCELED) {
onCanceled();
} else {
onCanceled();
}
}
/**
* Being called if the photo could be located. The photo's Uri
* and its orientation could be retrieved.
*/
protected void onPhotoUriFound()
{
logMessage("Your photo is stored under: " + photoUri.toString());
}
/**
* Being called if the photo could not be located (Uri == null).
*/
protected void onPhotoUriNotFound()
{
logMessage("Could not find a photoUri that is != null");
}
/**
* Being called if the camera intent could not be started or something else went wrong.
*/
protected void onCouldNotTakePhoto()
{
Toast.makeText(getApplicationContext(), getString(R.string.error_could_not_take_photo), Toast.LENGTH_LONG).show();
}
/**
* Being called if the SD card (or the internal mass storage respectively) is not mounted.
*/
protected void onSdCardNotMounted()
{
Toast.makeText(getApplicationContext(), getString(R.string.error_sd_card_not_mounted), Toast.LENGTH_LONG).show();
}
/**
* Being called if the camera intent was canceled.
*/
protected void onCanceled()
{
logMessage("Camera Intent was canceled");
}
/**
* Logs the passed exception.
*
* #param exception
*/
protected void logException(Exception exception)
{
logMessage(exception.toString());
}
/**
* Logs the passed exception messages.
*
* #param exceptionMessage
*/
protected void logMessage(String exceptionMessage)
{
Log.d(getClass().getName(), exceptionMessage);
}
/**
* Given an Uri that is a content Uri (e.g.
* content://media/external/images/media/1884) this function returns the
* respective file Uri, that is e.g. file://media/external/DCIM/abc.jpg
*
* #param cameraPicUri
* #return Uri
*/
private Uri getFileUriFromContentUri(Uri cameraPicUri)
{
try {
if (cameraPicUri != null
&& cameraPicUri.toString().startsWith("content")) {
String[] proj = {MediaStore.Images.Media.DATA};
Cursor cursor = getContentResolver().query(cameraPicUri, proj, null, null, null);
cursor.moveToFirst();
// This will actually give you the file path location of the image.
String largeImagePath = cursor.getString(cursor
.getColumnIndexOrThrow(MediaStore.Images.ImageColumns.DATA));
cursor.close();
return Uri.fromFile(new File(largeImagePath));
}
return cameraPicUri;
} catch (Exception e) {
return cameraPicUri;
}
}
}

Android Fabric Twitter share listener

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());
}
});
}

Categories

Resources