How to copy file from SDCARD to /data/data/... - Java for Android App Development

Hello everyone, I developed an app which utilizes database.
I implemented a method for backing up the database from /data/data/package_name/databases to the SDCARD wiith the following code
Code:
try {
File path_to_sd = Environment.getExternalStorageDirectory();
File path_to_data = Environment.getDataDirectory();
String current_db_path = "//data//" + getPackageName() + "//databases//";
String path_to_database = path_to_data.getAbsolutePath() + current_db_path;
String backup_name = "backup.db";
File current_db = new File(path_to_database, database_name);
File db_backup = new File(path_to_sd, backup_name);
FileChannel src = new FileInputStream(current_db).getChannel();
FileChannel dst = new FileOutputStream(db_backup).getChannel();
if(!db_backup.exists()){
try {
db_backup.createNewFile();
dst.transferFrom(src, 0, src.size());
src.close();
dst.close();
Toast.makeText(getApplicationContext(), "Exporting database done successfully!", Toast.LENGTH_LONG).show();
} catch (IOException e) {
e.printStackTrace();
}
}
} catch (Exception e) {
e.printStackTrace();
}
the thing is that the above code did the job but created a file with the following permissions ---rwxr-x
so my method for importing the database file from the SDCARD back to the /data/data/pachage_name/databases fail at the line
FileChannel src = new FileInputStream(current_db).getChannel();
and the error is that, no read permission for this file.
How can I fix this issue?
thanks a lot.

needed root
shakash3obd said:
Hello everyone, I developed an app which utilizes database.
I implemented a method for backing up the database from /data/data/package_name/databases to the SDCARD wiith the following code
Code:
try {
File path_to_sd = Environment.getExternalStorageDirectory();
File path_to_data = Environment.getDataDirectory();
String current_db_path = "//data//" + getPackageName() + "//databases//";
String path_to_database = path_to_data.getAbsolutePath() + current_db_path;
String backup_name = "backup.db";
File current_db = new File(path_to_database, database_name);
File db_backup = new File(path_to_sd, backup_name);
FileChannel src = new FileInputStream(current_db).getChannel();
FileChannel dst = new FileOutputStream(db_backup).getChannel();
if(!db_backup.exists()){
try {
db_backup.createNewFile();
dst.transferFrom(src, 0, src.size());
src.close();
dst.close();
Toast.makeText(getApplicationContext(), "Exporting database done successfully!", Toast.LENGTH_LONG).show();
} catch (IOException e) {
e.printStackTrace();
}
}
} catch (Exception e) {
e.printStackTrace();
}
the thing is that the above code did the job but created a file with the following permissions ---rwxr-x
so my method for importing the database file from the SDCARD back to the /data/data/pachage_name/databases fail at the line
FileChannel src = new FileInputStream(current_db).getChannel();
and the error is that, no read permission for this file.
How can I fix this issue?
thanks a lot.
Click to expand...
Click to collapse
since u r trying to copy files to /data/data which is only read only mode ... so u need root access to do your job.....
i have attached a a zip file that contains 4 java files and can be included in your project...
it gives you root access... but writing to /data/data must be implemented by u...

Thank you so much anurag.dev1512.
I will take a look at the files you provided.
I will not be able to get back to you about the result soon since it's almost finals time so I will be busy until December
again, thanks a lot.:good:

Related

[Q] Writing to your Apps data folder

im trying to write a Serializable Object to the data folder of my app. I was using this code to specify the path to the file and write the Serializable Object
Code:
/**
* writeMissedCalls()
*
* @param context - the Context of the application
* @return if the missedCalls were written to file successfully
*/
public static boolean writeMissedCalls(Context context) {
String filename = context.getApplicationInfo().dataDir + "/" + MCWUtils.MCW_DATA_FILE;
FileOutputStream fos;
ObjectOutputStream out;
try {
fos = context.openFileOutput(filename, Context.MODE_PRIVATE);
out = new ObjectOutputStream(fos);
out.writeObject(MissedCallWidget.missedCalls);
out.close(); }
catch (FileNotFoundException e) { return false; }
catch (IOException e) { return false; }
return true;
}
when i try to write this Object in the onDisabled() of my AppWidgetProvider class i get an error of this sort
java.lang.RuntimeException: Unable to start receiver com.tsb.fistfulofneurons.missedcallwidget.MissedCallWidget: java.lang.IllegalArgumentException: File /data/data/com.tsb.fistfulofneurons.missedcallwidget/missed_calls.dat contains a path separator
do i not need to specify the path to my apps data folder? will the openFileOutput() specify the path to the data for me?
so instead of passing the path "/data/data/com.tsb.fistfulofneurons.missedcallwidget/missed_calls.dat" just pass "missed_calls.dat"?
thanks!
I've not tried to open a file in this manner, but I would guess that it defaults to the apps data directory. Why not give it a try and see?
Gene Poole said:
I've not tried to open a file in this manner, but I would guess that it defaults to the apps data directory. Why not give it a try and see?
Click to expand...
Click to collapse
yea it appears to default to the /data/data folder for your package. the documentation appears to be lacking. thanks

Create pref and move it to another location

Sorry for the unclear title. What I'm trying to do is the following:
Code:
Button btncheat = (Button) findViewById(R.id.button1);
final EditText score = (EditText) findViewById(R.id.editText1);
btncheat.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
String filename = "FlappyBird.xml";
String string = "<?xml version='1.0' encoding='utf-8' standalone='yes' ?>\n<map>\n<int name=\"score\" value=\"" + score.getText().toString() + "\" />\n</map>";
FileOutputStream outputStream;
try {
outputStream = openFileOutput(filename, Context.MODE_PRIVATE);
outputStream.write(string.getBytes());
outputStream.close();
} catch (Exception e) {
e.printStackTrace();
}
try {
String[] commands = {"mv /data/data/de.aciid.nullgc/files/FlappyBird.xml /data/data/com.dotgears.flappybird/shared_prefs/"};
RunAsRoot(commands);
} catch (Exception e) {
e.printStackTrace();
}
}
});
So, it creates the XML file from the String "string" (I don't know if I can do it like this, but the XML file looks right in the end) and move it to /data/data/com.dotgears.flappybird/shared_prefs/. The creation and moving of the XML file works flawless, but Flappy Bird does not read the pref properly. When I start the game, it says that my highscore is zero, although the score 999 (for example) is in the XML file. As I stated, the XML file looks right, I pasted an original and my modded XML in an online script and there are no differences whatsoever.
So why doesn't this work?

[Q] Help with App permission search application

Hello,
I am student in my final year doing a project based on android development. I am thinking of creating an application that scans all the installed application in the device and recover all the list of permission associated with the app.. I will then manually use the data to check the manifest files manually, so that I can flag up any app that has more permission than it should.
I am learning and just starting creating it in eclipse. But, any advice would greatly be appreciated as am new to this development world.
I am thinking of creating a GUI for the layout but how can I make it list all the installed application on the device before I can proceed into getting the permission.
Thank you.
You need to use the PackageManager
The solution is on stackoverflow (love that site), but since I can't post links yet, I'll simply give you the code (should work):
final Intent mainIntent = new Intent(Intent.ACTION_MAIN, null);
mainIntent.addCategory(Intent.CATEGORY_LAUNCHER);
final List pkgAppsList = getPackageManager().queryIntentActivities(mainIntent, 0);
for (Object obj : pkgAppsList) {
ResolveInfo resolveInfo = (ResolveInfo) obj;
PackageInfo packageInfo = null;
try {
packageInfo = getPackageManager().getPackageInfo(resolveInfo.activityInfo.packageName, PackageManager.GET_PERMISSIONS);
} catch (NameNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
String[] requestedPermissions = packageInfo.requestedPermissions;
}
Good luck!!
Edwin Bos said:
You need to use the PackageManager
The solution is on stackoverflow (love that site), but since I can't post links yet, I'll simply give you the code (should work):
final Intent mainIntent = new Intent(Intent.ACTION_MAIN, null);
mainIntent.addCategory(Intent.CATEGORY_LAUNCHER);
final List pkgAppsList = getPackageManager().queryIntentActivities(mainIntent, 0);
for (Object obj : pkgAppsList) {
ResolveInfo resolveInfo = (ResolveInfo) obj;
PackageInfo packageInfo = null;
try {
packageInfo = getPackageManager().getPackageInfo(resolveInfo.activityInfo.packageName, PackageManager.GET_PERMISSIONS);
} catch (NameNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
String[] requestedPermissions = packageInfo.requestedPermissions;
}
Good luck!!
Click to expand...
Click to collapse
Is it possible I can create it within a searchView so that it can search it and display the installed application. But, displayed the app in a scroll view as well.

[Q] Google Drive android api - Downloading sqlite db file from drive

I am using the below code for downloading an already uploaded sqlite db file from google drive to the data/data/packagename/databases folder, but when the method completes, I am seeing a db corruption warning message logged in logcat and also all the data on the device for the app is overwritten and shows up blank, upon opening the app.
Code:
mfile = Drive.DriveApi.getFile(mGoogleApiClient, mResultsAdapter.getItem(0).getDriveId());
mfile.openContents(mGoogleApiClient, DriveFile.MODE_READ_ONLY, null).setResultCallback(contentsOpenedCallback);
--mfile is an instance of DriveFile
final private ResultCallback<ContentsResult> contentsOpenedCallback = new ResultCallback<ContentsResult>()
{
@Override
public void onResult(ContentsResult result)
{
if (!result.getStatus().isSuccess())
{
FileUtils.appendLog(getApplicationContext(), Tag + "-onResult", "Error opening file");
return;
}
try
{
if (GetFileFromDrive(result))
{
//FileUtils.Restore(getApplicationContext());
SharedPrefHelper.EditSharedPreference(getApplicationContext(), Constants.PREFS_DO_RESTORE, false);
}
}
catch (FileNotFoundException e)
{
// TODO Auto-generated catch block
e.printStackTrace();
}
catch (IOException e)
{
// TODO Auto-generated catch block
e.printStackTrace();
}
}
};
private boolean GetFileFromDrive(ContentsResult result)
{
Contents contents = result.getContents();
//InputStreamReader rda = new InputStreamReader(contents.getInputStream());
BufferedReader reader = new BufferedReader(new InputStreamReader(contents.getInputStream()));
FileOutputStream outStream;
String currLine;
boolean restoreSuccess = false;
File sourceDbFile = BackupDBBeforeDeletion();
if(sourceDbFile != null)
sourceDbFile.delete();
try
{
outStream = new FileOutputStream(getApplicationContext().getDatabasePath(Constants.DB_NAME));
while ((currLine = reader.readLine()) != null)
{
outStream.write(currLine.getBytes());
}
outStream.flush();
reader.close();
outStream.close();
restoreSuccess = true;
}
catch (FileNotFoundException e)
{
// TODO: Log exception
}
catch (IOException e)
{
// TODO: Log Exception
}
return restoreSuccess;
}
When the method GetFileFromDrive completes, a db corruption shows up on LogCat and all the existing data on the app's datanase file (sqlite db) is gone.
Please help, as I have verified that the drive uploaded sqlite db file is correct and well formed, by downloading the same and opening it up in Sqlite Browser. It's the download from drive that is not working.

Java&WinRAR-(dirthack) to get files >4GB to USB-Disk for Kodi

Hi together,
last year I've installed a 1st-Gen FireTV with Kodi in combination with a 4TB USB HDD for my parents RV. Don't exactly remember how I got the 4TB disk to fat32, but google should provide the answer, since it did for me than. The bigger issue anyway was to get files bigger than 4GB on the disk. The trick for my was to find out, that Kodi can access *.rar archives as if it was a file. So I wrote a java "dirtyhack": It uses a combination of java and WinRAR. Java to determine if a file is bigger than 4GB or not. If it is smaller, just copy the file, if it is bigger, call WinRAR with the right parameters to create a splittet archive consisting of parts smaller than 4GB on the HDD.
So first you choose a source-folder, than select a destination-folder (should be the Disk ) and all files get copied recursively.
As I'm currently updating the HDD and have unsuccessfully searched for an easier way (after I've installed all updates on the ftv *doh!*) I thought I could share my Code, so here you go:
Code:
import javax.swing.*;
import java.io.IOException;
import java.io.*;
/**
* @author der-gee
*
*/
public class Copy {
static int amountFiles = 0;
static long limit = 4294967295L;
/**
* Lists all files from a given folder, recursively
*
* @param dir
* Prints a list of files > 4GB and sums them up
*/
public static void listDir(File dir) {
File[] files = dir.listFiles();
if (files != null) {
for (int i = 0; i < files.length; i++) {
if (files[i].isDirectory()) {
listDir(files[i]); // calls itself
} else {
if (files[i].length() > limit) {
System.out.println(files[i].getAbsolutePath());
amountFiles++;
}
}
}
}
}
/**
* Shows a select file dialog and returns the choosen one ^^
*
* @param title
* Title to be shown by the "choose file dialog"
* @return The directory as file
*/
static public File getFolder(String title) {
JFileChooser chooser;
chooser = new JFileChooser();
chooser.setCurrentDirectory(File.listRoots()[0]);
chooser.setDialogTitle(title);
chooser.setFileSelectionMode(JFileChooser.DIRECTORIES_ONLY);
chooser.setAcceptAllFileFilterUsed(false);
if (chooser.showOpenDialog(null) == JFileChooser.APPROVE_OPTION) {
return chooser.getSelectedFile();
} else {
System.out.println("No Selection ");
return null;
}
}
/**
* Copies directories and files smaller than 4GB
*
* @param src
* @param dest
* @throws IOException
*/
public static void copyFolder(File src, File dest) throws IOException {
if (src.isDirectory()) {
// if directory not exists, create it
if (!dest.exists()) {
dest.mkdir();
System.out.println("Directory copied from " + src + " to "
+ dest);
}
// list all the directory contents
String files[] = src.list();
for (String file : files) {
// construct the src and dest file structure
File srcFile = new File(src, file);
File destFile = new File(dest, file);
// recursive copy
copyFolder(srcFile, destFile);
}
} else {
// if file, then copy it
// Use bytes stream to support all file types
// If file is t large for Fat32 -> rar it
if (src.length() >= limit)
rarThis(src, dest);
else {
InputStream in = new FileInputStream(src);
OutputStream out = new FileOutputStream(dest);
byte[] buffer = new byte[1024];
int length;
// copy the file content in bytes
while ((length = in.read(buffer)) > 0) {
out.write(buffer, 0, length);
}
in.close();
out.close();
System.out.println("File copied from " + src + " to " + dest);
System.out.println("Size from: " + src + ":" +src.length());
}
}
}
/**
* Should use a combination of cmd and winrar to create splitted archives,
* so that they can be stored to a fat32 drive.
*
* @param src
* @param dest
*/
public static void rarThis(File src, File dest) {
String[] command = {
"\"" + "C:\\Program Files\\WinRAR\\rar.exe" + "\"",
"a", "-m0", //a = Archive, -m0 = compressionMode store
"-v3.999g", "-y", //v = VolSize, y = always answer yes
"-ep", //ep = noPath in archive
"\"" + dest.getAbsolutePath().replace("mkv", "rar") + "\"",
"\"" + src.getAbsolutePath() + "\"" };
Runtime rt = Runtime.getRuntime();
try {
Process rar = rt.exec(command);
BufferedReader reader = new BufferedReader(new InputStreamReader(rar.getInputStream()));
String line;
while ((line = reader.readLine()) != null)
System.out.println("WinRAR: " + line);
rar.waitFor();
} catch (IOException e) {
// TODO Auto-generated catch block
System.out.println(e);
e.printStackTrace();
} catch (InterruptedException e) {
// TODO Auto-generated catch block
System.out.println(e);
e.printStackTrace();
}
}
/**
* Main program. Initiates the whole thing :)
*
* @param s
* @throws IOException
*/
public static void main(String s[]) throws IOException {
System.out.println("Size limit: " + limit);
File sourcePath = getFolder("Source");
if (sourcePath != null) {
listDir(sourcePath);
System.out.println("Amount files > 4GB: " + amountFiles);
}
File targetPath = getFolder("Destination");
copyFolder(sourcePath, targetPath);
System.out.println("Finished!");
}
}
I wrote this for Windows, using the x64 Version of WinRar, so if you are using the 32-bit version, you have to adjust the rar folder in the rarThis function. Feel free to use and share. If you have improvements, please share
Interesting. When I came to this problem of HD files larger than 4 GB I decided to use the NTFS format and then use Paragon to mount the external HDD on my rooted Fire TV.
PhoenixMark said:
Interesting. When I came to this problem of HD files larger than 4 GB I decided to use the NTFS format and then use Paragon to mount the external HDD on my rooted Fire TV.
Click to expand...
Click to collapse
Hehe, I would have done the same, but I checked for root after upgrading to the very last fw version
PhoenixMark said:
Interesting. When I came to this problem of HD files larger than 4 GB I decided to use the NTFS format and then use Paragon to mount the external HDD on my rooted Fire TV.
Click to expand...
Click to collapse
Was this on the latest rooted firmware? I have a AFTV2 running the latest prerooted rom from rbox
deanr1977 said:
Was this on the latest rooted firmware? I have a AFTV2 running the latest prerooted rom from rbox
Click to expand...
Click to collapse
I'm using 5.0.5 because I like using FireStarter, but I don't see why you can't still do this on 5.0.5.1 as well as there is a pre rooted rom for it. Only difference is you need the A to A USB cable to root 5.0.5.1.

Categories

Resources