I have trying to copy my app database from storage data to any outher floder
but i'm getting some error .
my device is rooted and i have used many apps from google play to nevigate to data/data but it's empty and i have used this code :
public void backup() {
try {
File sdcard = Environment.getRootDirectory();
File outputFile = new File(sdcard,
"YourDatabase.db");
if (!outputFile.exists())
outputFile.createNewFile();
File data = Environment.getDataDirectory();
File inputFile = new File(data,
"data/"+LoginActivity.this.getPackageName()+"/databases/"+"HafilTC.db");
InputStream input = new FileInputStream(inputFile);
OutputStream output = new FileOutputStream(outputFile);
byte[] buffer = new byte[1024];
int length;
while ((length = input.read(buffer)) > 0) {
output.write(buffer, 0, length);
}
output.flush();
output.close();
input.close();
} catch (IOException e) {
e.printStackTrace();
throw new Error(e.toString());
}
android mainfilfist :
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" />
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.READ_PHONE_STATE" />
error log :
02-11 18:38:16.213: E/AndroidRuntime(21338): java.lang.Error: java.io.IOException: open failed: EROFS (Read-only file system)
The problem is that Environment.getRootDirectory() does not return the root directory of the SD card. It returns the root OS directory, which you cannot write to.
You should instead use Environment.getExternalStorageDirectory(), which will return the root directory of the user's external storage directory (which may or may not be an SD Card, depending on the device).
You have at least two options here.
Using DDMS
Open Eclipse, and switch to DDMS perspective.
Than follow the path:
DDMS--> file explorer-->data--> data--> your package name-->databases
Your database should be inside databases folder, and since you're on a rooted device you can get it.
Using ADB
You can use ADB once you have a device connected via USB and with USB debig enabled. To check if your device is correctly connected use:
adb devices
Than get your DB with these commands (you're copying it to SDCARD, and then reading directly from there):
adb -d shell
run-as your.package.name
cat /data/data/your.package.name/databases/database_name.db > /sdcard/your_db_name.db
If you want to do it programmatically have a look to what #Tanis.7x suggests.
The problem has been solved by remove .db from
HafilTC.db
to make it just file name : HafilTC
Related
I'm working with Android Studio, writing in Java. I'm trying to write a piece of software that will take pictures from a camera based on an event. So first steps first was to figure out the API. Camera is depreciated, so there's Camera2, but the latest is CameraX. I've attempted to use both CameraX and Camera2, but for some reason I'm not saving any images. I believe the capture works, but the issue is saving the files. I don't know what's going on.
First lets start with permissions. Yes, I have set permissions for both the camera and external storage.
<uses-permission android:name="android.permission.CAMERA" />
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE"/>
So lets move on to the code itself.
I've never saved photos before, but I have worked with text files such as .txt and .csv files. Which I've been able to make work.
Right now I do a simple button click to capture the image. Which is nothing more than an onclicklistener. Once I press the button this is what actions occur.
SimpleDateFormat mDateFormat = new SimpleDateFormat("yyyyMMddHHmmss", Locale.US);
File file = new File(Environment.getDataDirectory(), mDateFormat.format(new Date())+ ".jpg");
if(!file.exists())
file.mkdirs();
ImageCapture.OutputFileOptions outputFileOptions = new ImageCapture.OutputFileOptions.Builder(file).build();
imageCapture.takePicture(outputFileOptions, executor, new ImageCapture.OnImageSavedCallback () {
#Override
public void onImageSaved(#NonNull ImageCapture.OutputFileResults outputFileResults) {
Toast.makeText(MainActivity.this, "TEST", Toast.LENGTH_SHORT).show();
new Handler().post(new Runnable() {
#Override
public void run() {
Toast.makeText(MainActivity.this, "Image Saved successfully", Toast.LENGTH_SHORT).show();
}
});
}
#Override
public void onError(#NonNull ImageCaptureException error) {
error.printStackTrace();
// Toast.makeText(MainActivity.this, "Image save FAILED!!!!", Toast.LENGTH_SHORT).show();
}
});
when the app launches the first time, it asks for permission and I grant permission. but looking at the run tab as part of the Android Studio ID, I get the following readout, when I press the capture button
D/ImageCapture: Send image capture request [current, pending] = [0, 1]
D/CaptureSession: Issuing capture request.
W/example.camera: JNI critical lock held for 21.148ms on Thread[14,tid=10076,Runnable,Thread*=0xdc743000,peer=0x13184cf8,"Binder:10045_2"]
W/ExifInterface: Stop reading file since a wrong offset may cause an infinite loop: 0
Skip the tag entry since data format (ULONG) is unexpected for tag: GPSAltitudeRef
W/ExifInterface: Stop reading file since a wrong offset may cause an infinite loop: 0
Stop reading file since a wrong offset may cause an infinite loop: 0
W/System.err: androidx.camera.core.ImageCaptureException: Failed to write or close the file
W/System.err: at androidx.camera.core.ImageCapture$3.onError(ImageCapture.java:669)
at androidx.camera.core.ImageSaver.lambda$postError$1$ImageSaver(ImageSaver.java:263)
at androidx.camera.core.-$$Lambda$ImageSaver$eAp-cZyzsEk-LVLazzLE-ezQzwo.run(Unknown Source:8)
W/System.err: at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1167)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:641)
at java.lang.Thread.run(Thread.java:919)
Caused by: java.io.FileNotFoundException: /data/20200728142756.jpg: open failed: EACCES (Permission denied)
at libcore.io.IoBridge.open(IoBridge.java:496)
at java.io.FileOutputStream.<init>(FileOutputStream.java:235)
at java.io.FileOutputStream.<init>(FileOutputStream.java:186)
at androidx.camera.core.ImageSaver.run(ImageSaver.java:97)
... 3 more
W/System.err: Caused by: android.system.ErrnoException: open failed: EACCES (Permission denied)
at libcore.io.Linux.open(Native Method)
at libcore.io.ForwardingOs.open(ForwardingOs.java:167)
at libcore.io.BlockGuardOs.open(BlockGuardOs.java:252)
at libcore.io.ForwardingOs.open(ForwardingOs.java:167)
at android.app.ActivityThread$AndroidOs.open(ActivityThread.java:7255)
at libcore.io.IoBridge.open(IoBridge.java:482)
... 6 more
W/example.camera: JNI critical lock held for 17.651ms on Thread[16,tid=10083,Runnable,Thread*=0xdc74bc00,peer=0x13184de8,"Binder:10045_4"]
I've searched around, and looked for different methods of saving the file, and I've had success with saving the image, sort of, when I use the camera2 api and save the file using outputstream
When I use Camera2 it appears to save just fine, but I have no idea where it saves, I can't find it. I point this out, because it still appears to be a permission denied error as what I'm seeing is when I open up Device File Explorer its not letting me view /storage/emulator/ it just shows me
ls: /storage/emulated/: Permission denied.
all the examples I have found have assumed access with no issues to emulated.
Does anyone have any insight as to why I'm having permission denied errors?
UPDATE
So I still haven't solved the issue related to the failed mkdir() call. However, I did fix one issue, that could have been causing the issue. The means as to how I was creating the directory and the file itself wasn't correct.
SimpleDateFormat mDateFormat = new SimpleDateFormat("yyyyMMddHHmmss", Locale.US);
File file = new File(getBatchDirectoryName(), mDateFormat.format(new Date())+ ".jpg");
public String getBatchDirectoryName() {
String app_folder_path = "";
app_folder_path = Environment.getExternalStorageDirectory() + "/images";
File dir = new File(app_folder_path);
if (!dir.exists() && !dir.mkdirs()) {
Toast.makeText(MainActivity.this, "Trip", Toast.LENGTH_SHORT).show();
}
return app_folder_path;
}
However, it still fails to create the directory. Which still makes me come back to a permission issue.
Environment.getExternalStorageDirectory() appears to be deprecated. Documentation appears to recommend using getExternalFilesDir(string) or MediaStore. However, I'm having issues finding sample use cases. And I can't imagine, that while deprecated, it would just stop working at all. Most devices on the market are not API 29 or higher.
Based on help from #blackapps, I was able to make changes to my Manifest file to allow access to external storage.
More information can be found here
Request Legacy External Storage
With #blackapps, and this thread on stackoverflow I was able to update my permissions to allow legacy access.
Because in Android Q they have disabled direct file access, they have added a work around to allow legacy support. This is, and as others have mentioned, only a temporary fix for the issue. You will need to follow the new format for saving files going forward with Android R. In my situation, I am only developing a proof of concept and will not need to worry about future versions of Android.
To make the temporary fix, do the following
Add the following line
android:requestLegacyExternalStorage="true">
inside your <application bracket on the manifest file. Should look similar to this
<?xml version="1.0" encoding="utf-8"?>
...
package="com.example.camerax">
...
<application
...
android:requestLegacyExternalStorage="true">
<activity android:name=".MainActivity">
<intent-filter>
...
</intent-filter>
</activity>
</application>
remember this is not a long term fix, and will not work when a device is updated to Android R
I'm following the File transfer example on the Nearby Connections Exchange page (the "more complex example" code snippet).
I can send an image and receive it on another device in the Download/Nearby folder. The image is sent successfully since if I were to change the file name to give it an appropriate extension (e.g. .jpg), I can open the image in a photo gallery app.
private void processFilePayload(long payloadId) {
Payload filePayload = completedFilePayloads.get(payloadId);
String filename = filePayloadFilenames.get(payloadId);
if (filePayload != null && filename != null) {
completedFilePayloads.remove(payloadId);
filePayloadFilenames.remove(payloadId);
// Retrieve received file from Downloads folder
Payload.File payloadFile2 = filePayload.asFile();
File payloadJavaFile = payloadFile2.asJavaFile();
if (payloadJavaFile == null) {
Log.d(TAG, "Payload java file is null in processFilePayload()");
} else {
payloadJavaFile.renameTo(new File(payloadJavaFile.getParentFile(), filename));
}
}
}
Why is the payloadJavaFile variable null? From looking at Payload.class, I know that the result of asJavaFile() is a nullable File and that, from the asJavaFile() method description, calling asJavaFile() in processFilePayload() from within onPayloadReceived() (as is done in the example on the API page) may lead to the File not having received all of the payload's contents yet. However, I also call processFilePayload() from within onPayloadTransferUpdate() after verifying the success of the PayloadTransferUpdate, and so shouldn't the payload have received all of its contents by this stage (and not be null when calling asJavaFile() on the payload object)?
My code is almost the same as the documentation for both sending and receiving the image and file name.
Payload.asJavaFile() will be null if the READ_EXTERNAL_STORAGE permission is not properly set up for your application. You need READ_EXTERNAL_STORAGE in the AndroidManifest.xml and you need to also request READ_EXTERNAL_STORAGE permission at runtime since it is a dangerous permission. (https://developer.android.com/training/permissions/requesting)
To share files using Nearby Connections, your application will need all of the following:
AndroidManifest.xml
<!-- Required for Nearby Connections -->
<uses-permission android:name="android.permission.BLUETOOTH" />
<uses-permission android:name="android.permission.BLUETOOTH_ADMIN" />
<uses-permission android:name="android.permission.ACCESS_WIFI_STATE" />
<uses-permission android:name="android.permission.CHANGE_WIFI_STATE" />
<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" />
<!-- Optional: needed to share files -->
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE"/>
MainActivity.java
ActivityCompat.requestPermissions(thisActivity,
new String[]{
Manifest.permission.ACCESS_COARSE_LOCATION,
Manifest.permission.READ_EXTERNAL_STORAGE
},
PERMISSIONS_REQUEST_CODE);
We will improve the documentation to make this requirement for sharing files more obvious.
I checked the source code. From what I can see, asJavaFile() is always set (and I'm not sure why it's marked as #Nullable).
Unfortunately, for me to look into it any further, I'd need you to provide me with a sample app that reproduces the bug you're seeing.
I am trying to write an image file to sd card but i get an error :Open Failed eacces permission denied.
i am using this code:
File ff = new File(aa.datasearchSG_getter().get(0).getUrl()+ "try" );
try{
ff.createNewFile();
} catch (Exception e){
Log.d("error" , "creating");
e.printStackTrace();
}
I have added permission :-
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/> and
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE"/>
but still getting error.
Finally I solved this issue. We need to get TreeUri using Android Storage Access Framework(SAF) and then using that Uri to modify the file.
I'm trying to create a simple app that can get an image from the Gallery app and display it on an imageButton. I'm testing with API 21 on a phone running Android 5.0.1. Unfortunately, no matter what I try I keep getting a security error - even when I specify the permissions.
My code for getting retrieving the image is:
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent imageReturnedIntent){
super.onActivityResult(requestCode, resultCode, imageReturnedIntent);
switch(requestCode){
case PICK_IMAGE_REQUEST:
if(resultCode == RESULT_OK && imageReturnedIntent != null && imageReturnedIntent.getData() != null) {
Uri uri = imageReturnedIntent.getData();
try {
Bitmap bitmap = MediaStore.Images.Media.getBitmap(getContentResolver(), uri);
// Log.d(TAG, String.valueOf(bitmap));
ImageButton ib = (ImageButton) findViewById(R.id.inputImg);
ib.setImageBitmap(bitmap);
} catch (IOException e) {
e.printStackTrace();
}
}
break;
}
}
The code works when I try to select an image from Dropbox, but when I select an image from gallery, I get
java.lang.SecurityException: Permission Denial: reading com.android.providers.media.MediaProvider uri content://media/external/images/media/35634 from pid=25240, uid=10070 requires android.permission.READ_EXTERNAL_STORAGE, or grantUriPermission()
I made the use-permission tag for READ_EXTERNAL_STORAGE a child of manifest:
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
package="[REDACTED]">
<uses-sdk
android:minSdkVersion="14"
android:targetSdkVersion="23" />
<uses-permission tools:node="replace" android:name="android.permission.READ_EXTERNAL_STORAGE" android:maxSdkVersion="18" />
<application>
[REDACTED]
</application>
</manifest>
I've searched high and low on other posts, but still can't seem to figure out why I'm still getting this pesky error.
PROBLEM
Your have the error
java.lang.SecurityException: Permission Denial: reading com.android.providers.media.MediaProvider uri content://media/external/images/media/35634 from pid=25240, uid=10070 requires android.permission.READ_EXTERNAL_STORAGE, or grantUriPermission().
CAUSE
You are not giving correctly permissions because of android:maxSdkVersion="18", which according to documentation.
The highest API level at which this permission should be granted to your app. Setting this attribute is useful if the permission your app requires is no longer needed beginning at a certain API level.
As long as you didn't give permissions to API 21 your app is behaving ok.
Check this topic for further info.
SOLUTION
If you wanna give read permissions under API 21, you must declare them as:
<uses-permission
android:name="android.permission.READ_EXTERNAL_STORAGE"
android:maxSdkVersion="21" />
IMPORTANT:
This only make sense when you need to give extra permissions because some old api's require permissions that new versions doesn't, so user experience get's improved because you only ask for certain permissions when needed.
So (in this case) the correct way will be:
<uses-permission
android:name="android.permission.READ_EXTERNAL_STORAGE" />
ADD ON
If you want to save data you must add WRITE_EXTERNAL_STORAGE permissions.
<uses-permission
android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
Simply replace with the below one and try,
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
While debugging on some devices you need to grant permission explicitly by going to your settings --> apps --> MY_APPLICATION --> Permissions and then grant required permissions.
In addition to adding the below in AndroidManifest.xml
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />
we also need to request permission in the activity for the app to actually have access to external storage. https://developer.android.com/training/permissions/requesting.html
Can anybody tell my why this doesn't work in the Android emulator? From the browser I have access and the server is internal. All I can think of is that I'm missing some configuration on my app so it can access the network layer.
try {
InetAddress server = Inet4Address.getByName("thehost");
//Doesn't work either
//or InetAddress server2 = Inet4Address.getByAddress(new String("192.168.1.30").getBytes());
if(server.isReachable(5000)){
Log.d(TAG, "Ping!");
}
Socket clientsocket = new Socket(server, 8080);
} catch (UnknownHostException e) {
Log.e(TAG, "Server Not Found");
} catch (IOException e) {
Log.e(TAG, "Couldn't open socket");
}
Throws an UnknownHostException
Thanks
As far as configuration goes, the only setting you should need to access the Internet from your application is the INTERNET permission, enabled by adding the following line outside the Application tags within your application Manifest.
<uses-permission android:name="android.permission.INTERNET" />
So the manifest would follow this general construction
<manifest xmlns:android="http://schemas.android.com/apk/res/android" package="com.example.android.apis">
<uses-permission android:name="android.permission.INTERNET" />
<application
android:name="MyApplication"
android:label="#string/application_title"
android:icon="#drawable/my_icon">
[ .. Your Activities go here ]
</application>
</manifest>
It might still not work, because of the timeout. Since you need root permissions to send an ICMP Package and the implemetation of isReachable will use the slow TCP version of ECHO. Chekcout the javaDoc.