How to create folder pro-grammatically in Android API 29 [duplicate] - android

This question already has answers here:
Can't create directory in Android 10
(7 answers)
Closed 2 years ago.
I am creating folder in SD card I tried many code in stackoverflow but its not working help me to solve this I am using Pixel 2 API 29 Emulator Compiled version 29 minSdkVersion 26 targetSdkVersion 29 and I added Permission external storage permission and its shown getExternalStorageDirectory() depreciated
I am tried codes
File mydir = new File(Environment.getExternalStorageDirectory() + "/mydir/");
if(!mydir.exists())
mydir.mkdirs();
else
Log.d("error", "dir. already exists");
Manifest
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>
<uses-permission android:name="android.permission.READ_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/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>

Use comma instead of +(sign) and try this code.
Try this code:
File mydir = new File(Environment.getExternalStorageDirectory(), "/mydir/");
if (!mydir.exists()) {
mydir.mkdirs();
Log.e("directory", "folder Created");
} else {
Log.e("directory", "folder already exists");
}
Also Cross verify your permission Code with below snippets:
#TargetApi(Build.VERSION_CODES.M)
public void checkMyPermission() {
String[] permissionArrays = new String[]{Manifest.permission.READ_EXTERNAL_STORAGE};
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
requestPermissions(permissionArrays, 11111);
} else {
Toast.makeText(mcontext, "Permission Granted", Toast.LENGTH_SHORT).show();
}
}
#TargetApi(Build.VERSION_CODES.M)
public void onRequestPermissionsResult(int requestCode, #NonNull String[] permissions, #NonNull int[] grantResults) {
super.onRequestPermissionsResult(requestCode, permissions, grantResults);
boolean openActivityOnce = true;
boolean openDialogOnce = true;
if (requestCode == 11111) {
boolean isPermitted = false;
for (int i = 0; i < grantResults.length; i++) {
String permission = permissions[i];
isPermitted = grantResults[i] == PackageManager.PERMISSION_GRANTED;
if (grantResults[i] == PackageManager.PERMISSION_DENIED) {
// user rejected the permission
boolean showRationale = shouldShowRequestPermissionRationale(permission);
if (!showRationale) {
//execute when 'never Ask Again' tick and permission dialog not show
} else {
if (openDialogOnce) {
alertView();
}
}
}
}
}
}
private void alertView() {
AlertDialog.Builder dialog = new AlertDialog.Builder(mcontext);
dialog.setTitle("Permission Denied")
.setInverseBackgroundForced(true)
//.setIcon(R.drawable.ic_info_black_24dp)
.setMessage("Without those permission the app is unable to save your profile. App needs to save profile image in your external storage and also need to get profile image from camera or external storage.Are you sure you want to deny this permission?")
.setNegativeButton("I'M SURE", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialoginterface, int i) {
dialoginterface.dismiss();
}
})
.setPositiveButton("RE-TRY", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialoginterface, int i) {
dialoginterface.dismiss();
checkMyPermission();
}
}).show();
}

Related

Android does not allow directory creation with SDK update

Strange issue, but on one device Android no longer lets the app create a directory (or any directories). This seems to have happened since I moved to SDK 27 (I brought in a 3rd party library that requires the upgrade). Even stranger, it works on other devices. The device that does not work is a Samsung Galaxy Tab S3, running Android 8 (sdk 26).
Here is the code that fails:
public static String mediaStorageDirectory() {
return Environment.getExternalStorageDirectory().toString() + File.separator + "myapp";
}
private DatabaseHelper(Context context) {
super(context, DB_NAME, null, 1);
File dbPath = new File(Utilities.mediaStorageDirectory() + "/databases/");
if (!dbPath.exists()) {
if (dbPath.mkdirs()) {
this.mContext = context;
createDataBase();
}
}
}
The code creates a directory, then copies the app DB in into that directory. This code has been working since the dawn of time...has Android changed some security requirements for file creation?
If you are wondering, I have set privileges as follows:
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.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.ACCESS_NETWORK_STATE" />
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" />
And the user is prompted for those privileges successfully before the creation of the directory structure.
So the problem seems to be related to SDK 27. Seems they are now requiring (enforcing?) that the permissions for WRITE be granted. Previously only READ was required. I would assume that this was related to security upgrades, but I could not find any documentation on this change. Perhaps everyone else just did the inclusion previously. For those wanting to see code that does the permissions handling, I pulled the following code from another Stack Overflow a while back. I merely added the WRITE_EXTERNAL_STORAGE part that was previously missing:
final private int REQUEST_CODE_ASK_MULTIPLE_PERMISSIONS = 124;
public void checkPermissions() {
List<String> permissionsNeeded = new ArrayList<String>();
final List<String> permissionsList = new ArrayList<String>();
if (!addPermission(permissionsList, Manifest.permission.CAMERA))
permissionsNeeded.add("Camera");
if (!addPermission(permissionsList, Manifest.permission.READ_EXTERNAL_STORAGE))
permissionsNeeded.add("Read External Storage");
if (!addPermission(permissionsList, Manifest.permission.WRITE_EXTERNAL_STORAGE))
permissionsNeeded.add("Write External Storage");
if (!addPermission(permissionsList, Manifest.permission.ACCESS_FINE_LOCATION))
permissionsNeeded.add("GPS");
if (!addPermission(permissionsList, Manifest.permission.RECORD_AUDIO))
permissionsNeeded.add("Record Audio");
if (permissionsList.size() > 0) {
if (permissionsNeeded.size() > 0) {
// Need Rationale
String message = "You need to grant access to " + permissionsNeeded.get(0);
for (int i = 1; i < permissionsNeeded.size(); i++) {
message = message + ", " + permissionsNeeded.get(i);
}
message = message + "." + " If you do not the application may not function correctly.";
showMessageOKCancel(message, this,
new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
requestPermissions(permissionsList.toArray(new String[permissionsList.size()]),
REQUEST_CODE_ASK_MULTIPLE_PERMISSIONS);
}
});
} else {
requestPermissions(permissionsList.toArray(new String[permissionsList.size()]),
REQUEST_CODE_ASK_MULTIPLE_PERMISSIONS);
}
}
}
private static void showMessageOKCancel(String message, Activity activity, DialogInterface.OnClickListener okListener) {
new AlertDialog.Builder(activity).setMessage(message).setPositiveButton("OK", okListener).create().show();
}
private boolean addPermission(List<String> permissionsList, String permission) {
if (checkSelfPermission(permission) != PackageManager.PERMISSION_GRANTED) {
permissionsList.add(permission);
// Check for Rationale Option
if (!shouldShowRequestPermissionRationale(permission))
return false;
}
return true;
}
#Override
public void onRequestPermissionsResult(int requestCode, String[] permissions, int[] grantResults) {
switch (requestCode) {
case REQUEST_CODE_ASK_MULTIPLE_PERMISSIONS: {
Map<String, Integer> perms = new HashMap<String, Integer>();
// Initial
perms.put(Manifest.permission.ACCESS_FINE_LOCATION, PackageManager.PERMISSION_GRANTED);
perms.put(Manifest.permission.CAMERA, PackageManager.PERMISSION_GRANTED);
perms.put(Manifest.permission.RECORD_AUDIO, PackageManager.PERMISSION_GRANTED);
perms.put(Manifest.permission.READ_EXTERNAL_STORAGE, PackageManager.PERMISSION_GRANTED);
perms.put(Manifest.permission.WRITE_EXTERNAL_STORAGE, PackageManager.PERMISSION_GRANTED);
// Fill with results
for (int i = 0; i < permissions.length; i++)
perms.put(permissions[i], grantResults[i]);
// Check for ACCESS_FINE_LOCATION
if (perms.get(Manifest.permission.ACCESS_FINE_LOCATION) == PackageManager.PERMISSION_GRANTED
&& perms.get(Manifest.permission.CAMERA) == PackageManager.PERMISSION_GRANTED
&& perms.get(Manifest.permission.RECORD_AUDIO) == PackageManager.PERMISSION_GRANTED
&& perms.get(Manifest.permission.READ_EXTERNAL_STORAGE) == PackageManager.PERMISSION_GRANTED
&& perms.get(Manifest.permission.WRITE_EXTERNAL_STORAGE) == PackageManager.PERMISSION_GRANTED) {
// All Permissions Granted
}
// Warn the user that the application will not run
else if (perms.get(Manifest.permission.READ_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED) {
AlertDialog.Builder builder = new AlertDialog.Builder(StartActivity.this);
builder.setTitle("File Read Permissions Not Granted");
builder.setMessage("The Application cannot operate without READ access to files on your device. Do you want to grant this access?");
builder.setPositiveButton("Yes", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
ActivityCompat.requestPermissions(StartActivity.this, new String[]{Manifest.permission.READ_EXTERNAL_STORAGE}, 0);
}
});
builder.setNegativeButton("No", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int id) {
}
});
if (!isFinishing())
builder.show();
}
// Warn the user that the application will not run
else if (perms.get(Manifest.permission.WRITE_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED) {
AlertDialog.Builder builder = new AlertDialog.Builder(StartActivity.this);
builder.setTitle("File Write Permissions Not Granted");
builder.setMessage("The Application cannot operate without WRITE access to directories on your device. Do you want to grant this access?");
builder.setPositiveButton("Yes", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
ActivityCompat.requestPermissions(StartActivity.this, new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE}, 0);
}
});
builder.setNegativeButton("No", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int id) {
}
});
if (!isFinishing())
builder.show();
}else {
// Permission Denied
Toast.makeText(StartActivity.this, "Some Permission is Denied", Toast.LENGTH_SHORT)
.show();
}
}
break;
default:
super.onRequestPermissionsResult(requestCode, permissions, grantResults);
}
}
The call is SDK specific, added to the OnCreate() of your main activity:
// Check permissions for Android 6.0 devices
if (Build.VERSION.SDK_INT >= 23) {
// Marshmallow+
checkPermissions();
}

Write image downloaded in the media content

I am writing an app who download some images from a remote server. I try to save them in the gallery but I got a android.permission.WRITE_EXTERNAL_STORAGE required due to a Permission Denial.
I do not understand why because I set up the permission in the manifest.xml
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.seb.sebastien.reddit">
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.MEDIA_CONTENT_CONTROL"/>
<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">
<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>
Any idea why the permission denial happens as I add the permission. For information, I do not have an Android Device, I use the emulator. SDK use is API 26.
Thanks
For Android Running on Android 6.0 (API level 23) and above , we need to add runtime permission to work, you can follow this link Storage permission error in Marshmallow
----Updated ----
Code reference
public boolean isStoragePermissionGranted() {
if (Build.VERSION.SDK_INT >= 23) {
if (checkSelfPermission(android.Manifest.permission.WRITE_EXTERNAL_STORAGE)
== PackageManager.PERMISSION_GRANTED) {
Log.v(TAG,"Permission is granted");
return true;
} else {
Log.v(TAG,"Permission is revoked");
ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE}, 1);
return false;
}
}
else { //permission is automatically granted on sdk<23 upon installation
Log.v(TAG,"Permission is granted");
return true;
}
}
Permission result callback:
#Override
public void onRequestPermissionsResult(int requestCode, String[] permissions, int[] grantResults) {
super.onRequestPermissionsResult(requestCode, permissions, grantResults);
if(grantResults[0]== PackageManager.PERMISSION_GRANTED){
Log.v(TAG,"Permission: "+permissions[0]+ "was "+grantResults[0]);
//resume tasks needing this permission
}
}
For TargetSDK 23 or higher, you need to give runtime permission As per Android's guideline. Check this link for code snippet and more description.
https://developer.android.com/training/permissions/requesting.html
Add this code for permission to allow run time operation in splash activity in onCreate or before download process of image.
if (!checkPermission()) {
openActivity();
} else {
if (checkPermission()) {
requestPermissionAndContinue();
} else {
openActivity();
}
}
Add this method outside onCreate.
private static final int PERMISSION_REQUEST_CODE = 200;
private boolean checkPermission() {
return ContextCompat.checkSelfPermission(this, WRITE_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED
&& ContextCompat.checkSelfPermission(this, READ_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED
;
}
private void requestPermissionAndContinue() {
if (ContextCompat.checkSelfPermission(this, WRITE_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED
&& ContextCompat.checkSelfPermission(this, READ_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED) {
if (ActivityCompat.shouldShowRequestPermissionRationale(this, WRITE_EXTERNAL_STORAGE)
&& ActivityCompat.shouldShowRequestPermissionRationale(this, READ_EXTERNAL_STORAGE)) {
AlertDialog.Builder alertBuilder = new AlertDialog.Builder(this);
alertBuilder.setCancelable(true);
alertBuilder.setTitle(getString(R.string.permission_necessary));
alertBuilder.setMessage(R.string.storage_permission_is_encessary_to_wrote_event);
alertBuilder.setPositiveButton(android.R.string.yes, new DialogInterface.OnClickListener() {
#TargetApi(Build.VERSION_CODES.JELLY_BEAN)
public void onClick(DialogInterface dialog, int which) {
ActivityCompat.requestPermissions(SplashActivity.this, new String[]{WRITE_EXTERNAL_STORAGE
, READ_EXTERNAL_STORAGE}, PERMISSION_REQUEST_CODE);
}
});
AlertDialog alert = alertBuilder.create();
alert.show();
Log.e("", "permission denied, show dialog");
} else {
ActivityCompat.requestPermissions(SplashActivity.this, new String[]{WRITE_EXTERNAL_STORAGE,
READ_EXTERNAL_STORAGE}, PERMISSION_REQUEST_CODE);
}
} else {
openActivity();
}
}
#Override
public void onRequestPermissionsResult(int requestCode, #NonNull String[] permissions, #NonNull int[] grantResults) {
if (requestCode == PERMISSION_REQUEST_CODE) {
if (permissions.length > 0 && grantResults.length > 0) {
boolean flag = true;
for (int i = 0; i < grantResults.length; i++) {
if (grantResults[i] != PackageManager.PERMISSION_GRANTED) {
flag = false;
}
}
if (flag) {
openActivity();
} else {
finish();
}
} else {
finish();
}
} else {
super.onRequestPermissionsResult(requestCode, permissions, grantResults);
}
}
private void openActivity() {
//add your further process after giving permission or to download images from remote server.
}
happy Coding.

unable to access video files from external storage directory with file provider in API version 23 and upper. Code is given below

I want to play video in Video view, I have tried so many solutions but I am not able to access image file and video file as well.
It allows me to access image files when I run application for second time.
Click to see error,
Full Error Log
I already have run time permissions, but system won't allow me to access images and files.
Here is my code -
MainActivity
`
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
imageView = (ImageView) findViewById(R.id.imageView);
videoView = (VideoView) findViewById(R.id.videoView);
String image = "/ImageVideos/1501064538061.jpg";
String video = "/ImageVideos/20170707155916_mmy037p0xZzcW.mp4";
MediaController mediaController = new MediaController(this);
String strFileDir = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES).toString();
String strImgDir = strFileDir + image;
String strVideoDir = strFileDir + video;
File fileImg = new File(strImgDir);
File fileVideo = new File(strVideoDir);
if (Build.VERSION.SDK_INT >= 24) {
if (!checkPermission()) {
requestPermission();
}
Uri imgContentUri = FileProvider.getUriForFile(getApplicationContext(), BuildConfig.APPLICATION_ID + ".provider", fileImg);
Uri videoContentUri = FileProvider.getUriForFile(getApplicationContext(), BuildConfig.APPLICATION_ID + ".provider", fileVideo);
this.grantUriPermission(getPackageName(), imgContentUri, Intent.FLAG_GRANT_READ_URI_PERMISSION);
this.grantUriPermission(getPackageName(), videoContentUri, Intent.FLAG_GRANT_READ_URI_PERMISSION);
imageView.setImageURI(imgContentUri);
videoView.setVideoPath(String.valueOf(videoContentUri));
mediaController.setAnchorView(videoView);
videoView.setMediaController(mediaController);
videoView.start();
}
}
private void requestPermission() {
ActivityCompat.requestPermissions(this, new String[]{WRITE_EXTERNAL_STORAGE, READ_EXTERNAL_STORAGE}, PERMISSION_ALL);
}
private boolean checkPermission() {
int result = ContextCompat.checkSelfPermission(getApplicationContext(), WRITE_EXTERNAL_STORAGE);
int result1 = ContextCompat.checkSelfPermission(getApplicationContext(), READ_EXTERNAL_STORAGE);
return result == PackageManager.PERMISSION_GRANTED && result1 == PackageManager.PERMISSION_GRANTED;
}
#Override
public void onRequestPermissionsResult(int requestCode, #NonNull String[] permissions, #NonNull int[] grantResults) {
switch (requestCode) {
case PERMISSION_ALL:
if (grantResults.length > 0) {
boolean WriteExternalAccepted = grantResults[0] == PackageManager.PERMISSION_GRANTED;
boolean ReadExternalAccepted = grantResults[1] == PackageManager.PERMISSION_GRANTED;
if (ReadExternalAccepted && WriteExternalAccepted) {
//Snackbar.make(view, "Permission Granted, Now you can access location data and camera.", Snackbar.LENGTH_LONG).show();
} else {
//Snackbar.make(view, "Permission Denied, You cannot access location data and camera.", Snackbar.LENGTH_LONG).show();
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
if (shouldShowRequestPermissionRationale(WRITE_EXTERNAL_STORAGE)) {
showMessageOKCancel("You need to allow access to both the permissions",
new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
requestPermissions(new String[]{WRITE_EXTERNAL_STORAGE, READ_EXTERNAL_STORAGE},
PERMISSION_ALL);
}
}
});
return;
}
}
}
}
break;
}
}
`
AndroidManifest.xml
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE"/>
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>
<uses-permission android:name="android.permission.INTERNET"/>
<provider
android:name="android.support.v4.content.FileProvider"
android:authorities="${applicationId}.provider"
android:exported="false"
android:grantUriPermissions="true">
<meta-data
android:name="android.support.FILE_PROVIDER_PATHS"
android:resource="#xml/provider_paths"/>
</provider>
provider_paths.xml
<path xmlns:android="http://schemas.android.com/apk/res/android">
<root-path name="external_files" path="."/>
</path>
try this
step 1 :- add this permission in manifest file
android.Manifest.permission.READ_EXTERNAL_STORAGE,
step 2 : ask runtime permission
String permission = Manifest.permission.READ_EXTERNAL_STORAGE;
if (ActivityCompat.checkSelfPermission(SearchCityClass.this, permission)
!= PackageManager.PERMISSION_GRANTED ) {
ActivityCompat.requestPermissions(SearchCityClass.this, new String[]
{permission}, 1010);
}
step 3: handle permsiion result
#Override
public void onRequestPermissionsResult(int requestCode, #NonNull String[] permissions,
#NonNull int[] grantResults) {
super.onRequestPermissionsResult(requestCode, permissions, grantResults);
if (requestCode == 1010) {
if (grantResults[0] == PackageManager.PERMISSION_GRANTED) {
Toast.makeText(this, location_permission_granted_msg, Toast.LENGTH_SHORT).show();
} else {
Toast.makeText(this, location_permission_not_granted_msg, Toast.LENGTH_SHORT).show();
}
}
}

required android.permission Read_External_storage, or grantUrlPermissions error

I think my permissions properly located on AndroidManifest.xml.
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.example.ganedu.intent">
<uses-sdk
android:minSdkVersion="8"
android:targetSdkVersion="23" />
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
<application
android:allowBackup="true"
android:icon="#drawable/ic_launcher"
android:label="#string/app_name"
android:supportsRtl="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>
<activity android:name=".NextActivity"
android:label="This is next_activity"/>
</application>
</manifest>
I have "android.permission.READ_EXTERNAL_STORAGE" and "android.permission.WRITE_EXTERNAL_STORAGE" right after manifest.
but the error is keep occured.
Caused by: java.lang.SecurityException: Permission Denial: reading
com.android.providers.media.MediaProvider uri
content://media/external/images/media/40 from pid=2473, uid=10073
requires android.permission.READ_EXTERNAL_STORAGE, or
grantUriPermission()
and this is my MainActivity.java
public class MainActivity extends AppCompatActivity {
public static final int IMAGE_GALLERY_REQUEST = 20;
Button btnStart;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
public void gallery_open(View view) {
Intent galleryPickerIntent = new Intent(Intent.ACTION_PICK);
File pictureDirectory = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES);
String pictureDirectoryPath = pictureDirectory.getPath();
Uri data = Uri.parse(pictureDirectoryPath);
galleryPickerIntent.setDataAndType(data,"image/*");
startActivityForResult(galleryPickerIntent, IMAGE_GALLERY_REQUEST);
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent imageReturnedIntent){
super.onActivityResult(requestCode, resultCode, imageReturnedIntent);
if(resultCode == Activity.RESULT_OK){
if(requestCode == IMAGE_GALLERY_REQUEST) {
onSelectedFromGalleryResult(imageReturnedIntent);
}
}
}
private void onSelectedFromGalleryResult(Intent data){
Bitmap bm = null;
if(data != null){
try{
bm = MediaStore.Images.Media.getBitmap(getApplicationContext().getContentResolver(), data.getData());
}catch(IOException e){
e.printStackTrace();
}
//ivImage.setImageBitmap(bm);
ImageView imgView = (ImageView)findViewById(R.id.ivImage);
imgView.setImageBitmap(bm);
}
}
James I suppose you are facing this error on Android 6.0 or onwards. You need to handle the permissions explicitly in these versions.
Please find the android developer link
https://developer.android.com/guide/topics/permissions/requesting.html
You need to provide the run time permission for android marshmallow version
You can add this code in onCreate() or any click events, try this:
if(Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP_MR1){
// requestPermission();
requestAppPermissions(new String[]{
Manifest.permission.READ_EXTERNAL_STORAGE,Manifest.permission.WRITE_EXTERNAL_STORAGE },
R.string.app_name, REQUEST_PERMISSIONS);
//this code will be executed on devices running ICS or later
}
also add this function for requesting the run time permission
public void requestAppPermissions(final String[] requestedPermissions,
final int stringId, final int requestCode) {
mErrorString.put(requestCode, stringId);
int permissionCheck = PackageManager.PERMISSION_GRANTED;
boolean shouldShowRequestPermissionRationale = false;
for (String permission : requestedPermissions) {
permissionCheck = permissionCheck + ContextCompat.checkSelfPermission(this, permission);
shouldShowRequestPermissionRationale = shouldShowRequestPermissionRationale || ActivityCompat.shouldShowRequestPermissionRationale(this, permission);
}
if (permissionCheck != PackageManager.PERMISSION_GRANTED) {
if (shouldShowRequestPermissionRationale) {
Snackbar.make(findViewById(android.R.id.content), stringId,
Snackbar.LENGTH_INDEFINITE).setAction("GRANT",
new View.OnClickListener() {
#Override
public void onClick(View v) {
ActivityCompat.requestPermissions(DashBoardActivity.this, requestedPermissions, requestCode);
}
}).show();
} else {
ActivityCompat.requestPermissions(this, requestedPermissions, requestCode);
}
} else {
onPermissionsGranted(requestCode);
}
}
This function is called when the permission is granted and you can read the internal and external storage
public void onPermissionsGranted(final int requestCode) {
Toast.makeText(this, "Permissions Received.", Toast.LENGTH_LONG).show();
}
The below code for checking the requested permission result
#Override
public void onRequestPermissionsResult(int requestCode, String[] permissions, int[] grantResults) {
super.onRequestPermissionsResult(requestCode, permissions, grantResults);
int permissionCheck = PackageManager.PERMISSION_GRANTED;
for (int permission : grantResults) {
permissionCheck = permissionCheck + permission;
}
if ((grantResults.length > 0) && permissionCheck == PackageManager.PERMISSION_GRANTED) {
onPermissionsGranted(requestCode);
} else {
Snackbar.make(findViewById(android.R.id.content), mErrorString.get(requestCode),
Snackbar.LENGTH_INDEFINITE).setAction("ENABLE",
new View.OnClickListener() {
#Override
public void onClick(View v) {
}
}).show();
}
}

The writing and reading the same file is not working in android application

I want to write a string to the file abc.txt and later read the same and compare with the input string. But it is not working as desired.
When I do the same by creating a project in netbeans, it works like a charm but here it doesnot.
Code for Writing :
try{
writer = new BufferedWriter( new FileWriter("abc.txt"));
writer.write("12345");
writer.close();
Toast.makeText(getBaseContext(), "Saved", Toast.LENGTH_LONG).show();
}catch(IOException i){
i.printStackTrace();
}
Code for Reading :
String ownerPass= null;
StringBuilder s = new StringBuilder();
try{
FileReader fr=new FileReader("abc.txt");
BufferedReader br=new BufferedReader(fr);
int i;
while((i=br.read())!=-1){
s.append((char)i);
}
br.close();
fr.close();
ownerPass = s.toString();
}catch(IOException i){
i.printStackTrace();
}
The case is same whether I compare s or ownerPass
I don't understand whether it is unable to write file or read file.
Also please tell me how to check the file abc.txt manually in computer.
This is my manifest file :
<?xml version="1.0" encoding="utf-8"?>
<application
android:allowBackup="true"
android:icon="#mipmap/ic_launcher"
android:label="NORIS"
android:roundIcon="#mipmap/ic_launcher_round"
android:supportsRtl="true"
android:theme="#style/AppTheme">
<activity android:name=".MainActivity">
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
if (!Settings.System.canWrite(this)) {
requestPermissions(new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE,
Manifest.permission.READ_EXTERNAL_STORAGE}, 2909);
} else {
// continue with your code
}
} else {
// continue with your code
}
#Override
public void onRequestPermissionsResult(int requestCode, String[] permissions, int[] grantResults) {
switch (requestCode) {
case 2909: {
if (grantResults[0] == PackageManager.PERMISSION_GRANTED) {
Log.e("Permission", "Granted");
} else {
Log.e("Permission", "Denied");
}
return;
}
}
}
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<activity android:name=".userBase" />
<activity android:name=".ownerBase" />
<activity android:name=".ownerPage" />
<activity
android:name=".SettingsActivity"
android:label="#string/title_activity_settings" />
<activity android:name=".ownerBrowse" />
<activity android:name=".ownerEdit"></activity>
</application>
This is my java launcher activity :
public class MainActivity extends AppCompatActivity {
SharedPreferences prefs = null;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
prefs = getSharedPreferences("com.example.srijankumar.myapp1", MODE_PRIVATE);
Button btnUser = (Button) findViewById(R.id.btnUser);
btnUser.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
callUserBase();
}
});
Button btnOwner = (Button) findViewById(R.id.btnOwner);
btnOwner.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
callOwnerBase();
}
});
BufferedWriter writer = null;
try{
writer = new BufferedWriter( new FileWriter("abc.txt"));
writer.write("12345");
writer.close();
Toast.makeText(getBaseContext(), "Saved", Toast.LENGTH_LONG).show();
} catch (Exception e) {
e.printStackTrace();
}
}
private void callOwnerBase() {
Intent i = new Intent(MainActivity.this,ownerBase.class);
startActivity(i);
}
private void callUserBase() {
Intent i = new Intent(MainActivity.this,userBase.class);
startActivity(i);
}
}
have you added manifest permissions and run time permissions?
add this lines in manifest
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
Add this run time permissions in launcher activity:
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
if (!Settings.System.canWrite(this)) {
requestPermissions(new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE,
Manifest.permission.READ_EXTERNAL_STORAGE}, 2909);
} else {
// continue with your code
}
} else {
// continue with your code
}
#Override
public void onRequestPermissionsResult(int requestCode, String[] permissions, int[] grantResults) {
switch (requestCode) {
case 2909: {
if (grantResults[0] == PackageManager.PERMISSION_GRANTED) {
Log.e("Permission", "Granted");
} else {
Log.e("Permission", "Denied");
}
return;
}
}
}

Categories

Resources