part 39 : File Search Adapter And Check If File Exist

1. Convert ArrayList To String Array
2. Change Adapter Constructor From String [] to String List
3. Check if File Exist in Directory Path
4. Hide Keyboard By the Help of Any
5. Understaiding Migrating AndroidX
6. Send Constructor Parameter as new File name When File Just Created
7. Change Color of Specific Item In ListView And Adapter Specific Position



////////////////////////////////////////

File Search Adapter : 

package first.learn.createdatabase;

/**
* Created by bismillah on 11/1/2017.
*/



import android.annotation.SuppressLint;
import android.app.Activity;
import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.pm.PackageManager;
import android.content.pm.ResolveInfo;
import android.content.res.ColorStateList;
import android.graphics.Color;
import android.graphics.Typeface;
import android.media.MediaPlayer;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.os.StrictMode;
import android.preference.PreferenceManager;
import android.text.Spannable;
import android.text.SpannableString;
import android.text.style.TextAppearanceSpan;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewGroup;
import android.view.inputmethod.InputMethodManager;
import android.widget.ArrayAdapter;
import android.widget.Filter;
import android.widget.TextView;
import androidx.annotation.NonNull;
import androidx.core.content.ContextCompat;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Locale;


public class AdapterFilesCreate extends ArrayAdapter<String> {
private final LayoutInflater mInflater;
private final Context mContext;
private final int mResource;
private List<String> mObjects;
private int mFieldId = 0;
private ArrayList<String> mOriginalValues;
private ArrayFilter mFilter;
private final Object mLock = new Object();
private String mSearchText; // this var for highlight



private String newCreatedFile = null;

private ArrayList<String> audioVideoUrlList = null;
ArrayList<String> fileNameListPure;
private boolean isAudioActivity = false;


public AdapterFilesCreate(Context context, int resource, int textViewResourceId, ArrayList<String> objects, String newCreateFile) {
super(context, resource, textViewResourceId, objects);
mContext = context;
mInflater = LayoutInflater.from(context);
mResource = resource;
mObjects = objects;
mFieldId = textViewResourceId;
this.newCreatedFile = newCreateFile;
StrictMode.VmPolicy.Builder builder = new StrictMode.VmPolicy.Builder();
StrictMode.setVmPolicy(builder.build());
}


public AdapterFilesCreate(Context context, int resource, int textViewResourceId, String[] objects,
ArrayList<String> fileNameListPure,
ArrayList<String> audioVideoUrlList, String newCreateFile, boolean isAudioActivity) {
super(context, resource, textViewResourceId, objects);
mContext = context;
mInflater = LayoutInflater.from(context);
mResource = resource;
mObjects = Arrays.asList(objects);
mFieldId = textViewResourceId;
this.newCreatedFile = newCreateFile;
this.audioVideoUrlList = audioVideoUrlList;
this.isAudioActivity = isAudioActivity;
this.fileNameListPure = fileNameListPure;

StrictMode.VmPolicy.Builder builder = new StrictMode.VmPolicy.Builder();
StrictMode.setVmPolicy(builder.build());
}


@NonNull
@Override
public Context getContext() {

return mContext;
}

@Override
public int getCount() {

return mObjects.size();

}

@Override
public String getItem(int position) {
return mObjects.get(position);
}


@Override
public int getPosition(String item) {
return mObjects.indexOf(item);
}

@NonNull
@Override
public Filter getFilter() {
if (mFilter == null) {
mFilter = new ArrayFilter();
}
return mFilter;
}

String TAG = "adapterWorldWide";

@Override
public long getItemId(int position) {

int itemID;

Log.i(TAG, "getItemId: 1 position: " + position);

// mOriginalValues will be null only if we haven't filtered yet:
if (mOriginalValues == null) {
itemID = position;
Log.i(TAG, "getItemId: 2 itemID: " + itemID + " text: " + mObjects.get(position));

} else {
itemID = mOriginalValues.indexOf(mObjects.get(position));
Log.i(TAG, "getItemId: 3 itemID: " + itemID + " text: " + mObjects.get(position));

}
return itemID;
// return super.getItemId(position);
}

@Override
public void notifyDataSetChanged() {
// Note: if you ever need to use notifyDatasetChanged() it might be a good idea to override this method as well:
// either this or: orig = dataSet;
// mOriginalValues = null;
super.notifyDataSetChanged();
}

private class ArrayFilter extends Filter {
@Override
protected FilterResults performFiltering(CharSequence prefix) {
FilterResults results = new FilterResults();

int j = 0;

if (mOriginalValues == null) {
synchronized (mLock) {
mOriginalValues = new ArrayList<>(mObjects);
}
}

if (prefix == null || prefix.length() == 0) {
mSearchText = "";
ArrayList<String> list;
synchronized (mLock) {
list = new ArrayList<>(mOriginalValues);

}
results.values = list;
results.count = list.size();
} else {
// String prefixString = prefix.toString().toLowerCase();
String prefixString = String.valueOf(prefix); // prefix.toString();

mSearchText = prefixString.toLowerCase(); // For Case Sensitive

ArrayList<String> values;

synchronized (mLock) {
values = new ArrayList<>(mOriginalValues);
// replace(values); // this is the system replace character to an array list elements

}

final int count = values.size();
final ArrayList<String> newValues = new ArrayList<>();

for (int i = 0; i < count; i++) {
final String value = values.get(i);
// final String valueText = value.toLowerCase();
final String valueText = value.toLowerCase(); // For Case Sensitive


// First match against the whole, non-splitted value
if (valueText.toLowerCase().startsWith(prefixString.toLowerCase()) || valueText.toLowerCase().contains(prefixString.toLowerCase())) {
newValues.add(value);
j++;
} else {
final String[] word = valueText.split(" ");
final int wordCount = word.length;

// Start at index 0, in case valueText starts with space(s)
for (int k = 0; k < wordCount; k++) {

if (word[k].toLowerCase().startsWith(prefixString.toLowerCase())) {
newValues.add(value);

break;
}
}
}
}

results.values = newValues;
results.count = newValues.size();
// if (filterListeners != null)
// filterListeners.filteringFinished(j);

}

return results;
}

@Override
protected void publishResults(CharSequence constraint, FilterResults results) {
//noinspection unchecked
mObjects = (List<String>) results.values;
if (results.count > 0) {
notifyDataSetChanged();
} else {
notifyDataSetInvalidated();
}

// if (filterListeners != null)
// filterListeners.filteringFinished(mObjects.size());

// setFilterListeners(filterListeners);
}
}


public static CharSequence highlight(String search, String originalText) {

int start = originalText.toLowerCase().indexOf(search.toLowerCase()); // For Case Sensitive
if (start < 0) {
// not found, nothing to to
return originalText;
} else {
// highlight each appearance in the original text
Spannable highlighted = new SpannableString(originalText);
while (start >= 0) {
int spanStart = Math.min(start, originalText.length());
int spanEnd = Math.min(start + search.length(), originalText.length());

ColorStateList blueColor = new ColorStateList(new int[][]{new int[]{}}, new int[]{Color.BLUE});
TextAppearanceSpan highlightSpan = new TextAppearanceSpan(null, Typeface.BOLD, -1, blueColor, null);
highlighted.setSpan(highlightSpan, spanStart, spanEnd, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);

start = originalText.indexOf(search, spanEnd);
}

return highlighted;
}
}


@SuppressLint("ClickableViewAccessibility")
@NonNull
@Override
public View getView(int position, View convertView, ViewGroup parent) {
View view;
TextView text;


if (convertView == null) {
view = mInflater.inflate(R.layout.sahitto_dropdown_layout, null);
} else {
view = convertView;
}

try {
if (mFieldId == 0) {
// If no custom field is assigned, assume the whole resource is a TextView
text = (TextView) view;
} else {
// Otherwise, find the TextView field within the layout
text = (TextView) view.findViewById(mFieldId);
}
} catch (ClassCastException e) {
Log.e("ArrayAdapter", "You must supply a resource ID for a TextView");
throw new IllegalStateException(
"ArrayAdapter requires the resource ID to be a TextView", e);
}

if (convertView != null) {
convertView.setOnTouchListener(new View.OnTouchListener() {
@Override
public boolean onTouch(View view, MotionEvent motionEvent) {
if (motionEvent.getAction() == MotionEvent.ACTION_DOWN) {
InputMethodManager inputMethodManager = (InputMethodManager) mContext.getSystemService(Activity.INPUT_METHOD_SERVICE);
inputMethodManager.hideSoftInputFromWindow(view.getApplicationWindowToken(), 0);
}
return false;
}
});
}


// HIGHLIGHT...

String fullText = getItem(position);
if (fullText != null) {
if (mSearchText != null && !mSearchText.isEmpty()) {

int startPos = fullText.toLowerCase(Locale.US).indexOf(mSearchText.toLowerCase(Locale.US));
// int startPos = fullText.indexOf(mSearchText);
int endPos = startPos + mSearchText.length();
if (startPos != -1) {

text.setText(highlight(mSearchText, fullText));

} else {
text.setText(fullText);
}
} else {
text.setText(fullText);

}

if (newCreatedFile != null && fullText.contains(". " + newCreatedFile)) {
text.setTextColor(Color.BLUE);
} else if (fullText.equalsIgnoreCase(newCreatedFile)) {
text.setTextColor(Color.BLUE);
}

System.out.println("newCreatedFile: " + newCreatedFile);
}





return view;
}




} 


void  createNewDb (){

androidx.appcompat.app.AlertDialog.Builder builder = new androidx.appcompat.app.AlertDialog.Builder(mContext);
builder.setTitle("নতুন দারস/ফাইল তৈরী করুন: ");

final View cl = getLayoutInflater().inflate(R.layout.create_new_dars_layout, null);

final EditText edtFileName = (EditText) cl.findViewById(R.id.edtFileName);
final Button btnCancel = (Button) cl.findViewById(R.id.btnCancel);
Button btnCreate = (Button) cl.findViewById(R.id.btnCreate);



final TextView txtError = (TextView) cl.findViewById(R.id.txtError);


builder.setView(cl);
final androidx.appcompat.app.AlertDialog dialog = builder.create();

btnCreate.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {

txtError.setText("");

String fileName = edtFileName.getText().toString().trim();

File dir = commonDir();
File subDir = new File(dir, FILE_TOIRY_FOLDER_NAME_STRING);
File alreadyloaded = new File(subDir + "/" + fileName + ".db");
File alreadyloaded2 = new File(subDir + "/" + fileName);

if (TextUtils.isEmpty(fileName)) {

edtFileName.setError("Empty");
} else {
edtFileName.setError(null);

if (alreadyloaded.exists() || alreadyloaded2.exists()) {

txtError.setText("একই নামের একটি ফাইল রয়েছে, অন্য নাম চেষ্টা করুন - ");

} else {

hideKeyboard(mContext, view);

createNewDarsDatabase(fileName);
txtError.setText("আলহামদুলিল্লাহ " + fileName + " নামক দারস / ফাইলটি তৈরী হয়েছে। OK বাটনে ক্লিক করুন। ");
btnCancel.setText("OK");

dialog.dismiss();
}
}

}
});

btnCancel.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
dialog.dismiss();
}
});



dialog.show();


}



public static void hideKeyboard(Context mContext, View view) {
InputMethodManager inputMethodManager = (InputMethodManager) mContext.getSystemService(Activity.INPUT_METHOD_SERVICE);
inputMethodManager.hideSoftInputFromWindow(view.getWindowToken(), 0);
inputMethodManager.hideSoftInputFromWindow(view.getApplicationWindowToken(), 0);

}



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, fileList, newCreatedFile);


fileListView.setAdapter(mainAdapter);


empty_text.setVisibility(View.GONE);
} else {

empty_text.setVisibility(View.VISIBLE);
}
}


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;

}

38. File Reading And Universal Context and etc.

 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);
}
}


}






Featured Post

Lesson 1 : Android Studio : DownLoad And Install and First App

বিসমিল্লাহির রাহমানির রাহীম Lesson 1 : Android Studio : DownLoad And Install  and First App এই লেসনটির ভিডিও ইউটিউবে দেখতে এখানে ক্ল...

Popular Posts