Reading files from a dir on the sdcard - java

I'm trying to read a dir and within this dir I have files for each contact. I want to to be able to read those contacts and then put them into the listview. I have tried but, I get a Java error and tried to research it more and found out when I try to do:
fileInputStream fi = fileInput(sdcard/contacts, 0);
fi.read();
//then the parse.
As I said I tried this and get an error which means I can't access a dir with the method above as that method is looking for app specific data.
My Code so far:
private void checkFosImprtCtacs() {
String FILENAME = "check";
String RND = "LewisR";
OutputStream out = null;
// TODO Auto-generated method stub
/*
* Check if the dir exists, if it does we'll load the contacts, if it
* doesn't the user will be presented with a dialog box and if they hit
* yes the contacts will be written to the SD card see the
* importcontacts theory file.
*/
File dir = new File(Environment.getExternalStorageDirectory()
+ "/chckcontacts");
if (dir.exists() && dir.isDirectory()) {
dir.exists();
dir.getPath().getBytes().toString(
//yes I KNOW THIS CODE IS WRONG, I JUST WANTED TO SHOW SOMETHING.
BufferedReader inputReader = null;
while (dir.getPath().getBytes() != null) {
}
} else {
if (dir.exists())
;
{
dir.mkdir();
// import contacts via dialog box.
new AlertDialog.Builder(this)
.setTitle("Import Contacts")
.setMessage("Do you want to import your contacts?")
.setPositiveButton("Yes",
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog,
int which) {
Cursor cursor = getContacts();
while (cursor.moveToNext()) {
String displayName = cursor.getString(cursor
.getColumnIndex(ContactsContract.Data.DISPLAY_NAME));
Log.e(displayName, displayName);
// create a File object for the
// parent directory
File Contacts = new File(
Environment
.getExternalStorageDirectory()
+ "/contacts");
// have the object build the
// directory structure, if needed.
Contacts.mkdirs();
// create a File object for the
// output file
File outputFile = new File(
Contacts,
displayName);
// now attach the OutputStream to
// the file object, instead of a
// String representation
try {
FileOutputStream fos = new FileOutputStream(
outputFile);
} catch (FileNotFoundException e) {
// TODO Auto-generated catch
// block
e.printStackTrace();
}
}
}
})
.setNegativeButton("No",
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog,
int which) {
// do nothing
}
}).show();
}
}
}
private Cursor getContacts() {
// TODO Auto-generated method stub
Uri uri = ContactsContract.Contacts.CONTENT_URI;
String[] projection = new String[] { ContactsContract.Contacts._ID,
ContactsContract.Contacts.DISPLAY_NAME };
String selection = ContactsContract.Contacts.IN_VISIBLE_GROUP + " = 1";
String[] selectionArgs = null;
String sortOrder = ContactsContract.Contacts.DISPLAY_NAME
+ " COLLATE LOCALIZED ASC";
return managedQuery(uri, projection, selection, selectionArgs,
sortOrder);
}

Related

How to get PDF File Path In Android 11 and 12

I tried much code for getting pdf path in android 11 or 12 but only working in android 10 or below devices.
Can you please help me? I share my code of lines
Intent calling like this
Intent intent = new Intent();
intent.setType("application/pdf");
statusAdapter = "pdf";
pos = position;
intent.setAction(Intent.ACTION_GET_CONTENT);
someActivityResultLauncher.launch(Intent.createChooser(intent, "Select PDF"));
someActivityResultLauncher = registerForActivityResult(
new ActivityResultContracts.StartActivityForResult(),
result -> {
if (result.getResultCode() == Activity.RESULT_OK) {
// There are no request codes
Intent data = result.getData();
if (data == null) {
//error
return;
}
try {
final Uri pdfUri= data.getData();
File pdfFile = new File(getPath(pdfUri));
long length = pdfFile.length();
length = length / 1024;
Toast.makeText(CreateSubEventActivity.this, "File Path : " + pdfFile.getPath() + ", File size : " + length + " KB", Toast.LENGTH_SHORT).show();
// uploadFile(imageFile);
} catch (Exception e) {
e.printStackTrace();
Toast.makeText(CreateSubEventActivity.this, "Something went wrong", Toast.LENGTH_LONG).show();
}
}
});
getPath calling like this
public String getPath(Uri uri) {
String[] projection = {MediaStore.Images.Media.DATA};
Cursor cursor = getContentResolver().query(uri, projection, null, null, null);
if (cursor == null) return null;
int column_index = cursor.getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
cursor.moveToFirst();
String s = cursor.getString(column_index);
cursor.close();
return s;
}
If you want to access a File or want a file path from a Uri that was returned from MediaStore, I have got a library that handles all the exceptions you might get. This includes all files on the disk, internal and removable disk. When selecting a File from Dropbox, for example, the File will be copied to your applications directory where you have full access, the copied file path will then be returned.
Let me share my experience to fix this stuff after so reading all.
Get input stream from URI
final Uri pdfUri= data.getData();
getContentResolver().openInputStream(pdfUri)
then do your stuff with InputStream, like I have uploaded pdf using okHttp
try {
RequestBody pdffile = new RequestBody() {
#Override public MediaType contentType() { return MediaType.parse("application/pdf"); }
#Override public void writeTo(BufferedSink sink) throws IOException {
Source source = null;
try {
source = Okio.source(inputStream);
sink.writeAll(source);
} finally {
Util.closeQuietly(source);
}
}
#Override
public long contentLength() {
try {
return inputStream.available();
} catch (IOException e) {
return 0;
}
}
};
RequestBody requestBody = new MultipartBody.Builder().setType(MultipartBody.FORM)
.addFormDataPart("file", "fname.pdf", pdffile)
//.addFormDataPart("Documents", value) // uncomment if you want to send Json along with file
.build();
Request request = new Request.Builder()
.url(serverURL)
.post(requestBody)
.build();
OkHttpClient client = new OkHttpClient.Builder().connectTimeout(10, TimeUnit.SECONDS).writeTimeout(180, TimeUnit.SECONDS).readTimeout(180, TimeUnit.SECONDS)
.addInterceptor(chain -> {
Request original = chain.request();
Request.Builder builder = original.newBuilder().method(original.method(), original.body());
builder.header("key", key);
return chain.proceed(builder.build());
})
.build();
client.newCall(request).enqueue(new Callback() {
#Override
public void onFailure(final Call call, final IOException e) {
// Handle the error
setIsLoading(false);
getNavigator().uploadIssue("Facing some issue to upload this file.");
}
#Override
public void onResponse(final Call call, final Response response) throws IOException {
setIsLoading(false);
if (!response.isSuccessful()) {
getNavigator().uploadIssue("Facing some issue to upload this file.");
}else {
// Upload successful
getNavigator().uploadedSucessfully();
}
}
});
return true;
} catch (Exception ex) {
// Handle the error
ex.printStackTrace();
}
This one helps in my case on Android 11 hope anyone gets this helpful
private String copyFile(Uri uri, String newDirName) {
Uri returnUri = uri;
Cursor returnCursor = this.getContentResolver().query(returnUri, new String[]{
OpenableColumns.DISPLAY_NAME, OpenableColumns.SIZE
}, null, null, null);
/*
* Get the column indexes of the data in the Cursor,
* * move to the first row in the Cursor, get the data,
* * and display it.
* */
int nameIndex = returnCursor.getColumnIndex(OpenableColumns.DISPLAY_NAME);
int sizeIndex = returnCursor.getColumnIndex(OpenableColumns.SIZE);
returnCursor.moveToFirst();
String name = (returnCursor.getString(nameIndex));
String size = (Long.toString(returnCursor.getLong(sizeIndex)));
File output;
if (!newDirName.equals("")) {
File dir = new File(this.getFilesDir() + "/" + newDirName);
if (!dir.exists()) {
dir.mkdir();
}
output = new File(this.getFilesDir() + "/" + newDirName + "/" + name);
} else {
output = new File(this.getFilesDir() + "/" + name);
}
try {
InputStream inputStream = this.getContentResolver().openInputStream(uri);
FileOutputStream outputStream = new FileOutputStream(output);
int read = 0;
int bufferSize = 1024;
final byte[] buffers = new byte[bufferSize];
while ((read = inputStream.read(buffers)) != -1) {
outputStream.write(buffers, 0, read);
}
inputStream.close();
outputStream.close();
} catch (Exception e) {
Log.e("Exception", e.getMessage());
}
return output.getPath();
}
String newPath = copyFileToInternalStorage(uri, getResources().getString(R.string.app_name));

Android 11: Send e-mail with automatically attached file

I want open and email app with already generated text, subject, recipient and attached file, it works with android sdk version 29 (android 10) and lower. However starting Android 11 there are restriction to writing file in external or internal storages, and there is also another restriction that is not allowed to attach file automatically from app file directory.
Previously I was copying from app storage to internal or external storage to attach file, any solutions?
done
android:requestLegacyExternalStorage="true"
public static void sendMail(Context context) throws IOException {
Context appContext = context.getApplicationContext();
File logFile = FileUtils.createFile(context.getFilesDir().getAbsolutePath(), "testFile.txt", "Test");
File logsDirectory = new File(FileUtils.getStorageDirectory(appContext), "files");
logsDirectory.mkdirs();
File destFile = new File(logsDirectory, "log.txt");
InputStream in = new FileInputStream(logFile);
boolean copied = FileUtils.copyToFile(in, destFile);
Uri logPath = Uri.fromFile(destFile);
Intent emailIntent = new Intent(Intent.ACTION_SENDTO);
emailIntent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
emailIntent.addFlags(Intent.FLAG_GRANT_WRITE_URI_PERMISSION);
// set the type to 'email'
emailIntent.setData(Uri.parse("mailto:"));
String[] to = {"support#test.com"};
String subject = "Test log";
String body =
"Hello";
emailIntent.putExtra(Intent.EXTRA_SUBJECT, subject);
emailIntent.putExtra(Intent.EXTRA_EMAIL, to);
emailIntent.putExtra(android.content.Intent.EXTRA_TEXT, body);
// the attachment
emailIntent.putExtra(Intent.EXTRA_STREAM, logPath);
context.startActivity(Intent.createChooser(emailIntent, "Send email..."));
}
public class FileUtils {
public static String getExtensionFromFileName(String fileName) {
if (fileName == null) return null;
String extension = null;
int i = fileName.lastIndexOf('.');
if (i > 0) {
extension = fileName.substring(i + 1);
}
return extension;
}
/**
* Copy data from a source stream to destFile. Return true if succeed, return false if failed.
*/
public static boolean copyToFile(InputStream inputStream, File destFile) {
if (inputStream == null || destFile == null) return false;
try {
try (OutputStream out = new FileOutputStream(destFile)) {
byte[] buffer = new byte[4096];
int bytesRead;
while ((bytesRead = inputStream.read(buffer)) >= 0) {
out.write(buffer, 0, bytesRead);
}
}
return true;
} catch (IOException e) {
Log.e("[File Utils]", "copyToFile exception: " + e);
}
return false;
}
public static String getStorageDirectory(Context mContext) {
String storageDir =
Environment.getExternalStorageDirectory().getAbsolutePath()
+ "/"
+ mContext.getString(R.string.app_name);
File file = new File(storageDir);
mContext.getExternalMediaDirs();
if (!file.isDirectory() || !file.exists()) {
}
return storageDir;
}
public static File createFile(String directory ,String fileName, String textToAttach)
{
File logFile = new File(directory + "/" + fileName);
if (!logFile.exists())
{
try
{
logFile.createNewFile();
}
catch (IOException e)
{
// TODO Auto-generated catch block
e.printStackTrace();
}
}
try
{
//BufferedWriter for performance, true to set append to file flag
BufferedWriter buf = new BufferedWriter(new FileWriter(logFile, true));
buf.append(textToAttach);
buf.newLine();
buf.close();
}
catch (IOException e)
{
// TODO Auto-generated catch block
e.printStackTrace();
}
return logFile;
}
}
I have done using FileProvider and selector, this is for multiple files
public static void sendMail(Context context) {
Context appContext = context.getApplicationContext();
final String authority = appContext.getPackageName() + ".FileProvider";
String[] to = {"test#test.com"};
String subject = "subject";
String body = "body";
ArrayList<File> logFiles = getLogFile(context);
if (logFiles.size() == 0) {
Toast.makeText(
context,
context.getString(R.string.toast_send_failed_no_file_found),
Toast.LENGTH_LONG)
.show();
return;
}
// has to be an ArrayList
ArrayList<Uri> logPaths = new ArrayList<>();
for (File file : logFiles) {
if (file.exists()) {
logPaths.add(FileProvider.getUriForFile(appContext, authority, file));
}
}
Intent emailSelectorIntent = new Intent(Intent.ACTION_SENDTO);
emailSelectorIntent.setDataAndType(Uri.parse("mailto:"), "plain/text");
final Intent emailIntent = new Intent(Intent.ACTION_SEND_MULTIPLE);
// emailIntent.setType("plain/text");
emailIntent.addFlags(
Intent.FLAG_GRANT_READ_URI_PERMISSION | Intent.FLAG_GRANT_WRITE_URI_PERMISSION);
emailIntent.putExtra(Intent.EXTRA_EMAIL, to);
emailIntent.putExtra(Intent.EXTRA_SUBJECT, subject);
emailIntent.putExtra(Intent.EXTRA_TEXT, body);
emailIntent.putParcelableArrayListExtra(Intent.EXTRA_STREAM, logPaths);
emailIntent.setSelector(emailSelectorIntent);
context.startActivity(Intent.createChooser(emailIntent, "Send Logs"));
}

can not display file content in text view

i am trying to select a file from the alert dialog and when i press OK i should display the content of the selected file in a text View by using the method display Content() that take the selected file read it and display the content line by line, but it does not display anything and i think the problem is with the call because i already use the method in another app and it work.
this is the code i have and how i call displayContent()
AlertDialog.Builder dialogBuilder = new AlertDialog.Builder(this);
dialogBuilder.setTitle("Single Choice List")
.setSingleChoiceItems(files, 0, new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
selectionID = which;
}
})
.setPositiveButton("Ok", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
//display the content of the selected file
displayContent();
Toast.makeText(View_Records.this, "You selected " + files[selectionID], Toast.LENGTH_SHORT).show();
}
})
this is the code for displayContent():
private void displayContent(){
try {
myFilesDirectory = new File(getFilesDir(), "MyFiles");
String fileName = files[selectionID] + ".txt";
File file = new File(myFilesDirectory, fileName);
String text;
FileInputStream fis = new FileInputStream(file);
InputStreamReader isr = new InputStreamReader(fis);
BufferedReader br = new BufferedReader(isr);
StringBuilder sb = new StringBuilder();
while ((text = br.readLine()) != null) {
sb.append(text).append("\n");
}
txtViewRecords.setText(sb.toString());
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
Replace
AlertDialog.Builder dialogBuilder = new AlertDialog.Builder(this);
dialogBuilder.setTitle("Single Choice List")
.setSingleChoiceItems(files, 0, new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
selectionID = which;
}
})
.setPositiveButton("Ok", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
//display the content of the selected file
displayContent();
Toast.makeText(View_Records.this, "You selected " + files[selectionID], Toast.LENGTH_SHORT).show();
}
})
with calling for another Activity (startActivityForResult()) with dialog style where you will pick a File and return it's path with Intent and then inside onActivityResult() you just use it to open File and then display it's content inside TextView.
Otherwise you can try to use create() first and add onDismissListener(). Like this:
AlertDialog.Builder dialogBuilder = new AlertDialog.Builder(this);
// do you things with builder
AlertDialog ad = builder.create();
ad.setOnDismissListener(new DialogInterface.OnDismissListener() {
#Override
public void onDismiss(DialogInterface dialogInterface) {
// here you open file, read content and put it inside TextView`
}
});
ad.show()
I'm not sure, but this should do the job with AlertDialog without creating Activity for this.
This is for getting all files from directory:
public static ArrayList<File> listFiles(File folder) {
if (folder.isDirectory()) {
ArrayList<File> tempList = new ArrayList<>();
File[] files = folder.listFiles();
for (File inFile : files) {
if (!inFile.isDirectory()) {
tempList.add(inFile);
}
}
/*Collections.sort(tempList, new Comparator<File>() { //you can sort by name
#Override
public int compare(File file1, File file2) {
return file1.getName().compareTo(file2.getName());
}
});*/
return tempList;
}
return null;
}
And you just send myFilesDirectory as a parameter.
Also you can skip checking if(!inFile.isDirectory()) if you are 100% sure that all files are files, not directories and return Array.
And then you just get your file using list.get(selectionID) or array[selectionID] depending what you are going to return from method.
Also method doesn't need to be static. I've got it static for my project needs.

How to create a simple local backup and restore for an app?

I Have five sqlite databases and I want user to be able to have local backup in his phone and he can restore the backup file .
I don't know how to create these backups and restore them programatcally .
I used A github repo but it did not work at all,
I need your help to create this process of backup and restore .
Thank for your attention
In your Activity make backup and restore button and define local database variable like,
private MainDatabase localBackup = new MainDatabase(this);
Then perform backup and restore operation when it's just click
#Override
public void onClick(View v) {
final MainDatabase db = new MainDatabase(getApplicationContext());
switch (v.getId()) {
case R.id.tvBackUp:
String outFileName = Environment.getExternalStorageDirectory() +
File.separator + getResources().getString(R.string.app_name) + File.separator;
localBackup.performBackup(db, outFileName);
break;
case R.id.tvRestore:
File folder = new File(Environment.getExternalStorageDirectory() + File.separator + getApplicationContext().getResources().getString(R.string.app_name));
if (folder.exists()) {
final File[] files = folder.listFiles();
if (files.length == 0) {
Toast.makeText(this, "No any Backup", Toast.LENGTH_SHORT).show();
} else {
localBackup.performRestore(db);
}
}
break;
}
}
Make a method for backup in your database file
public void performBackup(final MainDatabase db, final String outFileName) {
File folder = new File(Environment.getExternalStorageDirectory() + File.separator
+ mContext.getResources().getString(R.string.app_name));
boolean success = true;
if (!folder.exists())
success = folder.mkdirs();
if (success) {
final Dialog dialog = new Dialog(mContext);
dialog.setContentView(R.layout.backup_dialog);
dialog.getWindow().getAttributes().windowAnimations =
R.style.PauseDialogAnimation;
dialog.getWindow().setBackgroundDrawableResource(android.R.color.transparent);
dialog.show();
Button btnSave = dialog.findViewById(R.id.btnSave);
Button btnCancel = dialog.findViewById(R.id.btnCancel);
EditText etName = dialog.findViewById(R.id.etName);
etName.setInputType(InputType.TYPE_CLASS_TEXT);
btnSave.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
String m_Text = etName.getText().toString();
String out = outFileName + m_Text + ".db";
db.backup(out);
dialog.dismiss();
}
});
btnCancel.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
dialog.dismiss();
}
});
} else
Toast.makeText(mContext, "Unable to create directory. Retry",
Toast.LENGTH_SHORT).show();
}
public void backup(String outFileName) {
//database path
final String inFileName = mContext.getDatabasePath(DATABASE_NAME).toString();
try {
File dbFile = new File(inFileName);
FileInputStream fis = new FileInputStream(dbFile);
// Open the empty db as the output stream
OutputStream output = new FileOutputStream(outFileName);
// Transfer bytes from the input file to the output file
byte[] buffer = new byte[1024];
int length;
while ((length = fis.read(buffer)) > 0) {
output.write(buffer, 0, length);
}
// Close the streams
output.flush();
output.close();
fis.close();
Toast.makeText(mContext, "Backup Completed", Toast.LENGTH_SHORT).show();
} catch (Exception e) {
Toast.makeText(mContext, "Unable to backup database. Retry",
Toast.LENGTH_SHORT).show();
e.printStackTrace();
}
}
As well as for restore do this thing,
ask to the user what backup to restore
public void performRestore(final MainDatabase db) {
File folder = new File(Environment.getExternalStorageDirectory() + File.separator
+ mContext.getResources().getString(R.string.app_name));
if (folder.exists()) {
final File[] files = folder.listFiles();
final ArrayAdapter<String> arrayAdapter = new ArrayAdapter<>(mContext,
android.R.layout.select_dialog_item);
for (File file : files)
arrayAdapter.add(file.getName());
AlertDialog.Builder builderSingle = new AlertDialog.Builder(mContext);
builderSingle.setTitle("Select & Restore ");
builderSingle.setNegativeButton("cancle", (dialog, which) ->
dialog.dismiss());
builderSingle.setAdapter(arrayAdapter, (dialog, which) -> {
try {
db.importDB(files[which].getPath());
} catch (Exception e) {
Toast.makeText(mContext, "Unable to restore. Retry",
Toast.LENGTH_SHORT).show();
}
});
builderSingle.show();
} else
Toast.makeText(mContext, "Backup folder not present.\nDo a backup before a
restore!", Toast.LENGTH_SHORT).show();
}
public void importDB(String inFileName) {
final String outFileName = mContext.getDatabasePath(DATABASE_NAME).toString();
try {
File dbFile = new File(inFileName);
FileInputStream fis = new FileInputStream(dbFile);
// Open the empty db as the output stream
OutputStream output = new FileOutputStream(outFileName);
// Transfer bytes from the input file to the output file
byte[] buffer = new byte[1024];
int length;
while ((length = fis.read(buffer)) > 0) {
output.write(buffer, 0, length);
}
// Close the streams
output.flush();
output.close();
fis.close();
Toast.makeText(mContext, "Restore Completed", Toast.LENGTH_SHORT).show();
} catch (Exception e) {
Toast.makeText(mContext, "Unable to import database. Retry",
Toast.LENGTH_SHORT).show();
e.printStackTrace();
}
}
Android already supports system automatic backups if you have android:allowBackup="true" at your manifest. If it isn't enough and you want to manage backups manually between app reinstalls than you have to copy database from context.getDatabasePath("<your-database-name>") to external storage somewhere, and then copy it back when you want

FileNotFoundException When Uploading File (Non-image) To App

I've been trying to allow the user to upload a file (PDF) to my app for eventual upload to my Parse server, but every time I attempt to create a filestream/buffered input stream, I get a FileNotFoundException, claiming that there is 'no such file or directory'. One of my logged file paths appears below:
/storage/emulated/0/Android/data/com.parse.starter/files/Eloquent_JavaScript.pdf
I have no idea as to why it's giving me this bad path. This is my MainActivity (my only activity). I understand that not all files will be stored internally on the phone -- that's why I used certain support methods for my onActivityResult class. I've been struggling to isolate my issue because I haven't been working with files for very long, so things are still relatively new to me. Again, I apologize for all the code. Any assistance is appreciated.
Intent Method
public void getFile()
{
Intent intent = new Intent();
intent.setType("application/pdf");
intent.setAction(Intent.ACTION_GET_CONTENT);
startActivityForResult(intent, 1);
}
onActivityResult Method
public void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
filename = null;
if (requestCode == 1) {
if (resultCode == RESULT_OK) {
try {
Uri uri = data.getData();
if (1 > 1) {
Toast.makeText(this,"The selected file is too large. Select a new file with size less than 2mb",Toast.LENGTH_LONG).show();
} else {
String mimeType = getContentResolver().getType(uri);
if (mimeType == null) {
String path = getPath(this, uri);
if (path == null) {
filename = uri.toString().substring(uri.toString().lastIndexOf("/") + 1);
} else {
File file = new File(path);
filename = file.getName();
}
} else {
Uri returnUri = data.getData();
Cursor returnCursor = getContentResolver().query(returnUri, null, null, null, null);
int nameIndex = returnCursor.getColumnIndex(OpenableColumns.DISPLAY_NAME);
int sizeIndex = returnCursor.getColumnIndex(OpenableColumns.SIZE);
returnCursor.moveToFirst();
filename = returnCursor.getString(nameIndex);
String size = Long.toString(returnCursor.getLong(sizeIndex));
}
File fileSave = getExternalFilesDir(null);
String sourcePath = getExternalFilesDir(null) + "/" + filename;
sourcePath = sourcePath.substring(sourcePath.lastIndexOf("data") + 4, sourcePath.length());
Log.i("PATH", sourcePath);
Log.i("NAME", filename);
// create byte array
File file = new File(sourcePath);
int size = (int) file.length();
byte[] bytes = new byte[size];
try {
BufferedInputStream buf = new BufferedInputStream(new FileInputStream(file));
buf.read(bytes, 0, bytes.length);
buf.close();
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
// byte array created
}
} catch (Exception e) {
e.printStackTrace();
}
}
}
}
Here Are Some Support Methods for the onActivityResult method
public static String getDataColumn(Context context, Uri uri, String selection, String[] selectionArgs) {
Cursor cursor = null;
final String column = "_data";
final String[] projection = { column };
try {
cursor = context.getContentResolver().query(uri, projection, selection, selectionArgs, null);
if (cursor != null && cursor.moveToFirst()) {
final int index = cursor.getColumnIndexOrThrow(column);
return cursor.getString(index);
}
} finally {
if (cursor != null)
cursor.close();
}
return null;
}
public static boolean isExternalStorageDocument(Uri uri) {
return "com.android.externalstorage.documents".equals(uri.getAuthority());
}
/**
* #param uri The Uri to check.
* #return Whether the Uri authority is DownloadsProvider.
*/
public static boolean isDownloadsDocument(Uri uri) {
return "com.android.providers.downloads.documents".equals(uri.getAuthority());
}
/**
* #param uri The Uri to check.
* #return Whether the Uri authority is MediaProvider.
*/
public static boolean isMediaDocument(Uri uri) {
return "com.android.providers.media.documents".equals(uri.getAuthority());
}
/**
* #param uri The Uri to check.
* #return Whether the Uri authority is Google Photos.
*/
public static boolean isGooglePhotosUri(Uri uri) {
return "com.google.android.apps.photos.content".equals(uri.getAuthority());
}
All apps (root or not) have a default data directory, which is /data/data/<package_name>. By default, the apps databases, settings, and all other data go here. If an app expects huge amounts of data to be stored, or for other reasons wants to "be nice to internal storage", there's a corresponding directory on the SDCard (Android/data/<package_name>).
In your code, at this line
String sourcePath = getExternalFilesDir(null).toString() + "/" + filename;
filename is the actual path. getExternalFilesDir(null).toString() appends /storage/emulated/0/ to the start of sourcePath. Not all files are from Internal Storage. So remove it.
String sourcePath = filename;

Categories