"There was a problem parsing the package" - How to solve this? - java

I have an updated app in my device storage. I have to install that upper version app from my existing lower version app in a button click. (Like the way dora tv users update their app)
I wrote this code.But it's showing - "There was a problem parsing the package".
There is no error in logcat & no exception. What i need to do now?
App Install error
#RequiresApi(api = Build.VERSION_CODES.M)
private void requestPermission() {
requestPermissions(new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE}, REQUEST_WRITE_PERMISSION);
}
private void havePermission() {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O
&& !getPackageManager().canRequestPackageInstalls()) {
Intent unknownAppSourceIntent = new Intent()
.setAction(Settings.ACTION_MANAGE_UNKNOWN_APP_SOURCES)
.setData(Uri.parse(String.format("package:%s", getPackageName())));
startActivityForResult(unknownAppSourceIntent, Constants.APP_INSTALL_REQUEST);
//unknownAppSourceDialog.launch(unknownAppSourceIntent);
} else {
apkInstall();
}
}
private void apkInstall() {
String path = Environment.getExternalStoragePublicDirectory(
Environment.DIRECTORY_DOWNLOADS).getPath() + File.separator + "test.apk";
Log.d("filePath", path);
File file = new File(path);
if (file.exists() && !file.isDirectory()) {
// do something
Log.d("fileExist", file.getName());
}
Intent intent;
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
Uri apkUri = FileProvider.getUriForFile(this, BuildConfig.APPLICATION_ID + ".provider", file);
intent = new Intent(Intent.ACTION_INSTALL_PACKAGE);
intent.setData(apkUri);
intent.setFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
} else {
Uri apkUri = Uri.fromFile(file);
intent = new Intent(Intent.ACTION_VIEW);
intent.setDataAndType(apkUri, "application/vnd.android.package-archive");
intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
}
try {
startActivityForResult(intent, Constants.APP_INSTALL_REQUEST);
} catch (Exception e) {
e.printStackTrace();
BizUiUtils.showToast(this, "Error in installing App, please try again");
}
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == Constants.APP_INSTALL_REQUEST) {
apkInstall();
}
}

Related

Allowing microphone access(permission) in WebView Android Studio

send audio is not working can you please help
I would appreciate if you show me where to write the codes.
send audio is not working can you please help
I would appreciate if you show me where to write the codes.
send audio is not working can you please help
I would appreciate if you show me where to write the codes.
public class MainActivity extends AppCompatActivity {
private WebView web;
String webUrl = "https://tuk.az";
public Context context;
private static final String TAG = MainActivity.class.getSimpleName();
private static final int FILECHOOSER_RESULTCODE = 1;
private ValueCallback<Uri> mUploadMessage;
private Uri mCapturedImageURI = null;
// the same for Android 5.0 methods only
private ValueCallback<Uri[]> mFilePathCallback;
private String mCameraPhotoPath;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
web = (WebView) findViewById(R.id.myweb);
web.loadUrl(webUrl);
WebSettings mywebsettings = web.getSettings();
mywebsettings.setJavaScriptEnabled(true);
web.setWebViewClient(new WebViewClient());
// improve webview performance
web.getSettings().setAllowFileAccess(true);
web.getSettings().setRenderPriority(WebSettings.RenderPriority.HIGH);
web.getSettings().setCacheMode(WebSettings.LOAD_CACHE_ELSE_NETWORK);
web.getSettings().setAppCacheEnabled(true);
web.setScrollBarStyle(View.SCROLLBARS_INSIDE_OVERLAY);
mywebsettings.setDomStorageEnabled(true);
mywebsettings.setLayoutAlgorithm(WebSettings.LayoutAlgorithm.NARROW_COLUMNS);
mywebsettings.setUseWideViewPort(true);
mywebsettings.setSaveFormData(true);
mywebsettings.setAllowFileAccess(true);
mywebsettings.setAllowContentAccess(true);
// mywebsettings.setSavePassword(true);
// mywebsettings.setEnableSmoothTransition(true);
web.setWebChromeClient(new WebChromeClient(){
// for Lollipop, all in one
public boolean onShowFileChooser(
WebView webView, ValueCallback<Uri[]> filePathCallback,
WebChromeClient.FileChooserParams fileChooserParams) {
if (mFilePathCallback != null) {
mFilePathCallback.onReceiveValue(null);
}
mFilePathCallback = filePathCallback;
Intent takePictureIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
if (takePictureIntent.resolveActivity(getPackageManager()) != null) {
// create the file where the photo should go
File photoFile = null;
try {
photoFile = createImageFile();
takePictureIntent.putExtra("PhotoPath", mCameraPhotoPath);
} catch (IOException ex) {
// Error occurred while creating the File
Log.e(TAG, "Unable to create Image File", ex);
}
// continue only if the file was successfully created
if (photoFile != null) {
mCameraPhotoPath = "file:" + photoFile.getAbsolutePath();
takePictureIntent.putExtra(MediaStore.EXTRA_OUTPUT,
Uri.fromFile(photoFile));
} else {
takePictureIntent = null;
}
}
Intent contentSelectionIntent = new Intent(Intent.ACTION_GET_CONTENT);
contentSelectionIntent.addCategory(Intent.CATEGORY_OPENABLE);
contentSelectionIntent.setType("image/*");
Intent[] intentArray;
if (takePictureIntent != null) {
intentArray = new Intent[]{takePictureIntent};
} else {
intentArray = new Intent[0];
}
Intent chooserIntent = new Intent(Intent.ACTION_CHOOSER);
chooserIntent.putExtra(Intent.EXTRA_INTENT, contentSelectionIntent);
chooserIntent.putExtra(Intent.EXTRA_TITLE, getString(R.string.image_chooser));
chooserIntent.putExtra(Intent.EXTRA_INITIAL_INTENTS, intentArray);
startActivityForResult(chooserIntent, FILECHOOSER_RESULTCODE);
return true;
}
// creating image files (Lollipop only)
private File createImageFile() throws IOException {
File imageStorageDir = new File(Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES), "DirectoryNameHere");
if (!imageStorageDir.exists()) {
imageStorageDir.mkdirs();
}
// create an image file name
imageStorageDir = new File(imageStorageDir + File.separator + "IMG_" + String.valueOf(System.currentTimeMillis()) + ".jpg");
return imageStorageDir;
}
// openFileChooser for Android 3.0+
public void openFileChooser(ValueCallback<Uri> uploadMsg, String acceptType) {
mUploadMessage = uploadMsg;
try {
File imageStorageDir = new File(Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES), "DirectoryNameHere");
if (!imageStorageDir.exists()) {
imageStorageDir.mkdirs();
}
File file = new File(imageStorageDir + File.separator + "IMG_" + String.valueOf(System.currentTimeMillis()) + ".jpg");
mCapturedImageURI = Uri.fromFile(file); // save to the private variable
final Intent captureIntent = new Intent(android.provider.MediaStore.ACTION_IMAGE_CAPTURE);
captureIntent.putExtra(MediaStore.EXTRA_OUTPUT, mCapturedImageURI);
// captureIntent.putExtra(MediaStore.EXTRA_SCREEN_ORIENTATION, ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
Intent i = new Intent(Intent.ACTION_GET_CONTENT);
i.addCategory(Intent.CATEGORY_OPENABLE);
i.setType("image/*");
Intent chooserIntent = Intent.createChooser(i, getString(R.string.image_chooser));
chooserIntent.putExtra(Intent.EXTRA_INITIAL_INTENTS, new Parcelable[]{captureIntent});
startActivityForResult(chooserIntent, FILECHOOSER_RESULTCODE);
} catch (Exception e) {
Toast.makeText(getBaseContext(), "Camera Exception:" + e, Toast.LENGTH_LONG).show();
}
}
// openFileChooser for Android < 3.0
public void openFileChooser(ValueCallback<Uri> uploadMsg) {
openFileChooser(uploadMsg, "");
}
// openFileChooser for other Android versions
/* may not work on KitKat due to lack of implementation of openFileChooser() or onShowFileChooser()
https://code.google.com/p/android/issues/detail?id=62220
however newer versions of KitKat fixed it on some devices */
public void openFileChooser(ValueCallback<Uri> uploadMsg, String acceptType, String capture) {
openFileChooser(uploadMsg, acceptType);
}
});
//download
if(Build.VERSION.SDK_INT>= Build.VERSION_CODES.M){
if(checkSelfPermission(Manifest.permission.WRITE_EXTERNAL_STORAGE) == PackageManager.PERMISSION_DENIED){
Log.d("permission", "permission denied to WRITE_EXTERNAL_STORAGE - requesting it");
String[] permissions = {Manifest.permission.WRITE_EXTERNAL_STORAGE};
requestPermissions(permissions, 1);
}
}
//handle download
web.setDownloadListener(new DownloadListener() {
#Override
public void onDownloadStart(String url, String userAgent, String contentDisposition, String mimeType, long contentLenght) {
DownloadManager.Request request = new DownloadManager.Request(Uri.parse(url));
request.setMimeType(mimeType);
String cookies = CookieManager.getInstance().getCookie(url);
request.addRequestHeader("cookie", cookies);
request.addRequestHeader("User-Agent",userAgent);
request.setDescription("Downloading file...");
request.setTitle(URLUtil.guessFileName(url,contentDisposition,mimeType));
request.allowScanningByMediaScanner();
request.setNotificationVisibility(DownloadManager.Request.VISIBILITY_VISIBLE_NOTIFY_COMPLETED);
request.setDestinationInExternalPublicDir(Environment.DIRECTORY_DOWNLOADS,URLUtil.guessFileName(url, contentDisposition, mimeType));
DownloadManager dm = (DownloadManager) getSystemService(DOWNLOAD_SERVICE);
dm.enqueue(request);
Toast.makeText(getApplicationContext(), "Downloading File", Toast.LENGTH_SHORT).show();
}
});
}
// return here when file selected from camera or from SD Card
#Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
// code for all versions except of Lollipop
if (Build.VERSION.SDK_INT < Build.VERSION_CODES.LOLLIPOP) {
if (requestCode == FILECHOOSER_RESULTCODE) {
if (null == this.mUploadMessage) {
return;
}
Uri result = null;
try {
if (resultCode != RESULT_OK) {
result = null;
} else {
// retrieve from the private variable if the intent is null
result = data == null ? mCapturedImageURI : data.getData();
}
} catch (Exception e) {
Toast.makeText(getApplicationContext(), "activity :" + e, Toast.LENGTH_LONG).show();
}
mUploadMessage.onReceiveValue(result);
mUploadMessage = null;
}
} // end of code for all versions except of Lollipop
// start of code for Lollipop only
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
if (requestCode != FILECHOOSER_RESULTCODE || mFilePathCallback == null) {
super.onActivityResult(requestCode, resultCode, data);
return;
}
Uri[] results = null;
// check that the response is a good one
if (resultCode == Activity.RESULT_OK) {
if (data == null || data.getData() == null) {
// if there is not data, then we may have taken a photo
if (mCameraPhotoPath != null) {
results = new Uri[]{Uri.parse(mCameraPhotoPath)};
}
} else {
String dataString = data.getDataString();
if (dataString != null) {
results = new Uri[]{Uri.parse(dataString)};
}
}
}
mFilePathCallback.onReceiveValue(results);
mFilePathCallback = null;
} // end of code for Lollipop only
}
#Override
public void onBackPressed() {
if(web.canGoBack()){`enter code here`
web.goBack();
}else{
super.onBackPressed();
}
}
}
Did you set the permission in the manifest? You can do that by implementing this code:
<manifest ... >
<uses-permission android:name="android.permission.RECORD_AUDIO"/>
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>
<uses-permission android:name="android.permission.STORAGE"/>
...
</manifest>

Android - Unable to view image saved in new directory when I try to upload it again

I am uploading a image from gallery and saving it into new directory after cropping it (using Android-image-cropper library).
The directory is getting created and image is getting saved successfully.
It can be found in File Explorer, but when I try upload the same image in the app it is not showing up.
I also tried saving the image in existing directory, the directory is visible in the search and not the image in it, but it can be found in File Explorer.
EditActivity
save_button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
saveImage();
}
});
}
public void saveImage(){
try {
InputStream inputStream = getContentResolver().openInputStream(resultUri);
bitmap = BitmapFactory.decodeStream(inputStream);;
} catch (FileNotFoundException e) {
e.printStackTrace();
}
File file = Environment.getExternalStorageDirectory();
File dir = new File(file.getAbsolutePath()+"/Pictures/");
if(!dir.exists()){
dir.mkdirs();
}
File f = new File(dir,System.currentTimeMillis()+".jpg");
try {
outputStream = new FileOutputStream(f);
} catch (FileNotFoundException e) {
e.printStackTrace();
}
bitmap.compress(Bitmap.CompressFormat.JPEG,90,outputStream);
Toast.makeText(getApplicationContext(),f.toString(),Toast.LENGTH_SHORT).show();
try {
outputStream.flush();
} catch (IOException e) {
e.printStackTrace();
}
try {
outputStream.close();
} catch (IOException e) {
e.printStackTrace();
}
}
MainActivity
private void cam_permission() {
if(ContextCompat.checkSelfPermission(this, Manifest.permission.CAMERA)!= PackageManager.PERMISSION_GRANTED){
ActivityCompat.requestPermissions(this,new String[] {Manifest.permission.CAMERA}, CAMERA_PERMISSION_CODE);
} else{
dispatchTakePictureIntent();
}
}
private void storage_permission(){
if(ContextCompat.checkSelfPermission(this, Manifest.permission.WRITE_EXTERNAL_STORAGE)!= PackageManager.PERMISSION_GRANTED){
ActivityCompat.requestPermissions(this,new String[] {Manifest.permission.WRITE_EXTERNAL_STORAGE}, STORAGE_PERMISSION_CODE);
} else{
Intent gallery = new Intent(Intent.ACTION_PICK,MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
startActivityForResult(gallery, GALLERY_REQUEST_CODE);
}
}
#Override
public void onRequestPermissionsResult(int requestCode, #NonNull String[] permissions, #NonNull int[] grantResults) {
if (requestCode == CAMERA_PERMISSION_CODE) {
if (grantResults.length > 0
&& grantResults[0] == PackageManager.PERMISSION_GRANTED) {
} else {
Toast.makeText(this, "Camera Permission is required", Toast.LENGTH_SHORT).show();
}
}
else if (requestCode == STORAGE_PERMISSION_CODE) {
if (grantResults.length > 0
&& grantResults[0] == PackageManager.PERMISSION_GRANTED) {
}
else {
Toast.makeText(MainActivity.this, "Storage Permission is required", Toast.LENGTH_SHORT).show();
}
}
super.onRequestPermissionsResult(requestCode, permissions, grantResults);
}
#Override
protected void onActivityResult(int requestCode, int resultCode, #Nullable Intent data) {
if (requestCode == CAMERA_REQUEST_CODE) {
if (resultCode == Activity.RESULT_OK) {
File file = new File(currentPhotoPath);
Uri contentUri = Uri.fromFile(file);
Intent intent = new Intent(Intent.ACTION_VIEW);
intent .setClass(MainActivity.this, EditActivity.class);
intent .putExtra("imageUri", contentUri.toString());
startActivity(intent);
}
}
if (requestCode == GALLERY_REQUEST_CODE) {
if (resultCode == Activity.RESULT_OK) {
Uri contentUri = data.getData();
String timeStamp = new SimpleDateFormat("yyyyMMdd_HHmmss").format(new Date());
Intent intent = new Intent(Intent.ACTION_VIEW);
intent .setClass(MainActivity.this, EditActivity.class);
intent .putExtra("imageUri", contentUri.toString());
startActivity(intent);
}
}
super.onActivityResult(requestCode, resultCode, data);
}
private File createImageFile() throws IOException {
// Create an image file name
String timeStamp = new SimpleDateFormat("yyyyMMdd_HHmmss").format(new Date());
String imageFileName = "JPEG_" + timeStamp + "_";
File storageDir = getExternalFilesDir(Environment.DIRECTORY_PICTURES);
File image = File.createTempFile(
imageFileName, /* prefix */
".jpg", /* suffix */
storageDir /* directory */
);
// Save a file: path for use with ACTION_VIEW intents
currentPhotoPath = image.getAbsolutePath();
return image;
}
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(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
}
// Continue only if the File was successfully created
if (photoFile != null) {
Uri photoURI = FileProvider.getUriForFile(this,
"com.example.android.fileprovider",
photoFile);
takePictureIntent.putExtra(MediaStore.EXTRA_OUTPUT, photoURI);
startActivityForResult(takePictureIntent, CAMERA_REQUEST_CODE);
}
}
}
AndroidManifest.xml
<uses-permission android:name="android.permission.CAMERA" />
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />

Android VIEW intent with content Uri

I am creating a App, which should save reference documents, saved on the device.
I am receiving the content URI for these documents in the following way:
private void selectDocument() {
Intent chooseFile;
chooseFile = new Intent(Intent.ACTION_GET_CONTENT);
chooseFile.addCategory(Intent.CATEGORY_OPENABLE);
chooseFile.setType("*/*");
if (chooseFile.resolveActivity(getPackageManager()) != null)
startActivityForResult(chooseFile, ACTIVITY_CHOOSE_FILE);
}
#Override
protected void onActivityResult(int requestCode, int resultCode, #Nullable Intent data) {
if (resultCode != RESULT_OK) return;
if (requestCode == ACTIVITY_CHOOSE_FILE) {
try {
binding.txtLink.setText(URLDecoder.decode(data.getDataString(),"UTF-8"));
binding.btnLink.setTag(false);
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
} else {
super.onActivityResult(requestCode, resultCode, data);
}
}
after displaying the url to the user, he should be able to open the document.
And i am not really sure how to do that, since I only get the contentURI.
What i am currently trying is this:
private void openDocument() {
String file = binding.txtLink.getText().toString();
if (file.isEmpty()) {
return;
}
Intent intent;
String extension = file.substring(file.lastIndexOf(".") + 1);
String mimeType = MimeTypeMap.getSingleton().getMimeTypeFromExtension(extension);
intent = new Intent(Intent.ACTION_VIEW);
intent.setData(Uri.parse(file));
if (intent.resolveActivity(getPackageManager()) != null) {
startActivity(intent);
} else {
Snackbar.make(binding.root, "Keine Anwendung zum öffnen der Datei installiert", Snackbar.LENGTH_LONG).show();
}
}
This already opens the correct App, but they can't find the files.
What would i need to do, to enable this behavior?
Or do i have to copy the files to my app directory and open them from there?

Need to upload only pdf or any doc type format in android

I'm trying to upload only pdf or any doc type files but .gif and .psd format is also getting added. I need to upload only supported file format.
resume_add.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
if (ActivityCompat.checkSelfPermission(MyProfileActivity.this, android.Manifest
.permission.WRITE_EXTERNAL_STORAGE) != PackageManager
.PERMISSION_GRANTED) {
requestPermissions(new String[]{android.Manifest.permission
.WRITE_EXTERNAL_STORAGE}, 1);
} else {
Intent target = FileUtils.createGetContentIntent();
Intent intent = Intent.createChooser(target, "Select File");
intent.setType("application/msword,application/pdf");
try {
startActivityForResult(intent, SELECT_PICTURE);
} catch (ActivityNotFoundException ignored) {
}
}
} else {
Intent target = FileUtils.createGetContentIntent();
Intent intent = Intent.createChooser(target, "Select File");
try {
startActivityForResult(intent, SELECT_PICTURE);
} catch (ActivityNotFoundException ignored) {
}
}
}
});
Use the following code snippet for that
Intent intent = new Intent(Intent.ACTION_GET_CONTENT);
intent.setType("application/pdf|application/msword");
startActivityForResult(intent, PICK_DOC_REQUEST_CODE);
It's working for me hope it's works for you!

Uri.fromFile returning null?

For some reason outputFileUri returns null in my onActivityResult:
Uri selectedImageUri;
if (isCamera) {
selectedImageUri = outputFileUri;
I don't understand why. Please take a look at my code and see where I go wrong. I let the user take 4 images by choosing from gallery or using the camera. The ones that the user takes with the camera won't show presumably because their uri is null. outputFileUri is a class variable.
takePictureIntent():
private void dispatchTakePictureIntent() {
for(int i = 0; i < 4; i++) {
Intent takePictureIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
if (takePictureIntent.resolveActivity(getPackageManager()) != null) {
// Create the File where the photo should go
File photoFile = null;
try {
photoFile = createImageFile();
outputFileUri = Uri.fromFile(photoFile);
} catch (IOException ex) {
Log.w("error","IOException");
}catch (NullPointerException nullEx) {
Log.w("error","NullPointerException");
}
// Camera.
final List<Intent> cameraIntents = new ArrayList<Intent>();
final Intent captureIntent = new Intent(android.provider.MediaStore.ACTION_IMAGE_CAPTURE);
final PackageManager packageManager = getPackageManager();
final List<ResolveInfo> listCam = packageManager.queryIntentActivities(captureIntent, 0);
for (ResolveInfo res : listCam) {
final String packageName = res.activityInfo.packageName;
final Intent intent = new Intent(captureIntent);
intent.setComponent(new ComponentName(res.activityInfo.packageName, res.activityInfo.name));
intent.setPackage(packageName);
intent.putExtra(MediaStore.EXTRA_OUTPUT, Uri.fromFile(photoFile));
cameraIntents.add(intent);
}
// Filesystem.
final Intent galleryIntent = new Intent();
galleryIntent.setType("image/*");
galleryIntent.setAction(Intent.ACTION_OPEN_DOCUMENT);
// Chooser of filesystem options.
final Intent chooserIntent = Intent.createChooser(galleryIntent, "Select Source");
// Add the camera options.
chooserIntent.putExtra(Intent.EXTRA_INITIAL_INTENTS, cameraIntents.toArray(new Parcelable[cameraIntents.size()]));
if(id.equals(HAPPY_ID))
startActivityForResult(chooserIntent, REQUEST_HAPPY_PHOTO);
if(id.equals(SURPRISED_ID))
startActivityForResult(chooserIntent, REQUEST_SURPRISED_PHOTO);
if(id.equals(AFRAID_ID))
startActivityForResult(chooserIntent, REQUEST_AFRAID_PHOTO);
if(id.equals(UPSET_ID))
startActivityForResult(chooserIntent, REQUEST_UPSET_PHOTO);
if(id.equals(SAD_ID))
startActivityForResult(chooserIntent, REQUEST_SAD_PHOTO);
}
}
}
onActivityResult():
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if (resultCode == RESULT_OK) {
if (requestCode == REQUEST_HAPPY_PHOTO || requestCode == REQUEST_SURPRISED_PHOTO || requestCode == REQUEST_AFRAID_PHOTO ||
requestCode == REQUEST_UPSET_PHOTO || requestCode == REQUEST_SAD_PHOTO) {
final boolean isCamera;
if (data == null) {
isCamera = true;
} else {
final String action = data.getAction();
if (action == null) {
isCamera = false;
} else {
isCamera = action.equals(android.provider.MediaStore.ACTION_IMAGE_CAPTURE);
}
}
Uri selectedImageUri;
if (isCamera) {
selectedImageUri = outputFileUri;
} else {
selectedImageUri = data == null ? null : data.getData();
}
//Log.d("doing ids", "right before id");
//Log.d("doing ids", "id is " + id);
if(requestCode == REQUEST_HAPPY_PHOTO) {
//Log.d("doing ids", "in happy");
happyList.add(selectedImageUri);
}
if(requestCode == REQUEST_SURPRISED_PHOTO) {
//Log.d("doing ids", "in surprised");
surprisedList.add(selectedImageUri);
}
if(requestCode == REQUEST_AFRAID_PHOTO) {
//Log.d("doing ids", "in surprised");
afraidList.add(selectedImageUri);
}
if(requestCode == REQUEST_UPSET_PHOTO) {
//Log.d("doing ids", "in surprised");
upsetList.add(selectedImageUri);
}
if(requestCode == REQUEST_SAD_PHOTO) {
//Log.d("doing ids", "in surprised");
sadList.add(selectedImageUri);
}
}
}
}
My createImageFile():
private File createImageFile() throws IOException {
// Create an image file name
String timeStamp = new SimpleDateFormat("yyyyMMdd_HHmmss").format(new Date());
String imageFileName = "JPEG_" + timeStamp;
File storageDir = getExternalFilesDir(Environment.DIRECTORY_PICTURES);
File image = File.createTempFile(
imageFileName, /* prefix */
".jpg", /* suffix */
storageDir /* directory */
);
// Save a file: path for use with ACTION_VIEW intents
mCurrentPhotoPath = "file:" + image.getAbsolutePath();
return image;
}
I had a similar problem, I solved it by holding a reference to the URI that I pass to the Intent. This allowed me to not rely on the Intent to return the URI.
Here's the code:
private Uri startCameraFileUri;
private void startCameraIntent() {
final Intent intentCamera = new Intent(android.provider.MediaStore.ACTION_IMAGE_CAPTURE);
try {
startCameraFileUri = Uri.fromFile(Utils.getNewFile());
intentCamera.putExtra(MediaStore.EXTRA_OUTPUT, startCameraFileUri);
intentCamera.putExtra("return-data", true);
startActivityForResult(intentCamera, IConstants.REQUEST_TAKE_PICTURE);
} catch (Exception e) {
e.printStackTrace();
}
}
public void openGalleryIntent() {
final boolean isKitKat = Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT;
if (isKitKat) {
final Intent openGalleryIntent = new Intent(Intent.ACTION_OPEN_DOCUMENT);
openGalleryIntent.addCategory(Intent.CATEGORY_OPENABLE);
openGalleryIntent.setType("image/*");
openGalleryIntent.putExtra(Intent.EXTRA_LOCAL_ONLY, true);
startActivityForResult(
Intent.createChooser(openGalleryIntent, getString(R.string.PROFILE_PIC_LIBRARY)),
IConstants.REQUEST_GALLERY);
} else {
final Intent openGalleryIntent = new Intent(Intent.ACTION_PICK,
android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
openGalleryIntent.putExtra(Intent.EXTRA_LOCAL_ONLY, true);
startActivityForResult(Intent.createChooser(openGalleryIntent, getString(R.string.PROFILE_PIC_LIBRARY)), IConstants.REQUEST_GALLERY);
}
}
#Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
if (resultCode == Activity.RESULT_OK) {
final Uri uri;
if(data != null) {
uri = data.getData();
}
else{
uri = startCameraFileUri;
}
switch (requestCode) {
case IConstants.REQUEST_GALLERY:
case IConstants.REQUEST_TAKE_PICTURE:
try {
if (!uri.toString().isEmpty()) {
loadUserPhoto(uri.toString());
}
} catch (Exception e) {
e.printStackTrace();
}
break;
}
}
}

Categories

Resources