I'm trying to load images from Camera and Gallery to load inside Tensor flow lite model.
When loading image from gallery, I'm getting following errors.
2021-01-02 11:48:03.309 9858-9858/com.example.coco_classif E/BitmapFactory: Unable to decode stream: java.io.FileNotFoundException: /storage/emulated/0/Pictures/20200714_135735 (1).jpg: open failed: EACCES (Permission denied)
2021-01-02 11:48:03.332 9858-9858/com.example.coco_classif E/ErrorĀ log: java.lang.NullPointerException: Cannot load null bitmap.
NOTE: Issues seems coming from the try catch block, loading from camera works fine
mainfest
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.example.coco_classif">
<uses-permission android:name="android.permission.CAMERA" />
<uses-feature android:name="android.hardware.camera" />
<uses-feature android:name="android.hardware.camera.autofocus" />
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
<application
android:allowBackup="true"
android:icon="#mipmap/ic_launcher"
android:label="#string/app_name"
android:roundIcon="#mipmap/ic_launcher_round"
android:supportsRtl="true"
android:theme="#style/Theme.Coco_classif">
<activity android:name=".MainActivity">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
</application>
</manifest>
Main Activity
package com.example.coco_classif;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.appcompat.app.AlertDialog;
import androidx.appcompat.app.AppCompatActivity;
import android.Manifest;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.media.Image;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.provider.MediaStore;
import android.util.Log;
import android.view.View;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.Toast;
import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.Objects;
public class MainActivity extends AppCompatActivity {
private static final int CAMERA_PERMISSION_REQUEST_CODE = 1000;
private static final int CAMERA_REQUEST_CODE = 10001;
private ImageView imageView;
private ListView listView;
private ImageClassifier imageClassifier;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
inaializeUIElements();
}
private void inaializeUIElements() {
imageView = findViewById(R.id.iv_capture);
listView = findViewById(R.id.lv_probabilities);
Button takepicture = findViewById(R.id.bt_take_picture);
try {
imageClassifier = new ImageClassifier(this);
} catch (IOException e) {
Log.e("Error While Creating Image Classifier", "Error" +e);
}
takepicture.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if(hasPermission()) {
selectImage();
}else{
requestPermission();
}
}
});
}
#Override
protected void onActivityResult(int requestCode, int resultCode, #Nullable Intent data) {
if (resultCode == RESULT_OK) {
if (requestCode == 1) {
Bitmap photo = (Bitmap) Objects.requireNonNull(Objects.requireNonNull(data).getExtras()).get("data");
imageView.setImageBitmap(photo);
List<ImageClassifier.Recognition> predictions = imageClassifier.recognizeImage(photo, 0);
final List<String> predictionList = new ArrayList<>();
for(ImageClassifier.Recognition recog: predictions){
predictionList.add("Label: " + recog.getName() + "Confidence: " + recog.getConfidance());
}
ArrayAdapter<String> predictionsAdapter = new ArrayAdapter<>(
this,R.layout.support_simple_spinner_dropdown_item,predictionList);
listView.setAdapter(predictionsAdapter);
}
else if (requestCode == 2) {
try {
Uri selectedImage = data.getData();
String[] filePath = new String[]{MediaStore.Images.Media.DATA};
Cursor c = getContentResolver().query(selectedImage,filePath, null, null, null);
c.moveToFirst();
int columnIndex = c.getColumnIndex(filePath[0]);
String picturePath = c.getString(columnIndex);
c.close();
Bitmap thumbnail = (BitmapFactory.decodeFile(picturePath));
Log.w("path of image from gallery......******************.........", picturePath+"");
Toast.makeText(this,picturePath.toString(),Toast.LENGTH_LONG).show();
imageView.setImageBitmap(thumbnail);
List<ImageClassifier.Recognition> predictions = imageClassifier.recognizeImage(thumbnail, 0);
final List<String> predictionList = new ArrayList<>();
for(ImageClassifier.Recognition recog: predictions){
predictionList.add("Label: " + recog.getName() + "Confidence: " + recog.getConfidance());
}
ArrayAdapter<String> predictionsAdapter = new ArrayAdapter<>(
this,R.layout.support_simple_spinner_dropdown_item,predictionList);
listView.setAdapter(predictionsAdapter);
}catch (Exception e){
Toast.makeText(this,e.toString(),Toast.LENGTH_LONG).show();
Log.e("Error log", e.toString());
}
}
}
super.onActivityResult(requestCode, resultCode, data);
}
#Override
public void onRequestPermissionsResult(int requestCode, #NonNull String[] permissions, #NonNull int[] grantResults) {
super.onRequestPermissionsResult(requestCode, permissions, grantResults);
if(hasAllPermissions(grantResults)){
openCamera();
}else {
requestPermission();
}
}
private boolean hasAllPermissions(int[] grantResults) {
for(int result : grantResults){
if (result == PackageManager.PERMISSION_DENIED)
return false;
}
return true;
}
private void requestPermission() {
if(Build.VERSION.SDK_INT>=Build.VERSION_CODES.M){
if(shouldShowRequestPermissionRationale(Manifest.permission.CAMERA)){
Toast.makeText(this," Permission required",Toast.LENGTH_SHORT).show();
}
requestPermissions(new String[]{Manifest.permission.CAMERA}, CAMERA_PERMISSION_REQUEST_CODE);
}
}
private void openCamera() {
Intent camerIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
startActivityForResult(camerIntent,CAMERA_REQUEST_CODE);
}
private boolean hasPermission() {
if(Build.VERSION.SDK_INT>=Build.VERSION_CODES.M){
return checkSelfPermission(Manifest.permission.CAMERA)== PackageManager.PERMISSION_GRANTED;
}
return true;
}
private void selectImage() {
final CharSequence[] options = {"Take Photo", "Choose from Gallery", "Cancel"};
AlertDialog.Builder builder = new AlertDialog.Builder(MainActivity.this);
builder.setTitle("Add Photo!");
builder.setItems(options, new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int item) {
if (options[item].equals("Take Photo")) {
Intent camerIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
startActivityForResult(camerIntent,1);
} else if (options[item].equals("Choose 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();
}
}
Note: This code snippet worked for only writing a text file and I used this method to solve
open failed: EACCES (Permission denied)
I know your Implementation has to deal with images and that is causing this 2021-01-02 11:48:03.332 9858-9858/com.example.coco_classif E/Error log: java.lang.NullPointerException: Cannot load null bitmap.
Also, check out this Exception 'open failed: EACCES (Permission denied)' on Android
I had the exact same problem, all I did was create a directory and write a text file in it.
Also, it is a good practice to create a new filename for images programmatically, use the Date formatter.
As I can see you are using an alert dialog to select images, I suggest you should not do it that way, alert dialog causes a lot of synchronization problems.
This code is tested on android Q One Plus 6t works fine without any errors.
public void generateNoteOnSD(Context context, String sFileName, String sBody) {
try {
File root = new File(String.valueOf(Environment.getExternalStorageDirectory())+"/sysInfoReports");
if (!root.exists()) {
root.mkdirs();
}
File gpxfile = new File(root, sFileName);
FileWriter writer = new FileWriter(gpxfile);
writer.append(sBody);
writer.flush();
writer.close();
} catch (IOException e) {
e.printStackTrace();
}
}
Check you permissions
: Old storage permissions do not work on Android R.
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" tools:ignore="ScopedStorage" />
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE"/>
Related
I am trying to create a webView for my web application in which i also can upload pictures using camera, i get the option to choose between camera or file manager and the file manager works perfect. With the camera option it opens the camera but when i then click on capture and send it does not return anything and does not load the img into the input field.
After doing some research i figured out that response.getData().getDataString() does not return anything when using the camera to capture a picture but does return something when using the file explorer to send a picture
Here is my MainActivity.java
package com.webview.android;
import androidx.activity.result.ActivityResult;
import androidx.activity.result.ActivityResultCallback;
import androidx.activity.result.ActivityResultLauncher;
import androidx.activity.result.contract.ActivityResultContracts;
import androidx.appcompat.app.AppCompatActivity;
import android.annotation.SuppressLint;
import android.app.Activity;
import android.content.Intent;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.os.Environment;
import android.provider.MediaStore;
import android.util.Log;
import android.webkit.PermissionRequest;
import android.webkit.ValueCallback;
import android.webkit.WebChromeClient;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.Toast;
import com.karan.churi.PermissionManager.PermissionManager;
import java.io.File;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;
public class MainActivity extends AppCompatActivity {
private WebView webView;
PermissionManager permissionManager;
private static final String TAG = MainActivity.class.getSimpleName();
private String mCM;
private ValueCallback<Uri> mUM;
private ValueCallback<Uri[]> mUMA;
private ActivityResultLauncher<Intent> imgFinished = registerForActivityResult(
new ActivityResultContracts.StartActivityForResult(),
new ActivityResultCallback<ActivityResult>() {
#Override
public void onActivityResult(ActivityResult response) {
if (Build.VERSION.SDK_INT >= 21) {
Uri[] results = null;
//Check if response is positive
if (response.getResultCode() == Activity.RESULT_OK) {
if (null == mUMA) {
return;
}
if (response.getData() == null) {
//Capture Photo if no image available
if (mCM != null) {
results = new Uri[]{Uri.parse(mCM)};
}
} else {
Log.e(TAG, "TEST5");
String dataString = response.getData().getDataString();
Log.e(TAG, String.valueOf(response.getData().getDataString()));
if (dataString != null) {
Log.e(TAG, "TEST6");
results = new Uri[]{Uri.parse(dataString)};
}
}
}
mUMA.onReceiveValue(results);
mUMA = null;
} else {
if (null == mUM) return;
Uri result = response == null || response.getResultCode() != RESULT_OK ? null : response.getData().getData();
mUM.onReceiveValue(result);
mUM = null;
}
}
}
);
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
webView = findViewById(R.id.webView);
webView.getSettings().setJavaScriptEnabled(true);
webView.loadUrl("https://hbwfc-acc.9knots.nl/app");
WebSettings MyWebviewSettings = webView.getSettings();
MyWebviewSettings.setAllowFileAccessFromFileURLs(true);
MyWebviewSettings.setAllowUniversalAccessFromFileURLs(true);
MyWebviewSettings.setJavaScriptCanOpenWindowsAutomatically(true);
MyWebviewSettings.setJavaScriptEnabled(true);
MyWebviewSettings.setDomStorageEnabled(true);
MyWebviewSettings.setJavaScriptCanOpenWindowsAutomatically(true);
MyWebviewSettings.setBuiltInZoomControls(true);
MyWebviewSettings.setAllowFileAccess(true);
MyWebviewSettings.setSupportZoom(true);
MyWebviewSettings.setAllowContentAccess(true);
MyWebviewSettings.setMediaPlaybackRequiresUserGesture(false);
webView.setWebChromeClient(new WebChromeClient() {
#Override
public void onPermissionRequest(final PermissionRequest request) {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
request.grant(request.getResources());
}
}
//For Android 3.0+
public void openFileChooser(ValueCallback<Uri> uploadMsg){
mUM = uploadMsg;
Intent i = new Intent(Intent.ACTION_GET_CONTENT);
i.addCategory(Intent.CATEGORY_OPENABLE);
i.setType("*/*");
imgFinished.launch(Intent.createChooser(i,"File Chooser"));
}
// For Android 3.0+, above method not supported in some android 3+ versions, in such case we use this
public void openFileChooser(ValueCallback uploadMsg, String acceptType){
mUM = uploadMsg;
Intent i = new Intent(Intent.ACTION_GET_CONTENT);
i.addCategory(Intent.CATEGORY_OPENABLE);
i.setType("*/*");
imgFinished.launch(Intent.createChooser(i, "File Browser"));
}
//For Android 4.1+
public void openFileChooser(ValueCallback<Uri> uploadMsg, String acceptType, String capture){
mUM = uploadMsg;
Intent i = new Intent(Intent.ACTION_GET_CONTENT);
i.addCategory(Intent.CATEGORY_OPENABLE);
i.setType("*/*");
imgFinished.launch(Intent.createChooser(i, "File Chooser"));
}
//For Android 5.0+
public boolean onShowFileChooser(
WebView webView, ValueCallback<Uri[]> filePathCallback,
WebChromeClient.FileChooserParams fileChooserParams){
if(mUMA != null){
mUMA.onReceiveValue(null);
}
mUMA = filePathCallback;
Intent takePictureIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
if(takePictureIntent.resolveActivity(MainActivity.this.getPackageManager()) != null){
File photoFile = null;
try{
photoFile = createImageFile();
takePictureIntent.putExtra("PhotoPath", mCM);
}catch(IOException ex){
Log.e(TAG, "Image file creation failed", ex);
}
if(photoFile != null){
mCM = "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("*/*");
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, "Image Chooser");
chooserIntent.putExtra(Intent.EXTRA_INITIAL_INTENTS, intentArray);
imgFinished.launch(chooserIntent);
return true;
}
});
webView.setWebViewClient(new WebViewClient());
webView.setWebContentsDebuggingEnabled(true);
permissionManager = new PermissionManager() {};
permissionManager.checkAndRequestPermissions(this);
}
public class Callback extends WebViewClient{
public void onReceivedError(WebView view, int errorCode, String description, String failingUrl){
Toast.makeText(getApplicationContext(), "Failed loading app!", Toast.LENGTH_SHORT).show();
}
}
// Create an image file
private File createImageFile() throws IOException{
#SuppressLint("SimpleDateFormat") String timeStamp = new SimpleDateFormat("yyyyMMdd_HHmmss").format(new Date());
String imageFileName = "img_"+timeStamp+"_";
File storageDir = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES);
File tempFile = File.createTempFile(imageFileName,".jpg",storageDir);
return tempFile;
}
here is my manifest
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.webview.android">
<uses-permission android:name="android.permission.CAMERA" />
<uses-feature android:name="android.hardware.camera" />
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.INTERNET"/>
<uses-permission android:name="android.permission.READ_MEDIA_IMAGES"/>
<uses-permission android:name="android.permission.READ_MEDIA_VIDEO"/>
<uses-permission android:name="android.permission.READ_MEDIA_AUDIO"/>
<queries>
<intent>
<action android:name="android.media.action.IMAGE_CAPTURE" />
</intent>
</queries>
<application
android:allowBackup="true"
android:icon="#mipmap/ic_launcher"
android:label="#string/app_name"
android:roundIcon="#mipmap/ic_launcher_round"
android:supportsRtl="true">
<activity android:name=".MainActivity"
android:exported="true"
android:theme="#style/Theme.AppCompat.DayNight">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<provider
android:name="androidx.core.content.FileProvider"
android:authorities="${applicationId}"
android:exported="false"
android:grantUriPermissions="true">
<meta-data
android:name="android.support.FILE_PROVIDER_PATHS"
android:resource="#xml/provider_paths"/>
</provider>
</application>
</manifest>
I expect it loads a img file into the input field
I solved the problem by replacing
Uri.fromfile(photoFile)
with
FileProvider.getUriForFile(MainActivity.this, BuildConfig.APPLICATION_ID, photoFile)
this creates a url tot he taken image in the same way as when you open a image from the file explorer
Trying to make a web view app for a site. although everything works fine, unable to resolve few errors that are popping up while I add this "file download" code.
Here's the android code :
Activity Main:
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".MainActivity">
<WebView
android:id="#+id/webview_sample"
android:layout_width="match_parent"
android:layout_height="match_parent"/>
</RelativeLayout>
Main Activity.java
package com.appgrep.urstudymate;
import androidx.appcompat.app.AppCompatActivity;
import androidx.core.app.ActivityCompat;
import androidx.core.content.ContextCompat;
import android.Manifest;
import android.annotation.SuppressLint;
import android.app.Activity;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.os.Environment;
import android.os.Parcelable;
import android.provider.MediaStore;
import android.util.Log;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.webkit.ValueCallback;
import android.webkit.WebChromeClient;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.Toast;
import java.io.File;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;
public class MainActivity extends AppCompatActivity {
private final static int FCR = 1;
WebView webView;
private String mCM;
private ValueCallback<Uri> mUM;
private ValueCallback<Uri[]> mUMA;
private ValueCallback<Uri> mUploadMessage;
private Uri mCapturedImageURI = null;
private ValueCallback<Uri[]> mFilePathCallback;
private String mCameraPhotoPath;
private static final int INPUT_FILE_REQUEST_CODE = 1;
private static final int FILECHOOSER_RESULTCODE = 1;
private static final String TAG = MainActivity.class.getSimpleName();
#Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
if (requestCode != INPUT_FILE_REQUEST_CODE || 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) {
// 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;
} else if (Build.VERSION.SDK_INT <= Build.VERSION_CODES.KITKAT) {
if (requestCode != FILECHOOSER_RESULTCODE || mUploadMessage == null) {
super.onActivityResult(requestCode, resultCode, data);
return;
}
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;
}
}
return;
}
#SuppressLint({"SetJavaScriptEnabled", "WrongViewCast"})
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
webView = findViewById(R.id.webview_sample);
if (Build.VERSION.SDK_INT >= 23 && (ContextCompat.checkSelfPermission(this, Manifest.permission.WRITE_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED || ContextCompat.checkSelfPermission(this, Manifest.permission.CAMERA) != PackageManager.PERMISSION_GRANTED)) {
ActivityCompat.requestPermissions(MainActivity.this, new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE, Manifest.permission.CAMERA}, 1);
}
assert webView != null;
WebSettings webSettings = webView.getSettings();
webSettings.setJavaScriptEnabled(true);
webSettings.setAllowFileAccess(true);
webView.getSettings().setSupportZoom(true);
webView.getSettings().setBuiltInZoomControls(true);
if (Build.VERSION.SDK_INT >= 21) {
webSettings.setMixedContentMode(0);
webView.setLayerType(View.LAYER_TYPE_HARDWARE, null);
} else if (Build.VERSION.SDK_INT >= 19) {
webView.setLayerType(View.LAYER_TYPE_HARDWARE, null);
} else if (Build.VERSION.SDK_INT < 19) {
webView.setLayerType(View.LAYER_TYPE_SOFTWARE, null);
}
webView.setWebViewClient(new Callback());
webView.loadUrl("https://urstudymate.com/");
webView.setWebChromeClient(new WebChromeClient() {
private File createImageFile() throws IOException {
String timeStamp = new SimpleDateFormat("yyyyMMdd_HHmmss").format(new Date());
String imageFileName = "JPEG_" + timeStamp + "_";
File storageDir = Environment.getExternalStoragePublicDirectory(
Environment.DIRECTORY_PICTURES);
File imageFile = File.createTempFile(
imageFileName, /* prefix */
".jpg", /* suffix */
storageDir /* directory */
);
return imageFile;
}
public boolean onShowFileChooser(WebView view, ValueCallback<Uri[]> filePath, WebChromeClient.FileChooserParams fileChooserParams) {
// Double check that we don't have any existing callbacks
if (mFilePathCallback != null) {
mFilePathCallback.onReceiveValue(null);
}
mFilePathCallback = filePath;
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, "Image Chooser");
chooserIntent.putExtra(Intent.EXTRA_INITIAL_INTENTS, intentArray);
startActivityForResult(chooserIntent, INPUT_FILE_REQUEST_CODE);
return true;
}
public void openFileChooser(ValueCallback<Uri> uploadMsg, String acceptType) {
mUploadMessage = uploadMsg;
// Create AndroidExampleFolder at sdcard
// Create AndroidExampleFolder at sdcard
File imageStorageDir = new File(
Environment.getExternalStoragePublicDirectory(
Environment.DIRECTORY_PICTURES)
, "AndroidExampleFolder");
if (!imageStorageDir.exists()) {
// Create AndroidExampleFolder at sdcard
imageStorageDir.mkdirs();
}
// Create camera captured image file path and name
File file = new File(
imageStorageDir + File.separator + "IMG_"
+ String.valueOf(System.currentTimeMillis())
+ ".jpg");
mCapturedImageURI = Uri.fromFile(file);
// Camera capture image intent
final Intent captureIntent = new Intent(
android.provider.MediaStore.ACTION_IMAGE_CAPTURE);
captureIntent.putExtra(MediaStore.EXTRA_OUTPUT, mCapturedImageURI);
Intent i = new Intent(Intent.ACTION_GET_CONTENT);
i.addCategory(Intent.CATEGORY_OPENABLE);
i.setType("image/*");
// Create file chooser intent
Intent chooserIntent = Intent.createChooser(i, "Image Chooser");
// Set camera intent to file chooser
chooserIntent.putExtra(Intent.EXTRA_INITIAL_INTENTS
, new Parcelable[] { captureIntent });
// On select image call onActivityResult method of activity
startActivityForResult(chooserIntent, FILECHOOSER_RESULTCODE);
}
public void openFileChooser(ValueCallback<Uri> uploadMsg,
String acceptType,
String capture) {
openFileChooser(uploadMsg, acceptType);
}
});
}
webView.setDownloadListener(new DownloadListener(){
#Override
public void onDownloadStart(String url, String userAgent, String contentDisposition, String mimetype, long contentLength) {
DownloadManager.Request myRequest = new DownloadManager.Request(Uri.parse(url));
myRequest.allowScanningByMediaScanner();
myRequest.setNotificationVisibility(DownloadManager.Request.VISIBILITY_VISIBLE_NOTIFY_COMPLETED);
DownloadManager myManager = (DownloadManager)getSystemService(DOWNLOAD_SERVICE);
myManager.enqueue(myRequest);
Toast.makeText(getApplicationContext(), "File is Downloading...", Toast.LENGTH_SHORT).show();
}
});
public class Callback extends WebViewClient {
public void onReceivedError(WebView view, int errorCode, String description, String failingUrl) {
Toast.makeText(getApplicationContext(), "Failed loading app!", Toast.LENGTH_SHORT).show();
}
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
MenuInflater myMenuInflater = getMenuInflater();
myMenuInflater.inflate(R.menu.super_menu, menu);
return super.onCreateOptionsMenu(menu);
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case R.id.myMenuOne:
onBackPressed();
break;
case R.id.myMenuTwo:
GoForward();
break;
}
return true;
}
private void GoForward() {
if (webView.canGoForward()) {
webView.goForward();
} else {
Toast.makeText(this, "Can't go further!", Toast.LENGTH_SHORT).show();
}
}
#Override
public void onBackPressed() {
if (webView.canGoBack()) {
webView.goBack();
}
}
}
Super Menu.xml
<?xml version="1.0" encoding="utf-8"?>
<menu xmlns:android="http://schemas.android.com/apk/res/android" xmlns:app="http://schemas.android.com/apk/res-auto" xmlns:tools="http://schemas.android.com/tools" tools:context="com.filechooser.file.MainActivity">
<item android:id="#+id/myMenuOne" android:icon="#drawable/ic_arrow_back_black_24dp" android:title="Item" app:showAsAction="always" />
<item android:id="#+id/myMenuTwo" android:icon="#drawable/ic_arrow_back_black_24dp" android:title="Item" app:showAsAction="always" />
</menu>
Android Manifest
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android" package="com.appgrep.urstudymate">
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
<uses-permission android:name="android.permission.CALL_PHONE" />
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE"></uses-permission>
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"></uses-permission>
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
<application
android:allowBackup="true"
android:icon="#mipmap/ic_launcher"
android:label="#string/app_name"
android:roundIcon="#mipmap/ic_launcher_round"
android:supportsRtl="true"
android:usesCleartextTraffic="true"
android:theme="#style/AppTheme"
>
<activity android:name=".MainActivity">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
</application>
</manifest>
However the piece of code I added is :
webView.setDownloadListener(new DownloadListener(){
#Override
public void onDownloadStart(String url, String userAgent, String contentDisposition, String mimetype, long contentLength) {
DownloadManager.Request myRequest = new DownloadManager.Request(Uri.parse(url));
myRequest.allowScanningByMediaScanner();
myRequest.setNotificationVisibility(DownloadManager.Request.VISIBILITY_VISIBLE_NOTIFY_COMPLETED);
DownloadManager myManager = (DownloadManager)getSystemService(DOWNLOAD_SERVICE);
myManager.enqueue(myRequest);
Toast.makeText(getApplicationContext(), "File is Downloading...", Toast.LENGTH_SHORT).show();
}
});
(which i added already for which I got error at "setDownloadListener", "DownloadListener", "DownloadManager" and so on. almost all words in that piece.)
SCREENSHOT :
Any help is greatly appreciated.
I have problem like in title: Download Manager not working right - I want download file .apk but after click button nothing happens. In logcat I have no errors or warrnings, it not works on emulator and phone as well.
I tried all examples from here(but not only) Download a file with Android, and showing the progress in a ProgressDialog - and still downloading .apk is not starting.
My code:
import android.Manifest;
import android.app.Activity;
import android.app.DownloadManager;
import android.content.Context;
import android.content.pm.PackageManager;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.os.Environment;
import android.view.View;
import android.widget.Button;
import android.widget.Toast;
import androidx.annotation.NonNull;
import java.net.URI;
public class MainActivity extends Activity {
private String url = "https://someurl.com/appplication.apk";
Button btnDownload;
private static final int PERMISSION_STORAGE_CODE = 1000;
private int downloadedProgress = 0;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
btnDownload = findViewById(R.id.btnDownload);
btnDownload.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if(Build.VERSION.SDK_INT >= Build.VERSION_CODES.M){
if(checkSelfPermission(Manifest.permission.WRITE_EXTERNAL_STORAGE) ==
PackageManager.PERMISSION_DENIED){
String[] permissions = {Manifest.permission.WRITE_EXTERNAL_STORAGE};
requestPermissions(permissions, PERMISSION_STORAGE_CODE);
} else {
startDownloading();
}
} else {
startDownloading();
}
}
});
}
private void startDownloading(){
DownloadManager.Request request = new DownloadManager.Request(Uri.parse(url));
request.setAllowedNetworkTypes(DownloadManager.Request.NETWORK_MOBILE
| DownloadManager.Request.NETWORK_MOBILE);
request.setTitle("Download");
request.setDescription("Downloading file...");
request.allowScanningByMediaScanner();
request.setNotificationVisibility(DownloadManager.Request.VISIBILITY_VISIBLE_NOTIFY_COMPLETED);
request.setDestinationInExternalPublicDir(Environment.DIRECTORY_DOWNLOADS, "" + System.currentTimeMillis());
DownloadManager manager = (DownloadManager)getSystemService(Context.DOWNLOAD_SERVICE);
manager.enqueue(request);
}
#Override
public void onRequestPermissionsResult(int requestCode, #NonNull String[] permissions, #NonNull int[] grantResults) {
switch(requestCode){
case PERMISSION_STORAGE_CODE: {
if(grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED){
startDownloading();
} else {
Toast.makeText(this, "Permission denied...!", Toast.LENGTH_SHORT).show();
}
}
}
}
}
Manifest.xml permissions
<uses-permission android:name="android.permission.INSTALL_PACKAGES"
tools:ignore="ProtectedPermissions" />
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>
<uses-permission android:name="android.permission.WRITE_SYNC_SETTINGS"/>
<uses-permission android:name="android.permission.INTERNET"/>
I followed this tutorial : https://developer.android.com/training/camera/photobasics .
I had some errors, but I resolved them and the app was working fine.
Once you took a picture, the picture would be saved in under this path :
Android/data/<YourAppPackageName>/files/Pictures.
However, after last OS update I'm getting an empty image file with size 0 B!
How can I solve this issue?
here is my github project : https://github.com/AlineJo/CameraGalleryImage.git
here is my code :
Manifest.xml
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.example.cameragalleryimage">
<!--Permission to write to storage-->
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
<!--Inform google play that your app can take pictures-->
<uses-feature
android:name="android.hardware.camera"
android:required="true" />
<application
android:allowBackup="true"
android:icon="#mipmap/ic_launcher"
android:label="#string/app_name"
android:roundIcon="#mipmap/ic_launcher_round"
android:supportsRtl="true"
android:theme="#style/AppTheme">
<!-- File provider is a generic way to store image file across different Android SDK, And it enable us to get uri-->
<provider
android:name="androidx.core.content.FileProvider"
android:authorities="com.example.cameragalleryimage.fileprovider"
android:exported="false"
android:grantUriPermissions="true">
<meta-data
android:name="android.support.FILE_PROVIDER_PATHS"
android:resource="#xml/img_file_path"></meta-data>
</provider>
<activity android:name=".activities.MainActivity">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
</application>
</manifest>
UploadImageFragment
package com.example.cameragalleryimage.fragments;
import android.Manifest;
import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.provider.MediaStore;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.ProgressBar;
import android.widget.TextView;
import android.widget.Toast;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.core.app.ActivityCompat;
import androidx.core.content.FileProvider;
import androidx.fragment.app.Fragment;
import com.example.cameragalleryimage.R;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.text.SimpleDateFormat;
import java.util.Date;
import static android.app.Activity.RESULT_OK;
/**
* A simple {#link Fragment} subclass.
*/
public class UploadImageFragment extends Fragment implements ChooseDialogFragment.ChooseDialogInterface {
private static final int PICK_IMAGE = 100;
private static final int CAPTURE_IMAGE = 200;
private static final int STORAGE_PERMISSION_REQUEST = 300;
private Context mContext;
private Uri mImageUri;
private ImageView ivImg;
private TextView tvProgress;
private ProgressBar progressBar;
private String mImagePath;
public UploadImageFragment() {
// Required empty public constructor
}
#Override
public void onAttach(#NonNull Context context) {
super.onAttach(context);
mContext = context;
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
View parentView = inflater.inflate(R.layout.fragment_upload_image, container, false);
ivImg = parentView.findViewById(R.id.iv_img);
tvProgress = parentView.findViewById(R.id.tv_progress);
progressBar = parentView.findViewById(R.id.progressBar);
Button btnChoose = parentView.findViewById(R.id.btn_choose);
Button btnUpload = parentView.findViewById(R.id.btn_upload);
btnChoose.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
ChooseDialogFragment dialog = new ChooseDialogFragment();
dialog.setChooseDialogListener(UploadImageFragment.this);
dialog.show(getChildFragmentManager(), ChooseDialogFragment.class.getSimpleName());
}
});
btnUpload.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (mImageUri == null) {
Toast.makeText(mContext, "Please take an image", Toast.LENGTH_SHORT).show();
} else {
Toast.makeText(mContext, "Image URI Found : " + mImageUri.toString(), Toast.LENGTH_LONG).show();
}
}
});
return parentView;
}
#Override
public void onGalleryButtonClick() {
Intent i = new Intent();
i.setType("image/*"); // specify the type of data you expect
i.setAction(Intent.ACTION_GET_CONTENT); // we need to get content from another act.
startActivityForResult(Intent.createChooser(i, "choose App"), PICK_IMAGE);
}
#Override
public void onCameraButtonClick() {
if (isPermissionGranted()) {
openCamera();
} else {
showRunTimePermission();
}
}
private void openCamera() {
Intent takePictureIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
// Ensure that there's a camera activity to handle the intent
if (takePictureIntent.resolveActivity(mContext.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("capture_error", ex.toString());
}
// Continue only if the File was successfully created
if (photoFile != null) {
mImageUri = FileProvider.getUriForFile(mContext,
"com.example.cameragalleryimage.fileprovider",
photoFile);
startActivityForResult(takePictureIntent, CAPTURE_IMAGE);
}
}
}
#Override
public void onActivityResult(int requestCode, int resultCode, #Nullable Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (resultCode == RESULT_OK && data != null) {
if (requestCode == CAPTURE_IMAGE) {//img from camera
Bundle extras = data.getExtras();
Bitmap imageBitmap = (Bitmap) extras.get("data");
ivImg.setImageBitmap(imageBitmap);
} else if (requestCode == PICK_IMAGE) {// img from gallery
try {
Uri imgUri = data.getData();
InputStream imageStream = mContext.getContentResolver().openInputStream(imgUri);//2
Bitmap selectedImageBitmap = BitmapFactory.decodeStream(imageStream);//3}
mImageUri = imgUri;
ivImg.setImageBitmap(selectedImageBitmap);
} catch (FileNotFoundException e) {
e.printStackTrace();
}
}
} else {
Toast.makeText(mContext, "Unexpected Error Happened while selecting picture!", Toast.LENGTH_SHORT).show();
}
}
private File createImageFile() throws IOException {
// Create an image file name
String timeStamp = new SimpleDateFormat("yyyyMMdd_HHmmss").format(new Date());
String imageFileName = "IMG_" + timeStamp + "_";
File storageDir = mContext.getExternalFilesDir(Environment.DIRECTORY_PICTURES);// mContext.getExternalCacheDir();
File image = File.createTempFile(
imageFileName, /* prefix */
".jpg", /* suffix */
storageDir /* directory */
);
// Save a file: path for use with ACTION_VIEW intents
mImagePath = image.getAbsolutePath();
return image;
}
private boolean isPermissionGranted() {
return ActivityCompat.checkSelfPermission(mContext, Manifest.permission.WRITE_EXTERNAL_STORAGE) == PackageManager.PERMISSION_GRANTED;
}
public void showRunTimePermission() {
// Permission is not Granted !
// we should Request the Permission!
// put all permissions you need in this Screen into string array
String[] permissionsArray = {Manifest.permission.WRITE_EXTERNAL_STORAGE};
//here we requet the permission
requestPermissions(permissionsArray, STORAGE_PERMISSION_REQUEST);
}
#Override
public void onRequestPermissionsResult(int requestCode, #NonNull String[] permissions, #NonNull int[] grantResults) {
super.onRequestPermissionsResult(requestCode, permissions, grantResults);
if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
// user grants the Permission!
// you can call the function to write/read to storage here!
openCamera();
} else {
// user didn't grant the Permission we need
Toast.makeText(mContext, "Please Grant the Permission To use this Feature!", Toast.LENGTH_LONG).show();
}
}
}
img_file_path.xml
<?xml version="1.0" encoding="utf-8"?>
<paths>
<external-files-path
name="my_images"
path="/" />
<!-- Android/data/com.example.cameragalleryimage/files/Pictures-->
</paths>
Super thanks to #CommonsWare and #blackapps comments I was able to get uri and display the captured image
You can find the updated GitHub project here: https://github.com/AlineJo/CameraGalleryImage.git
here is the code I changed :
package com.example.cameragalleryimage.fragments;
import android.Manifest;
import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.provider.MediaStore;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.ProgressBar;
import android.widget.TextView;
import android.widget.Toast;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.core.app.ActivityCompat;
import androidx.core.content.FileProvider;
import androidx.fragment.app.Fragment;
import com.bumptech.glide.Glide;
import com.example.cameragalleryimage.R;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.text.SimpleDateFormat;
import java.util.Date;
import static android.app.Activity.RESULT_OK;
/**
* A simple {#link Fragment} subclass.
*/
public class UploadImageFragment extends Fragment implements ChooseDialogFragment.ChooseDialogInterface {
private static final int PICK_IMAGE = 100;
private static final int CAPTURE_IMAGE = 200;
private static final int STORAGE_PERMISSION_REQUEST = 300;
private Context mContext;
private Uri mImageUri;
private ImageView ivImg;
private TextView tvProgress;
private ProgressBar progressBar;
private String mImagePath;
private File photoFile;
public UploadImageFragment() {
// Required empty public constructor
}
#Override
public void onAttach(#NonNull Context context) {
super.onAttach(context);
mContext = context;
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
View parentView = inflater.inflate(R.layout.fragment_upload_image, container, false);
ivImg = parentView.findViewById(R.id.iv_img);
tvProgress = parentView.findViewById(R.id.tv_progress);
progressBar = parentView.findViewById(R.id.progressBar);
Button btnChoose = parentView.findViewById(R.id.btn_choose);
Button btnUpload = parentView.findViewById(R.id.btn_upload);
btnChoose.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
ChooseDialogFragment dialog = new ChooseDialogFragment();
dialog.setChooseDialogListener(UploadImageFragment.this);
dialog.show(getChildFragmentManager(), ChooseDialogFragment.class.getSimpleName());
}
});
btnUpload.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (mImageUri == null) {
Toast.makeText(mContext, "Please take an image", Toast.LENGTH_SHORT).show();
}
else {
Toast.makeText(mContext, "Image URI Found : " + mImageUri.toString(), Toast.LENGTH_LONG).show();
}
}
});
return parentView;
}
#Override
public void onGalleryButtonClick() {
Intent i = new Intent();
i.setType("image/*"); // specify the type of data you expect
i.setAction(Intent.ACTION_GET_CONTENT); // we need to get content from another act.
startActivityForResult(Intent.createChooser(i, "choose App"), PICK_IMAGE);
}
#Override
public void onCameraButtonClick() {
if (isPermissionGranted()) {
openCamera();
} else {
showRunTimePermission();
}
}
private void openCamera() {
Intent takePictureIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
// Ensure that there's a camera activity to handle the intent
if (takePictureIntent.resolveActivity(mContext.getPackageManager()) != null) {
// Create the File where the photo should go
photoFile = null;
try {
photoFile = createFileInstance();
} catch (IOException ex) {
// Error occurred while creating the File
Log.d("capture_error", ex.toString());
}
// Continue only if the File was successfully created
if (photoFile != null) {
mImageUri = FileProvider.getUriForFile(mContext,
"com.example.cameragalleryimage.fileprovider",
photoFile);
takePictureIntent.putExtra(MediaStore.EXTRA_OUTPUT, mImageUri); //this code was messing, However adding this code will make "Intent data" (in "onActivityResult") to be null
Glide.with(mContext).load(mImageUri).into(ivImg);//solution ask glide to load the image using uri
startActivityForResult(takePictureIntent, CAPTURE_IMAGE);
}
}
}
#Override
public void onActivityResult(int requestCode, int resultCode, #Nullable Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (resultCode == RESULT_OK && data != null) {
if (requestCode == PICK_IMAGE) {// img from gallery
try {
Uri imgUri = data.getData();
InputStream imageStream = mContext.getContentResolver().openInputStream(imgUri);//2
Bitmap selectedImageBitmap = BitmapFactory.decodeStream(imageStream);//3}
mImageUri = imgUri;
ivImg.setImageBitmap(selectedImageBitmap);
} catch (FileNotFoundException e) {
e.printStackTrace();
}
}
} else {
if (requestCode == CAPTURE_IMAGE) {
if (photoFile.length() == 0) {
Toast.makeText(mContext, "You took an image, but you canceled it!", Toast.LENGTH_SHORT).show();
mImageUri = null;
}
}
}
}
private File createFileInstance() throws IOException {
// Create an image file name
String timeStamp = new SimpleDateFormat("yyyyMMdd_HHmmss").format(new Date());
String imageFileName = "IMG_" + timeStamp + "_";
File storageDir = mContext.getExternalFilesDir(Environment.DIRECTORY_PICTURES);// mContext.getExternalCacheDir();
File image = new File(storageDir.toString()+"/"+imageFileName+".png");
// Save a file: path for use with ACTION_VIEW intents
mImagePath = image.getAbsolutePath();
return image;
}
private boolean isPermissionGranted() {
return ActivityCompat.checkSelfPermission(mContext, Manifest.permission.WRITE_EXTERNAL_STORAGE) == PackageManager.PERMISSION_GRANTED;
}
public void showRunTimePermission() {
// Permission is not Granted !
// we should Request the Permission!
// put all permissions you need in this Screen into string array
String[] permissionsArray = {Manifest.permission.WRITE_EXTERNAL_STORAGE};
//here we requet the permission
requestPermissions(permissionsArray, STORAGE_PERMISSION_REQUEST);
}
#Override
public void onRequestPermissionsResult(int requestCode, #NonNull String[] permissions, #NonNull int[] grantResults) {
super.onRequestPermissionsResult(requestCode, permissions, grantResults);
if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
// user grants the Permission!
// you can call the function to write/read to storage here!
openCamera();
} else {
// user didn't grant the Permission we need
Toast.makeText(mContext, "Please Grant the Permission To use this Feature!", Toast.LENGTH_LONG).show();
}
}
}
If you are updated to Android10. Then use below code snippet.
<application android:requestLegacyExternalStorage="true" ... >
...
</application>
I am working on the project of capturing photos or picking images from gallery and show it in the recycler view, the app is working good in Android-lollipop but crashes in marshmallow one as soon as camera button is clicked giving the exception
Caused by: java.lang.SecurityException: Permission Denial: writing com.android.providers.media.MediaProvider uri content://media/external/images/media from pid=1983, uid=10060 requires android.permission.WRITE_EXTERNAL_STORAGE, or grantUriPermission()
Here is the code:
Manifest
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
package="com.urjapawar.bevypart2">
<uses-permission tools:node="replace" android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>
<uses-permission tools:node="replace" android:name="android.permission.READ_EXTERNAL_STORAGE"/>
<uses-feature
android:name="android.hardware.camera"
android:required="false"/>
<uses-permission
android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>
<application
android:allowBackup="true"
android:icon="#mipmap/ic_launcher"
android:label="#string/app_name"
android:supportsRtl="true"
android:theme="#style/AppTheme"
>
<activity
android:name=".MainActivity"
android:label="#string/app_name"
android:theme="#style/AppTheme.NoActionBar">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity><!-- ATTENTION: This was auto-generated to add Google Play services to your project for
App Indexing. See https://g.co/AppIndexing/AndroidStudio for more information. -->
<meta-data
android:name="com.google.android.gms.version"
android:value="#integer/google_play_services_version" />
</application>
</manifest>
Images.java
public class Images {
String path;
public void setPath(String path) { this.path = path; }
public String getPath() {
return path;
}
/**
* Gets path.
*
* #return Value of path.
*/
#Override public String toString() {
return "\nPath:" + path;
}
}
MainActivity.java
import android.content.ContentValues;
import android.content.Intent;
import android.database.Cursor;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.provider.MediaStore;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.support.v7.widget.Toolbar;
import android.view.View;
import com.google.android.gms.appindexing.AppIndex;
import com.google.android.gms.common.api.GoogleApiClient;
import java.util.ArrayList;
public class MainActivity extends AppCompatActivity {
private ArrayList<Images> images;
private ImageAdapter imageAdapter;
private RecyclerView rv;
private LinearLayoutManager llm;
private Uri mCapturedImageURI;
private static final int RESULT_LOAD_IMAGE = 1;
private static final int REQUEST_IMAGE_CAPTURE = 2;
/**
* ATTENTION: This was auto-generated to implement the App Indexing API.
* See https://g.co/AppIndexing/AndroidStudio for more information.
*/
private GoogleApiClient client;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
images = new ArrayList<>();
imageAdapter = new ImageAdapter(images);
rv = (RecyclerView) findViewById(R.id.rv);
llm = new LinearLayoutManager(this);
rv.setLayoutManager(llm);
imageAdapter = new ImageAdapter(images);
rv.setAdapter(imageAdapter);
// ATTENTION: This was auto-generated to implement the App Indexing API.
// See https://g.co/AppIndexing/AndroidStudio for more information.
client = new GoogleApiClient.Builder(this).addApi(AppIndex.API).build();
}
public void activeCamera(View view) {
Intent takePictureIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
if (takePictureIntent.resolveActivity(getPackageManager()) != null) {
String fileName = "temp.jpg";
ContentValues values = new ContentValues();
values.put(MediaStore.Images.Media.TITLE, fileName);
mCapturedImageURI = getContentResolver()
.insert(MediaStore.Images.Media.EXTERNAL_CONTENT_URI,
values);
takePictureIntent
.putExtra(MediaStore.EXTRA_OUTPUT, mCapturedImageURI);
startActivityForResult(takePictureIntent, REQUEST_IMAGE_CAPTURE);
}
}
public void activeGallery(View view) {
Intent intent = new Intent(Intent.ACTION_PICK,
MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
startActivityForResult(intent, RESULT_LOAD_IMAGE);
}
#Override
protected void onActivityResult(int requestCode, int resultCode,
Intent data) {
super.onActivityResult(requestCode, resultCode, data);
switch (requestCode) {
case RESULT_LOAD_IMAGE:
Uri selectedImage = null;
if (requestCode == RESULT_LOAD_IMAGE &&
resultCode == RESULT_OK && null != data) {
if (Build.VERSION.SDK_INT < 19) {
selectedImage = data.getData();
} else {
selectedImage = data.getData();
}
String[] filePathColumn = {MediaStore.Images.Media.DATA};
Cursor cursor = getContentResolver()
.query(selectedImage, filePathColumn, null, null,
null);
if (cursor != null && cursor.getCount() > 0) {
cursor.moveToFirst();
}
// cursor.moveToFirst();
int columnIndex = cursor.getColumnIndex(filePathColumn[0]);
String picturePath = cursor.getString(columnIndex);
cursor.close();
Images image = new Images();
image.setPath(picturePath);
images.add(image);
}
case REQUEST_IMAGE_CAPTURE:
if (requestCode == REQUEST_IMAGE_CAPTURE &&
resultCode == RESULT_OK) {
String[] projection = {MediaStore.Images.Media.DATA};
Cursor cursor =
getContentResolver().query(mCapturedImageURI, projection, null,
null, null);
int column_index_data = cursor.getColumnIndexOrThrow(
MediaStore.Images.Media.DATA);
cursor.moveToFirst();
String picturePath = cursor.getString(column_index_data);
Images image = new Images();
image.setPath(picturePath);
images.add(image);
cursor.close();
}
}
}
}
ImageAdapter.java
import android.graphics.BitmapFactory;
import android.media.ThumbnailUtils;
import android.net.Uri;
import android.support.v7.widget.*;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import java.util.List;
public class ImageAdapter extends android.support.v7.widget.RecyclerView.Adapter<ImageAdapter.ImgViewHolder> {
List<Images> images;
ImageAdapter(List<Images> img){
this.images = img;
}
public class ImgViewHolder extends android.support.v7.widget.RecyclerView.ViewHolder
{
ImageView personPhoto;
CardView cv;
public ImgViewHolder(View itemView) {
super(itemView);
cv = (CardView)itemView.findViewById(R.id.card_view);
personPhoto=(ImageView)itemView.findViewById(R.id.thumbnail);
}
}
#Override
public ImgViewHolder onCreateViewHolder(final ViewGroup viewGroup, int i) {
View v = LayoutInflater.from(viewGroup.getContext()).inflate(R.layout.single_card, viewGroup, false);
ImgViewHolder pvh = new ImgViewHolder(v);
return pvh;
}
#Override
public int getItemCount() {
return images.size();
}
#Override
public void onBindViewHolder(ImgViewHolder holder, int i) {
Images image = images.get(i);
final int THUMBSIZE = 96;
// viewHolder.imgIcon.setImageURI(Uri.fromFile(new File(image
// .getPath())));
holder.personPhoto.setImageBitmap(ThumbnailUtils
.extractThumbnail(BitmapFactory.decodeFile(image.getPath()),
THUMBSIZE, THUMBSIZE));
// holder.personPhoto.setImageURI(Uri.parse("file://" + images.getPath() + "/" + mDataset[position]));
}
#Override
public void onAttachedToRecyclerView(RecyclerView recyclerView) {
super.onAttachedToRecyclerView(recyclerView);
}
}
I have checked many answers but not able to fix it, kindly help! Also while selecting images from gallery blank card shows up in marshmallow (no image content), it says Make sure the Cursor is initialized correctly before accessing data from it. while it works fine in lollipop one.
Any suggestions will be deeply appreciated.
You need to give android.hardware.Camera permission programmatically.
manifeast permission not work on Android Marshmallow
In marshmallow,We require runtime permissions for Storage,Contacts,Camera, etc. In edition to give these permissions in manifest for older version, We need to request them from users at Runtime for marshmallow.
For more details refer this : Marshmallow permissions
You must put Camera permission in code since android 6 + version checks for runtime permission.
public void getCameraPermission(){
if (!checkPermission()) {
requestPermission();
}
}
private boolean checkPermission(){
int result = ContextCompat.checkSelfPermission(context, Manifest.permission.CAMERA);
if (result == PackageManager.PERMISSION_GRANTED){
return true;
} else {
return false;
}
}
private void requestPermission(){
if (ActivityCompat.shouldShowRequestPermissionRationale(MainActivity.this, Manifest.permission.CAMERA)){
ActivityCompat.requestPermissions(MainActivity.this, new String[]{Manifest.permission.CAMERA}, PERMISSION_REQUEST_CODE);
} else {
ActivityCompat.requestPermissions(MainActivity.this, new String[]{Manifest.permission.CAMERA}, 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) {
Toast.makeText(MainActivity.this,"Permission granted",Toast.LENGTH_SHORT).show();
//store permission in shared pref
}
else {
Toast.makeText(MainActivity.this,"Permission denied",Toast.LENGTH_SHORT).show();
//store permission in shared pref
}
break;
}
}
You need to add
<uses-permission android:name="android.permission.CAMERA" />
Just a thought, have you allowed your app to access your phone or SD card in the Manifest?
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />