The only way to get and visualize the data table of my database inside external devices is by atribution of privilege of superuser privilege in external device? Don't exist another way that allow visualize the data tables as in emulator?
I make this question because this way of superuser privilege not inspire me security.
Thanks for your attention (PS: Sorry by mistakes, but english is not my mother language :) )
You can add functionality to export the database file from the internal read-only app storage to the SD-Card by simply letting your app copy the file.
Then use whatever ways you have to get it from there. Works on any device and no root required.
private void exportDb() {
File database = getDatabasePath("myDb.db");
File sdCard = new File(Environment.getExternalStorageDirectory(), "myDb.db");
if (copy(database, sdCard)) {
Toast.makeText(this, "Get db from " + sdCard.getPath(), Toast.LENGTH_LONG).show();
} else {
Toast.makeText(this, "Copying the db failed", Toast.LENGTH_LONG).show();
}
}
private static boolean copy(File src, File target) {
// try creating necessary directories
target.mkdirs();
boolean success = false;
FileOutputStream out = null;
FileInputStream in = null;
try {
out = new FileOutputStream(target);
in = new FileInputStream(src);
byte[] buffer = new byte[8 * 1024];
int read;
while ((read = in.read(buffer)) != -1) {
out.write(buffer, 0, read);
}
success = true;
} catch (FileNotFoundException e) {
// maybe log
} catch (IOException e) {
// maybe log
} finally {
close(in);
close(out);
}
if (!success) {
// try to delete failed attempts
target.delete();
}
return success;
}
private static void close(final Closeable closeMe) {
if (closeMe != null)
try {
closeMe.close();
} catch (IOException ignored) {
// ignored
}
}
Related
I'm working on an app where I'm downloading a PDF file, saving it to internal storage and then opening that file in other app using FileProvider.
Note: It may be a duplicate question, I've gone through most of the questions on StackOverflow, but still didn't find the solution.
The file is getting downloaded fine but when I'm opening it, it is empty.
The downlaoded file is 30 kb and it has 5 pages but all are empty.
Initially, I thought it is empty because the other app doesn't have permission to open the file, but I did another thing to check whether it is a permission issue. I've saved the file to external storage, still, it was empty. So, it means it is not a permission issue.
Please Note:
Along with pdf file, there is some .xls file as well and when I'm opening those in excel android app, it says cannot open the file. This indicates, that there is some issue while writing the byte stream.
Retrofit Interface.java
#GET(ApiConstants.END_POINT_DOWNLOAD_DOCUMENT)
#Streaming
Call<ResponseBody> downloadDocument(#Query("bucket") String bucket, #Query("filename") String fileName);
Code to Download the file: Here I'm checking if a file is already there, then return the file, otherwise download the file.
public LiveData<Resource<File>> openOrDownloadFile(String bucket, String fileName) {
MutableLiveData<Resource<File>> documentLiveData = new MutableLiveData<>();
documentLiveData.postValue(Resource.loading(null));
Context context = MyApp.getInstance();
final File file = new File(context.getFilesDir(), fileName);
if (file.exists()) {
documentLiveData.postValue(Resource.success(file));
} else {
Call<ResponseBody> call = apiService.downloadDocument(bucket, fileName);
call.enqueue(new Callback<ResponseBody>() {
#Override
public void onResponse(Call<ResponseBody> call, Response<ResponseBody> response) {
if (response.isSuccessful()) {
appExecutors.diskIO().execute(new Runnable() {
#Override
public void run() {
try {
InputStream inputStream = null;
OutputStream outputStream = null;
try {
byte[] fileReader = new byte[4096];
inputStream = response.body().byteStream();
outputStream = new FileOutputStream(file);
while (true) {
int read = inputStream.read(fileReader);
if (read == -1) {
break;
}
outputStream.write(fileReader, 0, read);
}
documentLiveData.postValue(Resource.success(file));
outputStream.flush();
} catch (IOException e) {
documentLiveData.postValue(Resource.error("Error: Unable to save file/n"+e.getLocalizedMessage(), null));
} finally {
if (inputStream != null) {
inputStream.close();
}
if (outputStream != null) {
outputStream.close();
}
}
} catch (IOException e) {
Log.e(AppConstants.TAG, e.getMessage(), e);
documentLiveData.postValue(Resource.error("Error: Unable to save file/n"+e.getLocalizedMessage(), null));
}
}
});
} else {
documentLiveData.postValue(Resource.error("Unable to download file", null));
}
}
#Override
public void onFailure(Call<ResponseBody> call, Throwable t) {
documentLiveData.postValue(Resource.error(t.getLocalizedMessage(), null));
}
});
}
return documentLiveData;
}
Fragment Code
private void onItemClickListener(Document document) {
mDocumentsViewModel.openORDownloadFile(document.getType(), document.getName()).observe(this, new Observer<Resource<File>>() {
#Override
public void onChanged(#Nullable Resource<File> fileResource) {
binding.setResource(fileResource);
if (fileResource.status == Status.SUCCESS) {
openFile(fileResource.data);
}
}
});
}
void openFile(File file) {
Intent intent = new Intent(Intent.ACTION_VIEW);
Uri uri = FileProvider.getUriForFile(getContext(), BuildConfig.APPLICATION_ID, file);
intent.setDataAndType(uri, mDocumentsViewModel.getMimeType(file.getAbsolutePath()));
intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
PackageManager pm = getActivity().getPackageManager();
if (intent.resolveActivity(pm) != null) {
startActivity(intent);
} else {
Toast.makeText(getActivity(), "This file cannot be opened on this device. Please download some compatible app from play store", Toast.LENGTH_SHORT).show();
}
}
Following are the versions :
ext.retrofit_version = "2.4.0"
ext.okhttp_version = "3.8.0"
I'm struggling with this issue, it'll be a great help if you can point out the issue. Thank you.
Update: The problem was with the backend APIs. My code was correct. Once they've fixed the problem at there side, it started working at my side without any changes.
My app allows user to export its data to other users or just to save as backup.
The import/export is working FINE
In order to let the user have a sample data when it first installs my app I want to package some default data. I created the sample data, tested IS WORKING FINE, then i packaged it in assets folder and load it when user runs the app for first time.
But i'm getting file not found exception
HERE GOES THE CODE:
private List<Giveaway> loadJsonData(Uri data, User user) {
List<Giveaway> result = null;
try {
InputStream is = this.getContentResolver().openInputStream(data);
Gson parser = new GsonBuilder().setDateFormat("dd/MM/yy").setFieldNamingPolicy(FieldNamingPolicy.LOWER_CASE_WITH_UNDERSCORES).setLongSerializationPolicy(LongSerializationPolicy.DEFAULT).setLenient().excludeFieldsWithModifiers(Modifier.FINAL, Modifier.STATIC, Modifier.TRANSIENT).create();
Set<Giveaway> temp = new HashSet<Giveaway>(50);
temp.addAll((Collection<? extends Giveaway>) parser.fromJson(new InputStreamReader(is), TypeToken.getParameterized(List.class, Giveaway.class).getType()));
result = new ArrayList<Giveaway>(temp);
} catch (FileNotFoundException e) {
e.printStackTrace();
result = new ArrayList<Giveaway>(1);
}
return result;
}
and I call it using:
loadJsonData(Uri.parse("file:///android_asset/giveaway_export.json"), sampleUser);
file:///android_asset works for WebView and pretty much nothing else. Use AssetManager to work with assets — you get one of these by calling getAssets() on a Context, such as your Activity.
Use AssetManager this is an example:
AssetManager assetManager = getAssets();
InputStream is = null;
try {
is = assetManager.open("giveaway_export.json");
} catch (IOException e) {
e.printStackTrace();
}
so you have to change your method:
private List<Giveaway> loadJsonData(Uri data, User user) {
List<Giveaway> result = null;
try {
//InputStream is = this.getContentResolver().openInputStream(data);
AssetManager assetManager = getAssets();
InputStream is = null;
try {
is = assetManager.open("giveaway_export.json");
} catch (IOException e) {
e.printStackTrace();
}
Gson parser = new GsonBuilder().setDateFormat("dd/MM/yy").setFieldNamingPolicy(FieldNamingPolicy.LOWER_CASE_WITH_UNDERSCORES).setLongSerializationPolicy(LongSerializationPolicy.DEFAULT).setLenient().excludeFieldsWithModifiers(Modifier.FINAL, Modifier.STATIC, Modifier.TRANSIENT).create();
Set<Giveaway> temp = new HashSet<Giveaway>(50);
temp.addAll((Collection<? extends Giveaway>) parser.fromJson(new InputStreamReader(is), TypeToken.getParameterized(List.class, Giveaway.class).getType()));
result = new ArrayList<Giveaway>(temp);
} catch (FileNotFoundException e) {
e.printStackTrace();
result = new ArrayList<Giveaway>(1);
}
return result;
}
Remember if you are using android 6.0+ you need to declared the permission:
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>
and require manually permissions:
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M){
//Verify permission for Android 6.0+
checkExternalStoragePermission();
}
use this method:
private void checkExternalStoragePermission() {
int permissionCheck = ContextCompat.checkSelfPermission(
this, Manifest.permission.WRITE_EXTERNAL_STORAGE);
if (permissionCheck != PackageManager.PERMISSION_GRANTED) {
Log.i("Message", "You require permissions!.");
ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE}, 225);
} else {
Log.i("Message", "you have already permissions!");
}
}
I am developing an application in which i have to get all available storage directories on device, like file directory, on Board storage, external sdCard storage (Removable)
but the storage path varies device to device such as
i have Samsung Galaxy tab 7 with Froyo2.2 that has these three storage
1: Files Directory
/mnt/.lfs,
2: OnBoard Storage Directory
/mnt/sdcard,
3: External sdCard Removeable Storage Directory
/mnt/sdcard/external_sd
i am getting these using this code
public static String[] getDirectories()
{
Log.d(TAG, "getStorageDirectories");
File tempFile;
String[] directories = null;
String[] splits;
ArrayList<String> arrayList = new ArrayList<String>();
BufferedReader bufferedReader = null;
String lineRead;
try
{
arrayList.clear(); // redundant, but what the hey
bufferedReader = new BufferedReader(new FileReader("/proc/mounts"));
while ((lineRead = bufferedReader.readLine()) != null)
{
Log.d(TAG, "lineRead: " + lineRead);
splits = lineRead.split(" ");
// System external storage
if (splits[1].equals(Environment.getExternalStorageDirectory().getPath()))
{
arrayList.add(splits[1]);
Log.d(TAG, "gesd split 1: " + splits[1]);
continue;
}
// skip if not external storage device
if (!splits[0].contains("/dev/block/"))
{
continue;
}
// skip if mtdblock device
if (splits[0].contains("/dev/block/mtdblock"))
{
continue;
}
// skip if not in /mnt node
if (!splits[1].contains("/mnt"))
{
continue;
}
// skip these names
if (splits[1].contains("/secure"))
{
continue;
}
if (splits[1].contains("/mnt/asec"))
{
continue;
}
// Eliminate if not a directory or fully accessible
tempFile = new File(splits[1]);
if (!tempFile.exists())
{
continue;
}
if (!tempFile.isDirectory())
{
continue;
}
if (!tempFile.canRead())
{
continue;
}
if (!tempFile.canWrite())
{
continue;
}
// Met all the criteria, assume sdcard
arrayList.add(splits[1]);
}
}
catch (FileNotFoundException e)
{
}
catch (IOException e)
{
}
finally
{
if (bufferedReader != null)
{
try
{
bufferedReader.close();
}
catch (IOException e)
{
}
}
}
// Send list back to caller
if (arrayList.size() == 0)
{
arrayList.add("sdcard not found");
}
directories = new String[arrayList.size()];
for (int i = 0; i < arrayList.size(); i++)
{
directories[i] = arrayList.get(i);
}
return directories;
}
but when i run this code on Nexus7 4.2.2 Jelly Beans it returns only one path at runtime how may i know what path is this
and this storage paths varies among different devices
i have to identify onBoard storage if available user can select device storage
if external sdcard available then user can select onBoard or external storage
I am looking for a way to detect and access removable sd cards on a variety of Android devices (Samsung, Motorola, LG, Sony, HTC).
I also need to be compatible with 2.2 so Environment.isExternalStorageRemovable() is unavailable for me.
Motorola has its own library, and for Samsung I can detect the existence of /external_sd/
I have no clue for the rest of them. For example, I have seen a /_ExternalSD/ on some LG's but it the directory remains even when the SD is removed.
A bonus question: will the ACTION_MEDIA_MOUNTED intent be broadcast for any of them
Any hint on this would be very helpful.
Here's a class I use to find all sdcards on a device; built in and removable. I've been using it on Ice Cream Sandwich, but it should work at 2x levels.
public class GetRemovableDevice {
private final static String TAG = "GetRemoveableDevice";
public GetRemovableDevice() {
}
public static String[] getDirectories() {
MyLog.d(TAG, "getStorageDirectories");
File tempFile;
String[] directories = null;
String[] splits;
ArrayList<String> arrayList = new ArrayList<String>();
BufferedReader bufferedReader = null;
String lineRead;
try {
arrayList.clear(); // redundant, but what the hey
bufferedReader = new BufferedReader(new FileReader("/proc/mounts"));
while ((lineRead = bufferedReader.readLine()) != null) {
MyLog.d(TAG, "lineRead: " + lineRead);
splits = lineRead.split(" ");
// System external storage
if (splits[1].equals(Environment.getExternalStorageDirectory()
.getPath())) {
arrayList.add(splits[1]);
MyLog.d(TAG, "gesd split 1: " + splits[1]);
continue;
}
// skip if not external storage device
if (!splits[0].contains("/dev/block/")) {
continue;
}
// skip if mtdblock device
if (splits[0].contains("/dev/block/mtdblock")) {
continue;
}
// skip if not in /mnt node
if (!splits[1].contains("/mnt")) {
continue;
}
// skip these names
if (splits[1].contains("/secure")) {
continue;
}
if (splits[1].contains("/mnt/asec")) {
continue;
}
// Eliminate if not a directory or fully accessible
tempFile = new File(splits[1]);
if (!tempFile.exists()) {
continue;
}
if (!tempFile.isDirectory()) {
continue;
}
if (!tempFile.canRead()) {
continue;
}
if (!tempFile.canWrite()) {
continue;
}
// Met all the criteria, assume sdcard
arrayList.add(splits[1]);
}
} catch (FileNotFoundException e) {
} catch (IOException e) {
} finally {
if (bufferedReader != null) {
try {
bufferedReader.close();
} catch (IOException e) {
}
}
}
// Send list back to caller
if (arrayList.size() == 0) {
arrayList.add("sdcard not found");
}
directories = new String[arrayList.size()];
for (int i = 0; i < arrayList.size(); i++) {
directories[i] = arrayList.get(i);
}
return directories;
}
}
The MyLog.d is a trace class that expands Log.d - it can be dropped.
The class reads /proc/mounts/ and:
checks to see if the path name is the internal sdcard directory
checks to see if its a block device
skips mtdblock devices
skips anything that is not mounted
skips secure and asec directories
makes sure it exists, is a directory, and read/write accessible
If all this is matched, it assumes that you have an sdcard and adds the path to the array list. It returns a string array of path names.
To call the getDirectories function, code something similar to:
String[] sdcardDirectories = GetRemoveableDevice.getDirectories();
The paths returned can be used to create a user selection list, scan for a file, or whatever.
Finally, here's two lines of MyLog.d from an emulator test (second line is the emulator sdcard):
09-19 15:57:12.511: D/GetRemoveableDevice(651): lineRead: /dev/block/mtdblock2 /cache yaffs2 rw,nosuid,nodev 0 0
09-19 15:57:12.511: D/GetRemoveableDevice(651): lineRead: /dev/block/vold/179:0 /mnt/sdcard vfat rw,dirsync,nosuid,nodev,noexec,uid=1000,gid=1015,fmask=0702,dmask=0702,allow_utime=0020,codepage=cp437,iocharset=iso8859-1,shortname=mixed,utf8,errors=remount-ro 0 0
Based on Howards class I made some modifications to make it work on the Galaxy S3.
Environment.getExternalStorageDirectory() returns internal storage on the S3.
Removable storage is not necessarily mounted under /mnt
Removable media must have vfat filesystem
_
public static String getDirectory() {
Log.d(TAG, "getStorageDirectories");
File tempFile;
String[] splits;
ArrayList<String> arrayList = new ArrayList<String>();
BufferedReader bufferedReader = null;
String lineRead;
try {
arrayList.clear(); // redundant, but what the hey
bufferedReader = new BufferedReader(new FileReader("/proc/mounts"));
while ((lineRead = bufferedReader.readLine()) != null) {
Log.d(TAG, "lineRead: " + lineRead);
splits = lineRead.split(" ");
// skip if not external storage device
if (!splits[0].contains("/dev/block/")) {
continue;
}
// skip if mtdblock device
if (splits[0].contains("/dev/block/mtdblock")) {
continue;
}
// skip if not in vfat node
if (!splits[2].contains("vfat")) {
continue;
}
// skip these names
if (splits[1].contains("/secure")) {
continue;
}
if (splits[1].contains("/mnt/asec")) {
continue;
}
// Eliminate if not a directory or fully accessible
tempFile = new File(splits[1]);
if (!tempFile.exists()) {
continue;
}
if (!tempFile.isDirectory()) {
continue;
}
if (!tempFile.canRead()) {
continue;
}
if (!tempFile.canWrite()) {
continue;
}
// Met all the criteria, assume sdcard
return splits[1];
}
} catch (FileNotFoundException e) {
} catch (IOException e) {
} finally {
if (bufferedReader != null) {
try {
bufferedReader.close();
} catch (IOException e) {
}
}
}
return null;
}
Based on Howards class I modified the class further on noticing that all of the external removable storage on several phones and tablets that I could find were mounted using vold, the volume mounting daemon.
// skip if not external storage device
if (!splits[0].contains("vold")) {
continue;
}
if (splits[1].contains("/mnt/asec")) {
continue;
}
// Eliminate if not a directory or fully accessible
tempFile = new File(splits[1]);
if (!tempFile.exists()) {
continue;
}
if (!tempFile.isDirectory()) {
continue;
}
if (!tempFile.canRead()) {
continue;
}
if (!tempFile.canWrite()) {
continue;
}
// Met all the criteria, assume sdcard
arrayList.add(splits[1]);
These capabilities are available in all Android versions:
To obtain the application's folder on the external storage, call Context.getExternalFilesDir.
Keep in mind that your app needs explicit permission to access external storage, and that you should check if it is available via Environment.getExternalStorageState
And yes, ACTION_MEDIA_MOUNTED will be broadcast whenever removable media becomes accessible (You should also listen for ACTION_MEDIA_EJECT and ACTION_MEDIA_REMOVED)
This is the method I created and am using. This has worked on Samsung Galaxy S4, Samsung Galaxy Note 3 and Sony Xperia Z2.
private static String[] getRemovableStoragePaths() {
String[] directories;
String[] splits;
ArrayList<String> pathList = new ArrayList<String>();
BufferedReader bufferedReader = null;
String lineRead;
try {
bufferedReader = new BufferedReader(new FileReader("/proc/mounts"));
while ((lineRead = bufferedReader.readLine()) != null) {
Log.d(TAG, "lineRead: " + lineRead);
splits = lineRead.split(" ");
Log.d(TAG, "Testing path: " + splits[1]);
if (!splits[1].contains("/storage")) {
continue;
}
if (splits[1].contains("/emulated")) {
// emulated indicates an internal storage location, so skip it.
continue;
}
// Eliminate if not a directory or fully accessible
Log.d(TAG, "Path found: " + splits[1]);
// Met all the criteria, assume sdcard
pathList.add(splits[1]);
}
} catch (FileNotFoundException e) {
} catch (IOException e) {
} finally {
if (bufferedReader != null) {
try {
bufferedReader.close();
} catch (IOException e) {
}
}
}
// Send list back to caller
if (pathList.size() == 0) {
pathList.add("sdcard not found");
} else {
Log.d(TAG, "Found potential removable storage locations: " + pathList);
}
directories = new String[pathList.size()];
for (int i = 0; i < pathList.size(); i++) {
directories[i] = pathList.get(i);
}
return directories;
}
I'm currently doing some debugging and I was wondering is it possible to display the contents of the phones SQLite database via the SDK? I know it's possible to do this via queries phone side. But I was just curious could you do it via the SDK?
Export the database to the sdcard file, and each time you have to copy over to your computer, and open by some SQLite Manager tool, I use Firefox's plugin for this. There simple I don't have to reopen the database again and again, just hit the refresh button and the tables will get updated.
You can use Eclipse's File Manager to get a file from the device, from sdcard while it's in usb mode. You have this option only as you cannot get the device into Eclipse and mount the SD Card in the same time. You have to use Eclipse.
Here is the code to export the database to SDCard
/*
* Task to backup the database to the SDCard
*/
public static class ExportDatabaseFileTask extends AsyncTask<String, Void, Boolean> {
private Context ctx;
/**
*
*/
public ExportDatabaseFileTask(Context ctx) {
super();
this.ctx=ctx;
}
// automatically done on worker thread (separate from UI thread)
protected Boolean doInBackground(final String... args) {
File dbFile =
new File(Environment.getDataDirectory() + "/data/[com.your.pkg]/databases/[pkg]");
File exportDir = new File(Environment.getExternalStorageDirectory(), "");
if (!exportDir.exists()) {
exportDir.mkdirs();
}
File file = new File(exportDir, dbFile.getName());
try {
file.createNewFile();
this.copyFile(dbFile, file);
return true;
} catch (IOException e) {
Log.e("birthdroid", e.getMessage(), e);
return false;
}
}
// can use UI thread here
protected void onPostExecute(final Boolean success) {
if (success) {
Toast.makeText(ctx, "Export successful!", Toast.LENGTH_SHORT).show();
} else {
Toast.makeText(ctx, "Export failed", Toast.LENGTH_SHORT).show();
}
}
void copyFile(File src, File dst) throws IOException {
FileChannel inChannel = new FileInputStream(src).getChannel();
FileChannel outChannel = new FileOutputStream(dst).getChannel();
try {
inChannel.transferTo(0, inChannel.size(), outChannel);
} finally {
if (inChannel != null)
inChannel.close();
if (outChannel != null)
outChannel.close();
}
}
}
On a cursor you always can call:
DatabaseUtils.dumpCursorToString(cur);
to get a raw String representation of the cursor