I have a basic File Browser inside my app and I want it to be able to open PDF files, but for some reason, even though I can tap on the PDF files and they open for a second, they go away and my phone gives a Toast message with an error, and this Toast I haven't programmed anywhere in my code. This is weird because the same PDF file opens from my other activities without any issues. (See the OpenPDF() Method which works from my PDFManager class) I researched a lot about how to fix this but couldn't find a clear answer. Thanks for helping!
The toast error: Cannot display PDF (filename.pdf cannot be opened)
OnListItemClick function from AndroidFileBrowser:
#Override
protected void onListItemClick(ListView l, View v, int position, long id) {
String filename = (String) getListAdapter().getItem(position);
if (path.endsWith(File.separator)) {
filename = path + filename;
} else {
filename = path + File.separator + filename;
}
pdf = new File(Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS).getPath() + "/PATH/" + filename);
Uri path = Uri.fromFile(pdf);
Intent intent = new Intent();
intent.setAction(Intent.ACTION_VIEW);
intent.setDataAndType(path, "application/pdf");
intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
try {
startActivity(intent);
} catch (ActivityNotFoundException e) {
e.printStackTrace();
}
}
AndroidManifest.xml:
<?xml version="1.0" encoding="utf-8"?>
<manifest package="com.faraz.pdfreader"
xmlns:android="http://schemas.android.com/apk/res/android">
<uses-permission android:name="android.permission.CAMERA"/>
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>
<uses-permission android:name="android.permission.INTERNET"/>
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE"/>
<uses-permission android:name="android.permission.READ_PHONE_STATE"/>
<application
android:allowBackup="true"
android:icon="#mipmap/ic_launcher"
android:label="#string/app_name"
android:theme="#style/AppTheme"
>
<activity
android:name=".MainActivity"
android:label="#string/app_name"
android:screenOrientation="portrait">
<intent-filter>
<action android:name="android.intent.action.MAIN"/>
<category android:name="android.intent.category.LAUNCHER"/>
</intent-filter>
</activity>
<activity
android:name=".SimpleScannerActivity"
android:label="#string/simple_scanner_activity"
android:theme="#style/AppOverlayTheme">
</activity>
<activity android:name=".PDFManager"/>
<activity android:name=".AndroidFileBrowser"/>
<!--android:screenOrientation="portrait"-->
</application>
</manifest>
OpenPDF() method from my PDFManager class
public void openPDF() {
File pdf = new File(Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS).getPath() + "/PATH/" + pdfname + ".pdf");
if (pdf.exists()) {
Uri path = Uri.fromFile(pdf);
Intent intent = new Intent();
intent.setAction(Intent.ACTION_VIEW);
intent.setDataAndType(path, "application/pdf");
intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
try {
startActivity(intent);
} catch (ActivityNotFoundException e) {
Toast.makeText(PDFManager.this,
"No application available to view PDF!",
Toast.LENGTH_SHORT).show();
/* Intent intent = new Intent(Intent.ACTION_VIEW)
.setData(Uri.parse("http://docs.google.com/gview?embedded=true&url=" + url));
startActivity(intent);
}
*/
}
}
}
}
In your OnItemClick():
if (path.endsWith(File.separator))
{
filename = path + filename;
}
else
{
filename = path + File.separator + filename;
}
pdf = new File(Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS).getPath() + "/PATH/" + filename);
Uri path = Uri.fromFile(pdf);
You use "path" before you initialize it, so depending on your intentions either change the name of one or the other, or declare it before your if-statement not after.
Related
I am sending images to firebase. but when my upload pictures method starts running, I get no auth token printed into my logcat couple of times. I tried using both camera and gallery, but they both make the same output even though my firebase storage rules are:
rules_version = '2';
service firebase.storage {
match /b/{bucket}/o {
match /{allPaths=**} {
allow read, write;
}
}
}
And my code is:
if (fragment3.isAdded()) {
EditText plantdetails = (EditText) fragment3.getView().findViewById(R.id.plantdetails);
if (plantdetails.getText().toString().equals("")) {
Toast.makeText(newPlant.this, "I think you forgot something.", Toast.LENGTH_LONG).show();
} else {
plants plantss = new plants();
SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(newPlant.this);
prefs.edit().putString("pldetails", plantdetails.getText().toString()).apply();
String pname = prefs.getString("plname","null");
String pdate = prefs.getString("pldate","null");
String petails = prefs.getString("pldetails","null");
plantss.setPlname(pname);
plantss.setPldate(pdate);
plantss.setPldetails(petails);
reference.child("Plants").child(pname).setValue(plantss);
try {
Fileuploader();
}catch (FileNotFoundException e){
e.printStackTrace();
}
}
}
if (fragment4.isAdded()){
}
}
});
}
private void Fileuploader() throws FileNotFoundException {
String imageid;
progress.showProgress(newPlant.this,"Loading...",false);
DatabaseHelper databaseHelper = new DatabaseHelper(newPlant.this);
Cursor getimage = databaseHelper.GetPath();
SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(newPlant.this);
String plname = prefs.getString("plname","null");
int count = 0;
int count2 = 0;
if (getimage !=null){
while (getimage.moveToNext()) {
System.out.println("IMAGE IS THIS MY MAN: "+ getimage.getString(0));
Bitmap bm = BitmapFactory.decodeFile(getimage.getString(0));
if (bm == null){
return;
}else {
ByteArrayOutputStream out = new ByteArrayOutputStream();
bm.compress(Bitmap.CompressFormat.JPEG, 35, out);
imageid = System.currentTimeMillis() + "_" + (count++) + "." + getExtension(uri);
DatabaseReference reference = FirebaseDatabase.getInstance().getReference().child("Plants").child(plname).child("PlantImages");
String imagekey = reference.push().getKey();
reference.child(imagekey).child("ImageID").setValue(imageid);
reference.child(imagekey).child("ID").setValue(count2++);
System.out.println("IMAGES UPLOADEDDDD: " + imageid);
byte[] data = out.toByteArray();
StorageReference Ref = mStorageRef.child(imageid);
Ref.putBytes(data)
.addOnSuccessListener(new OnSuccessListener<UploadTask.TaskSnapshot>() {
#Override
public void onSuccess(UploadTask.TaskSnapshot taskSnapshot) {
// Get a URL to the uploaded content
//Uri downloadUrl = taskSnapshot.getDownloadUrl();
//Toast.makeText(profuctadd.this,"Image uploaded",Toast.LENGTH_LONG).show();
progress.hideProgress();
Intent intent = new Intent(newPlant.this, Donenewplant.class);
startActivity(intent);
finish();
DatabaseHelper mDatabaseHelper = new DatabaseHelper(newPlant.this);
Cursor cursor2 = mDatabaseHelper.DeleteDataOfTableImagesAr();
cursor2.moveToNext();
}
})
.addOnFailureListener(new OnFailureListener() {
#Override
public void onFailure(#NonNull Exception exception) {
// Handle unsuccessful uploads
// ...
Toast.makeText(newPlant.this, "Failed", Toast.LENGTH_LONG).show();
System.out.println("FAILED:::: "+exception);
}
});
}
}
}
}
Mainfest file:
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.varroxsystems.plant">
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.CAMERA" />
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE"/>
<application
android:allowBackup="true"
android:icon="#drawable/plant"
android:label="#string/app_name"
android:roundIcon="#drawable/plant"
android:supportsRtl="true"
android:requestLegacyExternalStorage="true"
android:theme="#style/AppTheme">
<activity android:name=".Donenewplant"></activity>
<activity android:name=".newPlant" />
<activity android:name=".MainActivity" />
<activity android:name=".Splash_screen">
<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="com.varroxsystems.plant.fileprovider"
android:exported="false"
android:grantUriPermissions="true">
<meta-data
android:name="android.support.FILE_PROVIDER_PATHS"
android:resource="#xml/file_paths" />
</provider>
</application>
</manifest>
So does anyone know a solution for that, or is it just a bug, because I use the same exact code in another app and it works just fine.
EDIT: The other app I use uses a different database, not the same one.
I am trying to make a simple application in Java to install an APK on Android devices connected via USB. Using ABD manually or installing from Android Studio it works fine, but I wanted to give a simple single button click install option within my application, I have tried following code but unfortunately, it is not working
abdsourcesync = apkpath;
progress.setString("sync in progress");
System.out.println("Starting Sync via adb with command " + "adb"
+ " install -r " + apkpath);
Process process = Runtime.getRuntime().exec(
"adb" + " install -r " + apkpath);
InputStreamReader reader = new InputStreamReader(
process.getInputStream());
Scanner scanner = new Scanner(reader);
scanner.close();
int exitCode = process.waitFor();
System.out.println("Process returned: " + exitCode);
I have searched around here but I have only found installing an APK from within an Android application or from the android studio, not from a core Java. or java web module
Your helping hand would be really appreciated ;
Do not forget about runtime permissions
This simple example works for me for API 28.
It opens an apk file to install from "Download folder"
For simplification:
Download the apk file for application you want to install to "Download" folder of your phone. (There are a lot of instructions to do it programmaticaly, ot you can do it manualy)
TO DO
Create new project
Add a button to MainActivity
Create xml folder in res folder and create a file_paths.xml file there
Use the code bellow
Enjoy =)
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.teko.testcleanopenfile">
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.REQUEST_INSTALL_PACKAGES"/>
<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"
tools:ignore="GoogleAppIndexingWarning">
<activity android:name=".MainActivity">
<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/file_paths" />
</provider>
</application>
</manifest>
MainActivity
public class MainActivity extends AppCompatActivity {
TextView textView;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
// textView and button
textView = findViewById(R.id.textView);textView.setText("Hello updatable World\n");
(findViewById(R.id.button)).setOnClickListener(new View.OnClickListener() {
#RequiresApi(api = Build.VERSION_CODES.M)
#Override
public void onClick(View view) {RunAPK(getBaseContext());}
});
}
private void RunAPK(Context context){
requestPermissionsToRead();
}
private void requestPermissionsToRead() {
// ASK RUNTIME PERMISSIONS
ActivityCompat.requestPermissions(MainActivity.this, new String[]{READ_EXTERNAL_STORAGE},111);
}
#Override
public void onRequestPermissionsResult(int requestCode, #NonNull String[] permissions, #NonNull int[] grantResults) {
if (grantResults.length > 0) {
if (requestCode == 111 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
textView.append("Permission granted write\n");
// Create Uri
File downloads = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS);
File file1 = new File (downloads + "//app-debug.apk");//downloads.listFiles()[0];
Uri contentUri1 = getUriForFile(this, BuildConfig.APPLICATION_ID, file1);
// Intent to open apk
Intent intent = new Intent(Intent.ACTION_VIEW, contentUri1);
intent.setDataAndType(contentUri1, "application/vnd.android.package-archive");
intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
startActivity(intent);
}
}
}
}
file_paths.xml
<?xml version="1.0" encoding="utf-8"?>
<paths xmlns:android="http://schemas.android.com/apk/res/android">
<external-path name="download" path="."/>
</paths>
You can Install Application from Java code using below way.
File outputFile = null;
try {
outputFile = new File(<APK Path>);
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
Uri apkUri = FileProvider.getUriForFile(mContext, BuildConfig.APPLICATION_ID + ".provider", outputFile);
Intent intent = new Intent(Intent.ACTION_INSTALL_PACKAGE);
intent.setData(apkUri);
intent.setFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
mContext.startActivity(intent);
} else if (Build.VERSION.SDK_INT < Build.VERSION_CODES.N){
Uri apkUri = Uri.fromFile(outputFile);
Intent intent = new Intent(Intent.ACTION_VIEW);
intent.setDataAndType(apkUri, "application/vnd.android.package-archive");
intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
mContext.startActivity(intent);
}else {
Toast.makeText(mContext, "File not found.", Toast.LENGTH_LONG).show();
}
} catch (Exception e) {
e.printStackTrace();
}
I have written codes from the tutorials of SLIDENERD to save info in different areas as internal cache,External cache,Private information and public information with the following codes.
EditText uname,pwd;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
uname=(EditText)findViewById(R.id.editText);
pwd=(EditText)findViewById(R.id.editText3);
}
public void intCache(View view){
File fileDir=getCacheDir();
File myFile=new File(fileDir,"User_info_intCache.txt");
write(myFile);
}
public void extCache(View view){
File fileDir=getExternalCacheDir();
File myFile=new File(fileDir,"User_info_extCache.txt");
write(myFile);
}
public void pvtDir(View view){
File fileDir=getExternalFilesDir("User_Info");
File myFile=new File(fileDir,"User_info_pvtExt.txt");
write(myFile);
}
public void pubDir(View view){
File fileDir= Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS);
File myFile=new File(fileDir,"User_info_pubExt.txt");
write(myFile);
}
private void write(File myFile){
String unameS=uname.getText().toString();
String pwdS=pwd.getText().toString();
FileOutputStream fileOutputStream=null;
try {
fileOutputStream=new FileOutputStream(myFile);
try {
fileOutputStream.write(unameS.getBytes());
fileOutputStream.write(pwdS.getBytes());
} catch (IOException e) {
e.printStackTrace();
}
} catch (FileNotFoundException e) {
e.printStackTrace();
}
finally {
try {
if (fileOutputStream != null) {
fileOutputStream.close();
}
Toast.makeText(this,"data is written to "+myFile.getAbsolutePath(),Toast.LENGTH_LONG).show();
} catch (IOException e) {
e.printStackTrace();
}
}
}
I can see the files user_info_extCache.txt , User_info_pvtExt.txt. I know that internal cache location ( User_info_intCache.txt ) cant be seen.But i can't find the User_info_pubExt.txt file which must be stored in public directory Downloads.I cant see the file created by following code.
File fileDir= Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS);
File myFile=new File(fileDir,"User_info_pubExt.txt");
The toast shows that the file is created by above piece of code under /storage/emulated/0/Download/User_info_pubExt.txt .
I find somewhere that if phone is connected to pc,external storage cant be accessed.So i tried both by removing the mobile from pc.The toast says that file is created.But i cant find it under that folder.
AndroidManifest.xml
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.example.iamka.storage">
<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>
<activity android:name=".Main2Activity"></activity>
</application>
Your toast claiming that data is written is on the wrong place. As the toast also displays when there is an exception.
Place the toast in the try block instead. Or yet better after the close() but only if you close().
And place other toasts in the catch blocks to inform the user with e.getMessage().
As for the exception: all the paths exept the last one do not need any read/write permission at all. For the latter you need read/write permission.
But requesting them in manifest is not enough for Android 6+ as then you have to add some code to ask the user to confirm the requested permissions.
Google for runtime permissions.
I am new to firebase. I was using an old version code where the parameters i put were atleast working for the url. but now when link is clicked, the browser opens and its a 400 error that requested url was not found. it works with only the dynamic link
button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Uri BASE_URI = Uri.parse("http://example.com/");
Uri APP_URI = BASE_URI.buildUpon().
appendQueryParameter("extra1", "value").build();
String encodedUri = null;
try {
encodedUri = URLEncoder.encode(APP_URI.toString(), "UTF-8");
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
Log.v("ENCODED URI: ", encodedUri);
Uri deepLink = Uri.parse("https://eh62u.app.goo.gl/y6N7/?link="+encodedUri);
Intent intent = new Intent(Intent.ACTION_SEND);
intent.setType("text/plain");
intent.putExtra(Intent.EXTRA_EMAIL, "");
intent.putExtra(Intent.EXTRA_SUBJECT, "GET TICKETS" );
intent.putExtra(Intent.EXTRA_TEXT, "Click here to get the booked tickets: " + deepLink);
startActivity(Intent.createChooser(intent, "Send Email"));
}
});
}
Main Activity OnCreate code:
setContentView(R.layout.activity_main);
button = (Button) findViewById(R.id.button);
FirebaseDynamicLinks.getInstance().getDynamicLink(getIntent())
.addOnSuccessListener(this, new OnSuccessListener<PendingDynamicLinkData>() {
#Override
public void onSuccess(PendingDynamicLinkData data) {
if (data == null) {
Log.d("NULL DATA ", "getInvitation: no data");
return;
}
// Get the deep link
Uri deepLink = data.getLink();
String requestId2 = deepLink.getQueryParameter("extra1");
// Handle the deep link
// [START_EXCLUDE]
Log.d("DEEP LINK URL ", "deepLink:" + deepLink);
if (deepLink != null) {
if(requestId2 == "value") {
Intent intent = new Intent(getApplicationContext(), Main2Activity.class);
startActivity(intent);
}
}
// [END_EXCLUDE]
}
})
.addOnFailureListener(this, new OnFailureListener() {
#Override
public void onFailure(#NonNull Exception e) {
Log.w("onFailure: ", "getDynamicLink:onFailure", e);
}
});
Android Manifest Code:
<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>
<intent-filter> <action android:name="android.intent.action.VIEW"/>
<category android:name="android.intent.category.DEFAULT"/>
<category android:name="android.intent.category.BROWSABLE"/>
<data
android:host="example.com"
android:scheme="https"/>
</intent-filter>
</activity>
<activity android:name=".Main2Activity">
</activity>
</application>
how do i put the parameter and then get it in the onSuccess? Thanks
The problem that i finally figured out by trial and error was the encoding part of the code. When i removed the :
encodedUri = URLEncoder.encode(APP_URI.toString(), "UTF-8");
part and just passed APP_URI to the deep link like
Uri deepLink = Uri.parse("https://eh62u.app.goo.gl/y6N7/?link="+APP_URI);
or even constructing the link using builder as:
Uri.Builder URLbuilder = new Uri.Builder()
.scheme("https")
.authority(Constants.DOMAIN)
.path("/")
.appendQueryParameter("link", getBaseUri(value))
.appendQueryParameter("apn", context.getPackageName());
It worked. No Problems. Retrieving the parameter was the usual.
I've been searching the internet for several hours now in an attempt to find a file writing function that actually works for me. So far I have this in my MainActivity.java:
public void writeToFile(String data, Context ctx) {
File path = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOCUMENTS);
File tempFile = new File(path, "houseDataFile.txt");
if(!tempFile.exists()){
tempFile.mkdirs();
}
try
{
FileOutputStream fOut = new FileOutputStream(tempFile);
fOut.write(data.getBytes());
fOut.close();
Toast.makeText(ctx, "Saved", Toast.LENGTH_SHORT).show();
}catch (Exception e)
{
Log.w(TAG, "FileOutputStream exception: - " + e.toString());
}
}
My android manifest contains both permissions:
<?xml version="1.0" encoding="utf-8"?>
<manifest package="my.package.application"xmlns:android="http://schemas.android.com/apk/res/android">
<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:supportsRtl="true"
android:theme="#style/AppTheme">
<activity android:name=".MainActivity">
</activity>
<activity android:name=".Menu_activity">
<intent-filter>
<action android:name="android.intent.action.MAIN"/>
<category android:name="android.intent.category.LAUNCHER"/>
</intent-filter>
</activity>
</application>
Though rather frustratingly when I run the app and call writeToFile() it gives me an error saying:
W/MainActivity: FileOutputStream exception: - java.io.FileNotFoundException: /storage/emulated/0/Documents/houseDataFile.txt: open failed: ENOENT (No such file or directory)
Any help would be greatly appreciated, thank you in advance.
I'm assuming that you are failing to get the file path because you don't asking runtime-permission while executing method. Here you can take a look at the below code.
First, check if your device's OS version is above Lollipop or not. If above then show permission pop-up dialog.
final int MyVersion = Build.VERSION.SDK_INT;
if (MyVersion > Build.VERSION_CODES.LOLLIPOP_MR1)
{
if (!checkIfAlreadyhavePermission())
{
ActivityCompat.requestPermissions(ProfileActivity.this, new String[] {android.Manifest.permission.READ_EXTERNAL_STORAGE}, 1);
}
else
{
writeToFile(data, ctx);
}
}
else
{
writeToFile(data, ctx)
}
private boolean checkIfAlreadyhavePermission() {
int result = ContextCompat.checkSelfPermission(this, Manifest.permission.READ_EXTERNAL_STORAGE);
return result == PackageManager.PERMISSION_GRANTED;
}
Then define "Allow" and "Deny" button functionalities in OnRequestPerMissionResult().
public void onRequestPermissionsResult(int requestCode, String permissions[], int[] grantResults) {
switch (requestCode) {
case 1: {
// If request is cancelled, the result arrays are empty.
if (grantResults.length > 0
&& grantResults[0] == PackageManager.PERMISSION_GRANTED) {
writeToFile( data, ctx);
} else {
Toast.makeText(YourActivity.this, "Please provide permission", Toast.LENGTH_LONG).show();
}
break;
}
}
Please let me know if this solves the issue.