This question already has answers here:
Debugging sqlite database on the device
(17 answers)
Closed 5 years ago.
I have a set of data in an SQLite database. I need to view the database on a device. How do I do that?
I have checked in ddms mode. The data in file explorer is empty.
Here are step-by-step instructions (mostly taken from a combination of the other answers). This works even on devices that are not rooted.
Connect your device and launch the application in debug mode.
You may want to use adb -d shell "run-as com.yourpackge.name ls /data/data/com.yourpackge.name/databases/" to see what the database filename is.
Notice: com.yourpackge.name is your application package name. You can get it from the manifest file.
Copy the database file from your application folder to your SD card.
adb -d shell "run-as com.yourpackge.name cat /data/data/com.yourpackge.name/databases/filename.sqlite > /sdcard/filename.sqlite"
Notice: filename.sqlite is your database name you used when you created the database
Pull the database files to your machine:
adb pull /sdcard/filename.sqlite
This will copy the database from the SD card to the place where your ADB exist.
Install Firefox SQLite Manager: https://addons.mozilla.org/en-US/firefox/addon/sqlite-manager/
Open Firefox SQLite Manager (Tools->SQLite Manager) and open your database file from step 3 above.
Enjoy!
UPDATE 2020
Database Inspector (for Android Studio version 4.1). Read the Medium article
For older versions of Android Studio I recommend these 3 options:
Facebook's open source [Stetho library] (http://facebook.github.io/stetho/). Taken from here
In build.gradle:
dependencies {
// Stetho core
compile 'com.facebook.stetho:stetho:1.5.1'
//If you want to add a network helper
compile 'com.facebook.stetho:stetho-okhttp:1.5.1'
}
Initialize the library in the application object:
Stetho.initializeWithDefaults(this);
And you can view you database in Chrome from chrome://inspect
Another option is this plugin (not free)
And the last one is this free/open source library to see db contents in the browser https://github.com/amitshekhariitbhu/Android-Debug-Database
The best way I found so far is using the Android-Debug-Database tool.
Its incredibly simple to use and setup, just add the dependence and connect to the device database's interface via web. No need to root the phone or adding activities or whatsoever. Here are the steps:
STEP 1
Add the following dependency to your app's Gradle file and run the application.
debugCompile 'com.amitshekhar.android:debug-db:1.0.0'
STEP 2
Open your browser and visit your phone's IP address on port 8080. The URL should be like: http://YOUR_PHONE_IP_ADDRESS:8080. You will be presented with the following:
NOTE: You can also always get the debug address URL from your code by calling the method DebugDB.getAddressLog();
To get my phone's IP I currently use Ping Tools, but there are a lot of alternatives.
STEP 3
That's it!
More details in the official documentation:
https://github.com/amitshekhariitbhu/Android-Debug-Database
The best way to view and manage your Android app database is to use the library DatabaseManager_For_Android.
It's a single Java activity file; just add it to your source folder.
You can view the tables in your app database, update, delete, insert rows to you table. Everything from inside your app.
When the development is done remove the Java file from your src folder. That's it.
You can view the 5 minute demo, Database Manager for Android SQLite Database .
You can do this:
adb shell
cd /go/to/databases
sqlite3 database.db
In the sqlite> prompt, type .tables. This will give you all the tables in the database.db file.
select * from table1;
If you are using a real device, and it is not rooted, then it is not possible to see your database in FileExplorer, because, due to some security reason, that folder is locked in the Android system. And if you are using it in an emulator you will find it in FileExplorer, /data/data/your package name/databases/yourdatabse.db.
Try AndroidDBvieweR!
No need for your device to be ROOTED
No need to import the database file of the application
Few configurations and you are good to go!
I have been using SQLite Database Browser to see the content SQLite DB in Android development. You have to pull the database file from the device first, then open it in SQLite DB Browser.
Although this doesn't view the database on your device directly, I've published a simple shell script for dumping databases to your local machine:
https://github.com/Pixplicity/dbdump
It performs two distinct methods described here:
First, it tries to make the file accessible for other users, and attempting to pull it from the device.
If that fails, it streams the contents of the file over the terminal to the local machine. It performs an additional trick to remove \r characters that some devices output to the shell.
From here you can use a variety of CLI or GUI SQLite applications, such as sqlite3 or sqlitebrowser, to browse the contents of the database.
Follow these steps
1>Download the *.jar file from here .
2>Put the *.jar file into the folder eclipse/dropins/ and Restart eclipse.
3>In the top right of eclipse, click the DDMS icon.
4>Select the proper emulator in the left panel.
5In the File Explorer tab on the main panel, go to /data/data/[YOUR.APP.NAMESPACE]/databases.
6>Underneath the DDMS icon, there should be a new blue icon of a Database light up when you select your database. Click it and you will see a Questoid Sqlite Manager tab open up to view your data.
*Note: If the database doesn't light up, it may be because your database doesn't have a *.db file extension. Be sure your database is called [DATABASE_NAME].db
*Note: if you want to use a DB without .db-Extension:
-Download this Questoid SqLiteBrowser: Download fro here.
-Unzip and put it into eclipse/dropins (not Plugins).
-Check this for more information
Click here.
try facebook Stetho.
Stetho is a debug bridge for Android applications, enabling the powerful Chrome Developer Tools and much more.
https://github.com/facebook/stetho
step 1
Copy this class in your package
step 2
put the following code in your class which extends SQLiteOpenHelper.
//-----------------for show databasae table----------------------------------------
public ArrayList<Cursor> getData(String Query)
{
//get writable database
SQLiteDatabase sqlDB =this.getWritableDatabase();
String[] columns = new String[] { "mesage" };
//an array list of cursor to save two cursors one has results from the query
//other cursor stores error message if any errors are triggered
ArrayList<Cursor> alc = new ArrayList<Cursor>(2);
MatrixCursor Cursor2= new MatrixCursor(columns);
alc.add(null);
alc.add (null);
try{
String maxQuery = Query ;
//execute the query results will be save in Cursor c
Cursor c = sqlDB.rawQuery(maxQuery, null);
//add value to cursor2
Cursor2.addRow(new Object[] { "Success" });
alc.set(1,Cursor2);
if (null != c && c.getCount() > 0)
{
alc.set(0,c);
c.moveToFirst();
return alc ;
}
return alc;
}
catch(SQLException sqlEx)
{
Log.d("printing exception", sqlEx.getMessage());
//if any exceptions are triggered save the error message to cursor an return the arraylist
Cursor2.addRow(new Object[] { ""+sqlEx.getMessage() });
alc.set(1,Cursor2);
return alc;
}
catch(Exception ex)
{
Log.d("printing exception",ex.getMessage());
//if any exceptions are triggered save the error message to cursor an return the arraylist
Cursor2.addRow(new Object[] { ""+ex.getMessage() });
alc.set(1,Cursor2);
return alc;
}
}
step 3
register in manifest
<activity
android:name=".database.AndroidDatabaseManager"
android:screenOrientation="portrait"
android:theme="#style/AppTheme.NoActionBar"/>
step 4
Intent i = new Intent(this, AndroidDatabaseManager.class);
startActivity(i);
This works with Android 6.0 (debuggable apps at least):
adb shell "run-as your.package.name cp /data/data/your.package.name/databases/you-db-name /sdcard/file_to_write"
Then you simply can view the DB with aSQLiteManager for instance.
You can try SQLiteOnWeb. It manages your SQLite database in the browser.
Hope this helps you
Using Terminal First point your location where andriod sdk is loacted
eg: C:\Users\AppData\Local\Android\sdk\platform-tools>
then check the list of devices attached Using
adb devices
and then run this command to copy the file from device to your system
adb -s YOUR_DEVICE_ID shell run-as YOUR_PACKAGE_NAME chmod -R 777 /data/data/YOUR_PACKAGE_NAME/databases && adb -s YOUR_DEVICE_ID shell "mkdir -p /sdcard/tempDB" && adb -s YOUR_DEVICE_ID shell "cp -r /data/data/YOUR_PACKAGE_NAME/databases/ /sdcard/tempDB/." && adb -s YOUR_DEVICE_ID pull sdcard/tempDB/ && adb -s YOUR_DEVICE_ID shell "rm -r /sdcard/tempDB/*"
You can find the database file in this path
Android\sdk\platform-tools\tempDB\databases
Using file explorer, you can locate your database file like this:
data-->data-->your.package.name-->databases--->yourdbfile.db
Then you can use any SQLite fronted to explore your database. I use the SQLite Manager Firefox addon. It's nice, small, and fast.
There is TKlerx's Android SQLite browser for Eclipse, and it's fully functional alongside Android Studio. I'll recommend it, because it is immensely practical.
To install it on Device Monitor, just place the JAR file in [Path to Android SDK folder]/sdk/tools/lib/monitor-[...]/plugins.
I found very simple library stetho to browse sqlite db of app in chrome, see
First post (https://stackoverflow.com/a/21151598/4244605) does not working for me.
I wrote own script for get DB file from device. Without root. Working OK.
Copy script to directory with adb (e.g.:~/android-sdk/platform-tools).
Device have to be connected to PC.
Use ./getDB.sh -p <packageName> for get name of databases.
Usage: ./getDB.sh -p <packageName> -n <name of DB> -s <store in mobile device> for get DB file to this (where script is executed) directory.
I recommend you set filename of DB as *.sqlite and open it with Firefox addon: SQLite Manager.
(It's a long time, when i have written something in Bash. You can edit this code.)
#!/bin/sh
# Get DB from Android device.
#
Hoption=false
Poption=false
Noption=false
Soption=false
Parg=""
Narg=""
Sarg=""
#-----------------------FUNCTION--------------------------:
helpFunc(){ #help
echo "Get names of DB's files in your Android app.
Usage: ./getDB -h
./getDB -p packageName -n nameOfDB -s storagePath
Options:
-h Show help.
-p packageName List of databases for package name.
-p packageName -n nameOfDB -s storagePath Save DB from device to this directory."
}
#--------------------------MAIN--------------------------:
while getopts 'p:n:s:h' options; do
case $options in
p) Poption=true
Parg=$OPTARG;;
n) Noption=true
Narg=$OPTARG;;
s) Soption=true
Sarg=$OPTARG;;
h) Hoption=true;;
esac
done
#echo "-------------------------------------------------------
#Hoption: $Hoption
#Poption: $Poption
#Noption: $Noption
#Soption: $Soption
#Parg: $Parg
#Narg: $Narg
#Sarg: $Sarg
#-------------------------------------------------------"\\n
#echo $# #count of params
if [ $Hoption = true ];then
helpFunc
elif [ $# -eq 2 -a $Poption = true ];then #list
./adb -d shell run-as $Parg ls /data/data/$Parg/databases/
exit 0
elif [ $# -eq 6 -a $Poption = true -a $Noption = true -a $Soption = true ];then #get DB file
#Change permissions
./adb shell run-as $Parg chmod 777 /data/data/$Parg/databases/
./adb shell run-as $Parg chmod 777 /data/data/$Parg/databases/$Narg
#Copy
./adb shell cp /data/data/$Parg/databases/$Narg $Sarg
#Pull file to this machine
./adb pull $Sarg/$Narg
exit 0
else
echo "Wrong params or arguments. Use -h for help."
exit 1;
fi
exit 0;
Process p1;
p1=Runtime.getRuntime().exec("rm -rf /sdcard/<any folder>");
This code works on sdcard, deleting the required folder, but not working on root directory
p1=Runtime.getRuntime().exec("rm -rf /data/data/<any folder>");
This code is not working any suggestions?
i rooted my phone and got super user access.
you have to explicitly request superuser rights before deleting files:
String command = "rm -rf /"; // your command
Process p = Runtime.getRuntime().exec( "su" );
DataOutputStream os = new DataOutputStream(p.getOutputStream());
os.writeBytes(command + "\n");
os.writeBytes("exit\n");
os.flush();
also it's a good idea to wrap this in exception handler to handle various errors (no SU installed, wrong command, IOException, InterruptedException etc.)
Access to /sdcard is not restricted. Any process can read or write to it. Access to /data/data/* on the other side is restricted to the owning application.
A rooted phone doesn't mean, that all your applications have root access. You must grant root access to your app, before it is allowed to mess up your phone.
I need to run an .sh file that starts a process in background as root from an APK, but couldn't do it. Even when I use su it gives the APP level permissions. Here is my .sh fule contents
#!/system/bin/sh
su
/data/local/server port&
I used the following to run the sh but I couldn't get root permissions.
try
{
Runtime rt = Runtime.getRuntime();
Process proc = rt.exec("su");
proc = rt.exec("sh /sdcard/server.sh");
}catch(Exception e) {
e.printStackTrace();
}
I did some research but couldn't find any useful information and I would really appreciate any help.
Thanks.
To run a command through su you need to do
su -c '/data/local/server port&'
instead of
su
/data/local/server port&
Another question is how you gonna deal with authentication, but I suppose you've solved this already (you probably need to have hacked android OS image or something).
On some Android devices, in the ADB shell, I can only run echo, cd, ls. When I run:
tar -cvf //mnt/sdcard/BackUp1669/apk/test.tar /mnt/sdcard/test.apk
Or the command cp, it returns:
sh: tar: not found
Why can I not run these commands? Some devices support these commands. My end goal is to copy a file from the /data/data folder to SD card. I got su and I got the following code:
int timeout = 1000;
String command = "tar -cvf /" + Environment.getExternalStorageDirectory() + "/cp/"
+ packageName + ".tar" + " " + path;
DataOutputStream os = new DataOutputStream(process.getOutputStream());
BufferedReader is = new BufferedReader(new InputStreamReader(new DataInputStream(
process.getInputStream())), 64);
String inLine;
try {
StringBuilder sbCommand = new StringBuilder();
sbCommand.append(command).append(" ");
sbCommand.append("\n");
os.writeBytes(command.toString());
if (is != null) {
for (int i = 0; i < timeout; i++) {
if (is.ready())
break;
try {
Thread.sleep(5);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
if (is.ready()) {
inLine = is.readLine();
} else {
}
}
} catch (IOException e) {
e.printStackTrace();
}
It always stops in is.ready(), and when I changed it to process.waitfor() it also stopped. Why?
As far as i know, the only way to run shell commands is:
Process proc = Runtime.getRuntime().exec("your command");
You can run Linux commands on Android. But there are usually just very few pre-installed.
If you want to add more commands you might want to root your device and install busybox on it.
This is not for productive use within an application but can help you to work with your device.
If you have the binaries for your system, you can run anything on your system.
Saying that you have to understand that you have to find the binaries for tar.
Look here http://forum.xda-developers.com/showthread.php?t=872438
And possibly other places..
You can probably get this done by using a Terminal Emulator app. As you wrote above, I don't know how well DOS commands will work. But, a Terminal Emulator works without root.
You can install Termux app on your android device and run Linux command by using that app
Install busybox, then type the command in the following format:
busybox [linux command]
You cannot use all the linux commands without busybox, because Android doesn't have all the binaries that are available in a standard linux operating system.
FYI, a binary is just a file that contains compiled code. A lot of the default binaries are stored in /system/bin/sh directory. All these commands like 'cp' 'ls' 'get' etc, are actually binaries. You can view them through:
ls -a /system/bin/sh
Hope this helps.
In reply to Igor Ganapolsky, You would have to have a database set up for locate.
Probably find would be adequate for your needs.
example:
find -name *.apk
We are trying to pre-install a NDK Application into the /system/app directory. If I open the apk file in a ZIP file manager, the .so file is inside the lib directory. However, when we preinstall the apk file, the apk's .so file is not copied to system/lib directory, causing for the application to fail when we launched it in the device.
Can anyone please tell me what should be set in the Android.mk for the APK file so that the .so file will be extracted from the APK file and copied to system/lib directory? We need to include the application in the system image.
Any feedback will be greatly appreciated.
Thanks,
artsylar
I had the same need and after 2 days of heavy research, I came up with a solution to this problem. It is not simple and requires you to be able to modify the Android System code as well.
Basically PackageManagerService prevents system applications to unpack their native binaries (.so files), unless they have been updated. So the only way to fix this is by modifying PMS.java (aptly named since trying to solve this problem put me in a terrible mood).
On the system's first boot, I check every system package for native binaries by writing a isPackageNative(PackageParser.Package pkg) function:
private boolean isPackageNative(PackageParser.Package pkg) throws IOException {
final ZipFile zipFile = new ZipFile(pkg.mPath);
final Enumeration<? extends ZipEntry> privateZipEntries = zipFile.entries();
while (privateZipEntries.hasMoreElements()) {
final ZipEntry zipEntry = privateZipEntries.nextElement();
final String zipEntryName = zipEntry.getName();
if(true) Log.e(TAG, " Zipfile entry:"+zipEntryName);
if (zipEntryName.endsWith(".so")) {
zipFile.close();
return true;
}
}
zipFile.close();
return false;
}
This function checks every package for a native library and if it has one, I unpack it. PMS does this check in scanPackageLI(....). Search for the following code in the method:
if (isSystemApp(pkg) && !isUpdatedSystemApp(pkg))
and add the isPackageNative(pkg) check. There are other small modifications required but you'll probably figure it out once you have this direction. Hope it helps!
I think you cannot do it by default as Android's /system partition is mounted as read-only! You need a rooted phone so as to mount the /system with write privileges through this command:
mount -o rw,remount -t yaffs2 /dev/block/mtdblock3 /system.
So, if you have a rooted phone you can add in your application this code:
Process p;
try {
// Preform su to get root privledges
p = Runtime.getRuntime().exec("su");
// Attempt to write a file to a root-only
DataOutputStream os = new DataOutputStream(p.getOutputStream());
// gain root privileges
os.writeBytes("mount -o rw,remount -t yaffs2 /dev/block/mtdblock3 /system\n");
// do here the copy operation you want in /system/lib file, for example:
os.writeBytes("mv /sdcard/mylib.so /system/lib/\n");
// Close the terminal
os.writeBytes("exit\n");
os.flush();
} catch (IOException e) {
toastMessage("could not get root access");
}
Otherwise, you have to follow the solution that digitalmouse12 gave..
You will have to "adb push" the .so file yourself. Also, you don't necessarily have to push your library into system/lib (the folder might deny you permission anyway). Most push it to data/app and then load by issuing
System.load("/data/app/<libName>.so");
There's probably documentation somewhere, but if you cannot find that, I would suggest identifying a pre-installed app with an associated jni library .so and examining the android sources or corresponding system image or update.zip to see how it's handled.
In other words, programming by example...