1. Add Any Permission To Manifest And Boolean Method
2. How To Create Directory in External Storage
3. How To create File Reading Method For All Api
4. How To Create File []
5. How To Filter File [] on Runtime Filter
6. How To Create File Sub-Directory
7. How To check if File or Directory Exist
8. How To Sort Files Names Array In Ascending Order
9. How To Add Numbering In Array ListView
10. How To Create Universal Context and Use On Demand
///////////////////////////////////////////////////////////
Manifest.xml :
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools">
<uses-permission android:name="android.permission.CAMERA" />
<uses-permission android:name="android.permission.POST_NOTIFICATIONS" />
<uses-permission android:name="android.permission.READ_MEDIA_IMAGES" />
<uses-permission android:name="android.permission.READ_MEDIA_AUDIO" />
<uses-permission android:name="android.permission.READ_MEDIA_VIDEO" />
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />
<uses-permission
android:name="android.permission.WRITE_EXTERNAL_STORAGE"
tools:ignore="ScopedStorage" />
<application
android:name="._MyApplication"
android:allowBackup="true"
android:dataExtractionRules="@xml/data_extraction_rules"
android:fullBackupContent="@xml/backup_rules"
android:icon="@mipmap/ic_launcher"
android:label="@string/app_name"
android:supportsRtl="true"
android:theme="@style/Theme.CreateDatabase"
tools:targetApi="31">
<activity
android:name=".InsertOrModifyFile"
android:exported="false" />
<activity
android:name=".DarsFileRead"
android:exported="false" />
<activity
android:name=".MainActivity"
android:exported="true">
<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}.provider"
android:exported="false"
android:grantUriPermissions="true">
<meta-data
android:name="android.support.FILE_PROVIDER_PATHS"
android:resource="@xml/file_provider_paths" />
</provider>
</application>
</manifest>
Permission :
////////////////////////////////////////////////////////////////////////////////////////
public static final int REQUEST_ID_MULTIPLE_PERMISSIONS = 1;
private boolean checkAndRequestPermissions() {
int permissionReadExternalStorage;
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.TIRAMISU)
permissionReadExternalStorage = ContextCompat.checkSelfPermission(this,
Manifest.permission.READ_MEDIA_IMAGES);
else
permissionReadExternalStorage = ContextCompat.checkSelfPermission(this,
Manifest.permission.READ_EXTERNAL_STORAGE);
int permissionWriteExtarnalStorage;
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.TIRAMISU)
permissionWriteExtarnalStorage = ContextCompat.checkSelfPermission(this,
Manifest.permission.READ_MEDIA_AUDIO);
else
permissionWriteExtarnalStorage = ContextCompat.checkSelfPermission(this,
Manifest.permission.WRITE_EXTERNAL_STORAGE);
List<String> listPermissionsNeeded = new ArrayList<>();
if (permissionWriteExtarnalStorage != PackageManager.PERMISSION_GRANTED) {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.TIRAMISU)
listPermissionsNeeded.add(Manifest.permission.READ_MEDIA_AUDIO);
else
listPermissionsNeeded.add(Manifest.permission.WRITE_EXTERNAL_STORAGE);
}
if (permissionReadExternalStorage != PackageManager.PERMISSION_GRANTED) {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.TIRAMISU)
listPermissionsNeeded.add(Manifest.permission.READ_MEDIA_IMAGES);
else
listPermissionsNeeded.add(Manifest.permission.READ_EXTERNAL_STORAGE);
}
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.TIRAMISU) {
int permissionVideoStorage = ContextCompat.checkSelfPermission(this,
Manifest.permission.READ_MEDIA_VIDEO);
if (permissionVideoStorage != PackageManager.PERMISSION_GRANTED) {
listPermissionsNeeded.add(Manifest.permission.READ_MEDIA_VIDEO);
}
int notificationPermission = ContextCompat.checkSelfPermission(this,
Manifest.permission.POST_NOTIFICATIONS);
if (notificationPermission != PackageManager.PERMISSION_GRANTED) {
listPermissionsNeeded.add(Manifest.permission.POST_NOTIFICATIONS);
}
}
int cameraPermission = ContextCompat.checkSelfPermission(this, Manifest.permission.CAMERA);
if(cameraPermission != PackageManager.PERMISSION_GRANTED){
listPermissionsNeeded.add(Manifest.permission.CAMERA);
}
if (!listPermissionsNeeded.isEmpty()) {
ActivityCompat.requestPermissions(this, listPermissionsNeeded.toArray(new String[0]), REQUEST_ID_MULTIPLE_PERMISSIONS);
return false;
}
return true;
}
@SuppressWarnings("ConstantConditions")
@Override
public void onRequestPermissionsResult(int requestCode,
@NonNull String permissions[], @NonNull int[] grantResults) {
super.onRequestPermissionsResult(requestCode, permissions, grantResults);
switch (requestCode) {
case REQUEST_ID_MULTIPLE_PERMISSIONS: {
Map<String, Integer> perms = new HashMap<>();
// Initialize the map with both permissions
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.TIRAMISU) {
perms.put(Manifest.permission.READ_MEDIA_IMAGES, PackageManager.PERMISSION_GRANTED);
perms.put(Manifest.permission.READ_MEDIA_AUDIO, PackageManager.PERMISSION_GRANTED);
perms.put(Manifest.permission.READ_MEDIA_VIDEO, PackageManager.PERMISSION_GRANTED);
perms.put(Manifest.permission.POST_NOTIFICATIONS, PackageManager.PERMISSION_GRANTED);
} else {
perms.put(Manifest.permission.WRITE_EXTERNAL_STORAGE, PackageManager.PERMISSION_GRANTED);
perms.put(Manifest.permission.READ_EXTERNAL_STORAGE, PackageManager.PERMISSION_GRANTED);
}
perms.put(Manifest.permission.CAMERA, PackageManager.PERMISSION_GRANTED);
// Fill with actual results from user
if (grantResults.length > 0) {
for (int i = 0; i < permissions.length; i++)
perms.put(permissions[i], grantResults[i]);
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.TIRAMISU) {
if (perms.get(Manifest.permission.READ_MEDIA_IMAGES) == PackageManager.PERMISSION_GRANTED
&& perms.get(Manifest.permission.READ_MEDIA_AUDIO) == PackageManager.PERMISSION_GRANTED
&& perms.get(Manifest.permission.READ_MEDIA_VIDEO) == PackageManager.PERMISSION_GRANTED
&& perms.get(Manifest.permission.POST_NOTIFICATIONS) == PackageManager.PERMISSION_GRANTED
&& perms.get(Manifest.permission.CAMERA) == PackageManager.PERMISSION_GRANTED
) {
// All Permissions Are granted :
Toast.makeText(this, "Jajakumullah, For Granting Permission.", Toast.LENGTH_LONG).show();
makeFileListInListView();
//else any one or both the permissions are not granted
} else {
if (ActivityCompat.shouldShowRequestPermissionRationale(this, Manifest.permission.READ_MEDIA_IMAGES)
|| ActivityCompat.shouldShowRequestPermissionRationale(this, Manifest.permission.READ_MEDIA_AUDIO)
|| ActivityCompat.shouldShowRequestPermissionRationale(this, Manifest.permission.READ_MEDIA_VIDEO)
|| ActivityCompat.shouldShowRequestPermissionRationale(this, Manifest.permission.POST_NOTIFICATIONS)
|| ActivityCompat.shouldShowRequestPermissionRationale(this, Manifest.permission.CAMERA)
) {
showDialogOK("Necessary Permissions required for this app",
new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
switch (which) {
case DialogInterface.BUTTON_POSITIVE:
checkAndRequestPermissions();
break;
case DialogInterface.BUTTON_NEGATIVE:
// proceed with logic by disabling the related features or quit the app.
Toast.makeText(MainActivity.this, "Necessary Permissions required for this app", Toast.LENGTH_LONG).show();
// permissionSettingScreen ( );
// finish();
break;
}
}
});
}
//permission is denied (and never ask again is checked)
//shouldShowRequestPermissionRationale will return false
else {
permissionSettingScreen();
}
}
} else {
if (perms.get(Manifest.permission.WRITE_EXTERNAL_STORAGE) == PackageManager.PERMISSION_GRANTED
&& perms.get(Manifest.permission.READ_EXTERNAL_STORAGE) == PackageManager.PERMISSION_GRANTED
&& perms.get(Manifest.permission.CAMERA) == PackageManager.PERMISSION_GRANTED
) {
Toast.makeText(this, "Jajakumullah, For Granting Permission.", Toast.LENGTH_LONG).show();
//else any one or both the permissions are not granted
} else {
if (ActivityCompat.shouldShowRequestPermissionRationale(this, Manifest.permission.WRITE_EXTERNAL_STORAGE)
|| ActivityCompat.shouldShowRequestPermissionRationale(this, Manifest.permission.READ_EXTERNAL_STORAGE)
|| ActivityCompat.shouldShowRequestPermissionRationale(this, Manifest.permission.CAMERA)
) {
showDialogOK("Necessary Permissions required for this app",
new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
switch (which) {
case DialogInterface.BUTTON_POSITIVE:
checkAndRequestPermissions();
break;
case DialogInterface.BUTTON_NEGATIVE:
// proceed with logic by disabling the related features or quit the app.
Toast.makeText(MainActivity.this, "Necessary Permissions required for this app", Toast.LENGTH_LONG).show();
// permissionSettingScreen ( );
// finish();
break;
}
}
});
}
//permission is denied (and never ask again is checked)
//shouldShowRequestPermissionRationale will return false
else {
permissionSettingScreen();
}
}
}
}
}
}
}
private void permissionSettingScreen() {
Toast.makeText(this, "Enable All permissions, Click On Permission", Toast.LENGTH_LONG)
.show();
Intent intent = new Intent();
intent.setAction(Settings.ACTION_APPLICATION_DETAILS_SETTINGS);
intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
Uri uri = Uri.fromParts("package", getPackageName(), null);
intent.setData(uri);
startActivity(intent);
// finishAffinity();
finish();
}
private void showDialogOK(String message, DialogInterface.OnClickListener okListener) {
new AlertDialog.Builder(this)
.setMessage(message)
.setPositiveButton("OK", okListener)
.setNegativeButton("Cancel", okListener)
.create()
.show();
}
Make File List :
String FILE_TOIRY_FOLDER_NAME_STRING = "Darsul_Quran";
public void makeFileListInListView() {
File dir = commonDir();
if (!dir.exists())
dir.mkdir();
File subDir = new File(dir + "/" + FILE_TOIRY_FOLDER_NAME_STRING);
if (!subDir.exists())
subDir.mkdir();
fileList = GetFilesList(subDir.toString());
fileListView.setAdapter(null);
if (fileList != null && fileList.size() > 0) {
// fileAdapter = new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1, fileListArray);
fileNamesArray = new String[fileList.size()];
fileNamesArray = fileList.toArray(fileNamesArray);
mainAdapter = new AdapterFilesCreate(mContext, R.layout.sahitto_dropdown_layout, R.id.textview_item, fileNamesArray, newCreatedFile);
fileListView.setAdapter(mainAdapter);
empty_text.setVisibility(View.GONE);
} else {
empty_text.setVisibility(View.VISIBLE);
}
}
ArrayList<String> filesNamesListPure;
ArrayList<String> filePathList;
public ArrayList<String> GetFilesList(String DirectoryPath) {
darFilesStaticList = new ArrayList<>();
filesNamesListPure = new ArrayList<String>();
filePathList = new ArrayList<>();
ArrayList<String> MyFiles = new ArrayList<String>();
File f = new File(DirectoryPath);
f.mkdirs();
File[] files = f.listFiles(new FilenameFilter() {
public boolean accept(File dir, String name) {
return checkDbFileName(name);
}
});
int fileNumber = 1;
assert files != null;
if (files.length == 0)
return null;
else {
Arrays.sort(files, sortFilesAscendingOrder);
for (int i = 0; i < files.length; i++) {
String fileName = files[i].getName();
if (checkDbFileName(fileName)) {
String s = files[i].getName();
String filePath = files[i].getPath();
if (checkDbFileName(s)) {
s = s.replace(".db", "");
MyFiles.add(fileNumber + ". " + s.trim()); // for extra security
filesNamesListPure.add(s.trim()); // for extra security
darFilesStaticList.add(s.trim()); // for alertDialog items ;
filePathList.add(filePath);
fileNumber++;
}
}
}
}
return MyFiles;
}
Another Methods In Common.java:
public static File commonDir() {
File dir = null;
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.R) {
dir = new File(_MyApplication.getContext().getExternalFilesDir(null) + "/tilawaat");
} else {
dir = new File(Environment.getExternalStorageDirectory() + "/tilawaat");
}
try {
if (!dir.exists()) {
// Make it, if it doesn't exit
boolean success = false;
try {
success = dir.mkdirs();
} catch (Exception e) {
e.printStackTrace();
}
if (!success) {
dir = null;
}
}
} catch (Exception e) {
e.printStackTrace();
}
System.out.println("Called 13: " + dir.toString());
return dir;
}
public static boolean checkDbFileName(String fileName) {
return !fileName.toLowerCase().endsWith(".db-journal".toLowerCase())
&& !fileName.toLowerCase().endsWith(".db-wal".toLowerCase())
&& !fileName.toLowerCase().endsWith(".db-shm".toLowerCase());
}
public static Comparator<? super File> sortFilesAscendingOrder = new Comparator<File>(){
public int compare(File file1, File file2) {
if(file1.isDirectory()){
if (file2.isDirectory()){
return String.valueOf(file1.getName().toLowerCase()).compareTo(file2.getName().toLowerCase());
}else{
return -1;
}
}else {
if (file2.isDirectory()){
return 1;
}else{
return String.valueOf(file1.getName().toLowerCase()).compareTo(file2.getName().toLowerCase());
}
}
}
};
Universal Context :
package first.learn.createdatabase;
import android.annotation.SuppressLint;
import android.app.Application;
import android.content.Context;
import android.os.Handler;
import android.os.Looper;
import androidx.multidex.MultiDex;
public class _MyApplication extends Application {
@SuppressLint("StaticFieldLeak")
private static Context context;
@Override
public void onCreate() {
super.onCreate();
context = getApplicationContext(); // Grab the Context you want.
}
@Override
protected void attachBaseContext(Context base) {
super.attachBaseContext(base);
MultiDex.install(this);
}
public static Context getContext() {
return context;
}
private static final Handler mHandler = new Handler();
public static void runOnUiThread(Runnable runnable) {
if (Thread.currentThread() == Looper.getMainLooper().getThread()) {
runnable.run();
} else {
mHandler.post(runnable);
}
}
}
No comments:
Post a Comment