Repository: amitshekhariitbhu/Android-Debug-Database
Branch: master
Commit: bf149df61f03
Files: 108
Total size: 255.2 KB
Directory structure:
gitextract_t_j5_uvg/
├── .gitignore
├── CHANGELOG.md
├── CONTRIBUTING.md
├── LICENSE
├── README.md
├── build.gradle
├── debug-db/
│ ├── .gitignore
│ ├── build.gradle
│ ├── gradle.properties
│ ├── proguard-rules.pro
│ └── src/
│ ├── androidTest/
│ │ └── java/
│ │ └── com/
│ │ └── amitshekhar/
│ │ └── debug/
│ │ └── ExampleInstrumentedTest.java
│ ├── main/
│ │ ├── AndroidManifest.xml
│ │ ├── java/
│ │ │ └── com/
│ │ │ └── amitshekhar/
│ │ │ └── debug/
│ │ │ ├── DebugDBInitProvider.java
│ │ │ └── sqlite/
│ │ │ ├── DebugDBFactory.java
│ │ │ └── DebugSQLiteDB.java
│ │ └── res/
│ │ └── values/
│ │ └── strings.xml
│ └── test/
│ └── java/
│ └── com/
│ └── amitshekhar/
│ └── debug/
│ └── ExampleUnitTest.java
├── debug-db-base/
│ ├── build.gradle
│ ├── proguard-rules.pro
│ └── src/
│ ├── androidTest/
│ │ └── java/
│ │ └── com/
│ │ └── amitshekhar/
│ │ └── ExampleInstrumentedTest.java
│ ├── main/
│ │ ├── AndroidManifest.xml
│ │ ├── assets/
│ │ │ ├── app.js
│ │ │ ├── custom.css
│ │ │ ├── dataTables.altEditor.free.js
│ │ │ └── index.html
│ │ ├── java/
│ │ │ └── com/
│ │ │ └── amitshekhar/
│ │ │ ├── DebugDB.java
│ │ │ ├── model/
│ │ │ │ ├── Response.java
│ │ │ │ ├── RowDataRequest.java
│ │ │ │ ├── TableDataResponse.java
│ │ │ │ └── UpdateRowResponse.java
│ │ │ ├── server/
│ │ │ │ ├── ClientServer.java
│ │ │ │ └── RequestHandler.java
│ │ │ ├── sqlite/
│ │ │ │ ├── DBFactory.java
│ │ │ │ ├── InMemoryDebugSQLiteDB.java
│ │ │ │ └── SQLiteDB.java
│ │ │ └── utils/
│ │ │ ├── Constants.java
│ │ │ ├── ConverterUtils.java
│ │ │ ├── DataType.java
│ │ │ ├── DatabaseFileProvider.java
│ │ │ ├── DatabaseHelper.java
│ │ │ ├── NetworkUtils.java
│ │ │ ├── PrefHelper.java
│ │ │ ├── TableNameParser.java
│ │ │ └── Utils.java
│ │ └── res/
│ │ └── values/
│ │ └── strings.xml
│ └── test/
│ └── java/
│ └── com/
│ └── amitshekhar/
│ └── ExampleUnitTest.java
├── debug-db-encrypt/
│ ├── .gitignore
│ ├── build.gradle
│ ├── gradle.properties
│ ├── proguard-rules.pro
│ └── src/
│ ├── androidTest/
│ │ └── java/
│ │ └── com/
│ │ └── amitshekhar/
│ │ └── debug/
│ │ └── encrypt/
│ │ └── ExampleInstrumentedTest.java
│ ├── main/
│ │ ├── AndroidManifest.xml
│ │ ├── java/
│ │ │ └── com/
│ │ │ └── amitshekhar/
│ │ │ └── debug/
│ │ │ └── encrypt/
│ │ │ ├── DebugDBEncryptInitProvider.java
│ │ │ └── sqlite/
│ │ │ ├── DebugDBEncryptFactory.java
│ │ │ └── DebugEncryptSQLiteDB.java
│ │ └── res/
│ │ └── values/
│ │ └── strings.xml
│ └── test/
│ └── java/
│ └── com/
│ └── amitshekhar/
│ └── debug/
│ └── encrypt/
│ └── ExampleUnitTest.java
├── gradle/
│ └── wrapper/
│ ├── gradle-wrapper.jar
│ └── gradle-wrapper.properties
├── gradle.properties
├── gradlew
├── gradlew.bat
├── sample-app/
│ ├── build.gradle
│ ├── proguard-rules.pro
│ └── src/
│ ├── androidTest/
│ │ └── java/
│ │ └── com/
│ │ └── sample/
│ │ └── ExampleInstrumentedTest.java
│ ├── main/
│ │ ├── AndroidManifest.xml
│ │ ├── java/
│ │ │ └── com/
│ │ │ └── sample/
│ │ │ ├── MainActivity.java
│ │ │ ├── database/
│ │ │ │ ├── CarDBHelper.java
│ │ │ │ ├── ContactDBHelper.java
│ │ │ │ ├── ExtTestDBHelper.java
│ │ │ │ └── room/
│ │ │ │ ├── AppDatabase.java
│ │ │ │ ├── User.java
│ │ │ │ ├── UserDBHelper.java
│ │ │ │ └── UserDao.java
│ │ │ └── utils/
│ │ │ └── Utils.java
│ │ └── res/
│ │ ├── layout/
│ │ │ └── activity_main.xml
│ │ ├── values/
│ │ │ ├── colors.xml
│ │ │ ├── dimens.xml
│ │ │ ├── strings.xml
│ │ │ └── styles.xml
│ │ └── values-w820dp/
│ │ └── dimens.xml
│ └── test/
│ └── java/
│ └── com/
│ └── sample/
│ └── ExampleUnitTest.java
├── sample-app-encrypt/
│ ├── .gitignore
│ ├── build.gradle
│ ├── proguard-rules.pro
│ └── src/
│ ├── androidTest/
│ │ └── java/
│ │ └── com/
│ │ └── sample/
│ │ └── encrypt/
│ │ └── ExampleInstrumentedTest.java
│ ├── main/
│ │ ├── AndroidManifest.xml
│ │ ├── java/
│ │ │ └── com/
│ │ │ └── sample/
│ │ │ └── encrypt/
│ │ │ ├── MainActivity.java
│ │ │ ├── database/
│ │ │ │ ├── CarDBHelper.java
│ │ │ │ ├── ContactDBHelper.java
│ │ │ │ ├── ExtTestDBHelper.java
│ │ │ │ ├── PersonDBHelper.java
│ │ │ │ └── room/
│ │ │ │ ├── AppDatabase.java
│ │ │ │ ├── User.java
│ │ │ │ ├── UserDBHelper.java
│ │ │ │ └── UserDao.java
│ │ │ └── utils/
│ │ │ └── Utils.java
│ │ └── res/
│ │ ├── drawable/
│ │ │ └── ic_launcher_background.xml
│ │ ├── drawable-v24/
│ │ │ └── ic_launcher_foreground.xml
│ │ ├── layout/
│ │ │ └── activity_main.xml
│ │ ├── mipmap-anydpi-v26/
│ │ │ ├── ic_launcher.xml
│ │ │ └── ic_launcher_round.xml
│ │ └── values/
│ │ ├── colors.xml
│ │ ├── dimens.xml
│ │ ├── strings.xml
│ │ └── styles.xml
│ └── test/
│ └── java/
│ └── com/
│ └── sample/
│ └── encrypt/
│ └── ExampleUnitTest.java
└── settings.gradle
================================================
FILE CONTENTS
================================================
================================================
FILE: .gitignore
================================================
# Gradle files
.gradle/
build/
# Local configuration file (sdk path, etc)
local.properties
# Android Studio generated folders
captures/
.externalNativeBuild
# IntelliJ project files
*.iml
.idea/
# Misc
.DS_Store
================================================
FILE: CHANGELOG.md
================================================
Change Log
==========
Version 1.0.6 *(2019-03-07)*
----------------------------
* Fix: Fix query error
* Fix: Fix DebugDb class not found error
Version 1.0.5 *(2019-02-18)*
----------------------------
* Reduce size by taking out encrypted database library as a separate module
* New: Add support for database delete
* Changed compile to implementation
* Fix: Minor bug fixes
Version 1.0.4 *(2018-06-23)*
----------------------------
* Fix: Fix issue of Room Database
Version 1.0.3 *(2018-02-12)*
----------------------------
* New: Add support for debugging inMemory Room Database
* Add example for Room Database
Version 1.0.2 *(2018-01-08)*
----------------------------
* New: Add SqlCipher support
* New: List table name in non case sensitive alphabetical order
Version 1.0.1 *(2017-06-23)*
----------------------------
* New: Add insert row feature
* New: Add custom database files support
* New: Add method for checking isServerRunning
* New: Add pragma support
* Fix: Minor bug fixes
Version 1.0.0 *(2017-02-08)*
----------------------------
* New: Add support for editing database directly
* New: Delete rows directly
* New: Delete Shared Pref
* New: Edit shared preferences directly
* New: Add standard code for checking databases files
* New: Complete offline support
* Refactor library code
Version 0.5.0 *(2017-01-21)*
----------------------------
* New: Export DB
* New: Method to get DB version
* Fix: Fix proguard issue and other minor issues
Version 0.4.0 *(2016-11-29)*
----------------------------
* Optimizations
* Fix: Fix few minor bugs
Version 0.3.0 *(2016-11-23)*
----------------------------
* New: Add support for custom port
* Fix: Fix few minor bugs
Version 0.2.0 *(2016-11-17)*
----------------------------
* New: Add method for getting address
* Fix: Fix few minor bugs
Version 0.1.0 *(2016-11-16)*
----------------------------
Initial release.
================================================
FILE: CONTRIBUTING.md
================================================
# Contributing
1. Fork it!
2. Checkout the development branch: `git checkout development`
3. Create your feature branch: `git checkout -b my-new-feature`
4. Add your changes to the index: `git add .`
5. Commit your changes: `git commit -m 'Add some feature'`
6. Push to the branch: `git push origin my-new-feature`
7. Submit a pull request against the `development` branch
================================================
FILE: LICENSE
================================================
Apache License
Version 2.0, January 2004
http://www.apache.org/licenses/
TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
1. Definitions.
"License" shall mean the terms and conditions for use, reproduction,
and distribution as defined by Sections 1 through 9 of this document.
"Licensor" shall mean the copyright owner or entity authorized by
the copyright owner that is granting the License.
"Legal Entity" shall mean the union of the acting entity and all
other entities that control, are controlled by, or are under common
control with that entity. For the purposes of this definition,
"control" means (i) the power, direct or indirect, to cause the
direction or management of such entity, whether by contract or
otherwise, or (ii) ownership of fifty percent (50%) or more of the
outstanding shares, or (iii) beneficial ownership of such entity.
"You" (or "Your") shall mean an individual or Legal Entity
exercising permissions granted by this License.
"Source" form shall mean the preferred form for making modifications,
including but not limited to software source code, documentation
source, and configuration files.
"Object" form shall mean any form resulting from mechanical
transformation or translation of a Source form, including but
not limited to compiled object code, generated documentation,
and conversions to other media types.
"Work" shall mean the work of authorship, whether in Source or
Object form, made available under the License, as indicated by a
copyright notice that is included in or attached to the work
(an example is provided in the Appendix below).
"Derivative Works" shall mean any work, whether in Source or Object
form, that is based on (or derived from) the Work and for which the
editorial revisions, annotations, elaborations, or other modifications
represent, as a whole, an original work of authorship. For the purposes
of this License, Derivative Works shall not include works that remain
separable from, or merely link (or bind by name) to the interfaces of,
the Work and Derivative Works thereof.
"Contribution" shall mean any work of authorship, including
the original version of the Work and any modifications or additions
to that Work or Derivative Works thereof, that is intentionally
submitted to Licensor for inclusion in the Work by the copyright owner
or by an individual or Legal Entity authorized to submit on behalf of
the copyright owner. For the purposes of this definition, "submitted"
means any form of electronic, verbal, or written communication sent
to the Licensor or its representatives, including but not limited to
communication on electronic mailing lists, source code control systems,
and issue tracking systems that are managed by, or on behalf of, the
Licensor for the purpose of discussing and improving the Work, but
excluding communication that is conspicuously marked or otherwise
designated in writing by the copyright owner as "Not a Contribution."
"Contributor" shall mean Licensor and any individual or Legal Entity
on behalf of whom a Contribution has been received by Licensor and
subsequently incorporated within the Work.
2. Grant of Copyright License. Subject to the terms and conditions of
this License, each Contributor hereby grants to You a perpetual,
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
copyright license to reproduce, prepare Derivative Works of,
publicly display, publicly perform, sublicense, and distribute the
Work and such Derivative Works in Source or Object form.
3. Grant of Patent License. Subject to the terms and conditions of
this License, each Contributor hereby grants to You a perpetual,
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
(except as stated in this section) patent license to make, have made,
use, offer to sell, sell, import, and otherwise transfer the Work,
where such license applies only to those patent claims licensable
by such Contributor that are necessarily infringed by their
Contribution(s) alone or by combination of their Contribution(s)
with the Work to which such Contribution(s) was submitted. If You
institute patent litigation against any entity (including a
cross-claim or counterclaim in a lawsuit) alleging that the Work
or a Contribution incorporated within the Work constitutes direct
or contributory patent infringement, then any patent licenses
granted to You under this License for that Work shall terminate
as of the date such litigation is filed.
4. Redistribution. You may reproduce and distribute copies of the
Work or Derivative Works thereof in any medium, with or without
modifications, and in Source or Object form, provided that You
meet the following conditions:
(a) You must give any other recipients of the Work or
Derivative Works a copy of this License; and
(b) You must cause any modified files to carry prominent notices
stating that You changed the files; and
(c) You must retain, in the Source form of any Derivative Works
that You distribute, all copyright, patent, trademark, and
attribution notices from the Source form of the Work,
excluding those notices that do not pertain to any part of
the Derivative Works; and
(d) If the Work includes a "NOTICE" text file as part of its
distribution, then any Derivative Works that You distribute must
include a readable copy of the attribution notices contained
within such NOTICE file, excluding those notices that do not
pertain to any part of the Derivative Works, in at least one
of the following places: within a NOTICE text file distributed
as part of the Derivative Works; within the Source form or
documentation, if provided along with the Derivative Works; or,
within a display generated by the Derivative Works, if and
wherever such third-party notices normally appear. The contents
of the NOTICE file are for informational purposes only and
do not modify the License. You may add Your own attribution
notices within Derivative Works that You distribute, alongside
or as an addendum to the NOTICE text from the Work, provided
that such additional attribution notices cannot be construed
as modifying the License.
You may add Your own copyright statement to Your modifications and
may provide additional or different license terms and conditions
for use, reproduction, or distribution of Your modifications, or
for any such Derivative Works as a whole, provided Your use,
reproduction, and distribution of the Work otherwise complies with
the conditions stated in this License.
5. Submission of Contributions. Unless You explicitly state otherwise,
any Contribution intentionally submitted for inclusion in the Work
by You to the Licensor shall be under the terms and conditions of
this License, without any additional terms or conditions.
Notwithstanding the above, nothing herein shall supersede or modify
the terms of any separate license agreement you may have executed
with Licensor regarding such Contributions.
6. Trademarks. This License does not grant permission to use the trade
names, trademarks, service marks, or product names of the Licensor,
except as required for reasonable and customary use in describing the
origin of the Work and reproducing the content of the NOTICE file.
7. Disclaimer of Warranty. Unless required by applicable law or
agreed to in writing, Licensor provides the Work (and each
Contributor provides its Contributions) on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
implied, including, without limitation, any warranties or conditions
of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
PARTICULAR PURPOSE. You are solely responsible for determining the
appropriateness of using or redistributing the Work and assume any
risks associated with Your exercise of permissions under this License.
8. Limitation of Liability. In no event and under no legal theory,
whether in tort (including negligence), contract, or otherwise,
unless required by applicable law (such as deliberate and grossly
negligent acts) or agreed to in writing, shall any Contributor be
liable to You for damages, including any direct, indirect, special,
incidental, or consequential damages of any character arising as a
result of this License or out of the use or inability to use the
Work (including but not limited to damages for loss of goodwill,
work stoppage, computer failure or malfunction, or any and all
other commercial damages or losses), even if such Contributor
has been advised of the possibility of such damages.
9. Accepting Warranty or Additional Liability. While redistributing
the Work or Derivative Works thereof, You may choose to offer,
and charge a fee for, acceptance of support, warranty, indemnity,
or other liability obligations and/or rights consistent with this
License. However, in accepting such obligations, You may act only
on Your own behalf and on Your sole responsibility, not on behalf
of any other Contributor, and only if You agree to indemnify,
defend, and hold each Contributor harmless for any liability
incurred by, or claims asserted against, such Contributor by reason
of your accepting any such warranty or additional liability.
END OF TERMS AND CONDITIONS
APPENDIX: How to apply the Apache License to your work.
To apply the Apache License to your work, attach the following
boilerplate notice, with the fields enclosed by brackets "[]"
replaced with your own identifying information. (Don't include
the brackets!) The text should be enclosed in the appropriate
comment syntax for the file format. We also recommend that a
file or class name and description of purpose be included on the
same "printed page" as the copyright notice for easier
identification within third-party archives.
Copyright [yyyy] [name of copyright owner]
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
================================================
FILE: README.md
================================================
# Android Debug Database
## Android Debug Database is a powerful library for debugging databases and shared preferences in Android applications
### Android Debug Database allows you to view databases and shared preferences directly in your browser in a very simple way
### What can Android Debug Database do?
* See all the databases.
* See all the data in the shared preferences used in your application.
* Run any sql query on the given database to update and delete your data.
* Directly edit the database values.
* Directly edit the shared preferences.
* Directly add a row in the database.
* Directly add a key-value in the shared preferences.
* Delete database rows and shared preferences.
* Search in your data.
* Sort data.
* Download database.
* Debug Room inMemory database.
## About me
Hi, I am Amit Shekhar, Founder @ [Outcome School](https://outcomeschool.com) • IIT 2010-14 • I have taught and mentored many developers, and their efforts landed them high-paying tech jobs, helped many tech companies in solving their unique problems, and created many open-source libraries being used by top companies. I am passionate about sharing knowledge through open-source, blogs, and videos.
### Follow Amit Shekhar
- [X/Twitter](https://twitter.com/amitiitbhu)
- [LinkedIn](https://www.linkedin.com/in/amit-shekhar-iitbhu)
- [GitHub](https://github.com/amitshekhariitbhu)
### Follow Outcome School
- [YouTube](https://youtube.com/@OutcomeSchool)
- [X/Twitter](https://x.com/outcome_school)
- [LinkedIn](https://www.linkedin.com/company/outcomeschool)
- [GitHub](http://github.com/OutcomeSchool)
## I teach at Outcome School
- [AI and Machine Learning](https://outcomeschool.com/program/ai-and-machine-learning)
- [Android](https://outcomeschool.com/program/android)
Join Outcome School and get a high-paying tech job: [Outcome School](https://outcomeschool.com)
## [Outcome School Blog](https://outcomeschool.com/blog) - High-quality content to learn Android concepts.
### All these features work without rooting your device -> No need of rooted device
### Using Android Debug Database Library in your application
Add this in your `settings.gradle`:
```groovy
maven { url 'https://jitpack.io' }
```
If you are using `settings.gradle.kts`, add the following:
```kotlin
maven { setUrl("https://jitpack.io") }
```
Add this in your `build.gradle`
```groovy
debugImplementation 'com.github.amitshekhariitbhu.Android-Debug-Database:debug-db:1.0.7'
```
If you are using `build.gradle.kts`, add the following:
```kotlin
debugImplementation("com.github.amitshekhariitbhu.Android-Debug-Database:debug-db:1.0.7")
```
Using the Android Debug Database with encrypted database
Add this in your `build.gradle`
```groovy
debugImplementation 'com.github.amitshekhariitbhu.Android-Debug-Database:debug-db-encrypt:1.0.7'
```
If you are using `build.gradle.kts`, add the following:
```kotlin
debugImplementation("com.github.amitshekhariitbhu.Android-Debug-Database:debug-db-encrypt:1.0.7")
```
And to provide the password for the DB, you should add this in the Gradle:
DB_PASSWORD_{VARIABLE}, if for example, PERSON is the database name: DB_PASSWORD_PERSON
```groovy
debug {
resValue("string", "DB_PASSWORD_PERSON", "password")
}
```
Use `debugImplementation` so that it will only compile in your debug build and not in your release build.
That’s all, just start the application, you will see in the logcat an entry like follows :
* D/DebugDB: Open http://XXX.XXX.X.XXX:8080 in your browser
* You can also always get the debug address url from your code by calling the method `DebugDB.getAddressLog();`
Now open the provided link in your browser.
Important:
* Your Android phone and laptop should be connected to the same Network (Wifi or LAN).
* If you are using it over usb, run `adb forward tcp:8080 tcp:8080`
Note : If you want use different port other than 8080.
In the app build.gradle file under buildTypes do the following change
```groovy
debug {
resValue("string", "PORT_NUMBER", "8081")
}
```
You will see something like this :
### Seeing values
### Editing values
### Working with emulator
* Android Default Emulator: Run the command in the terminal - `adb forward tcp:8080 tcp:8080` and open http://localhost:8080
* Genymotion Emulator: Enable bridge from configure virtual device (option available in genymotion)
### Getting address with toast, in case you missed the address log in logcat
As this library is auto-initialize, if you want to get the address log, add the following method and call (we have to do like this to avoid build error in release build as this library will not be included in the release build) using reflection.
```java
public static void showDebugDBAddressLogToast(Context context) {
if (BuildConfig.DEBUG) {
try {
Class> debugDB = Class.forName("com.amitshekhar.DebugDB");
Method getAddressLog = debugDB.getMethod("getAddressLog");
Object value = getAddressLog.invoke(null);
Toast.makeText(context, (String) value, Toast.LENGTH_LONG).show();
} catch (Exception ignore) {
}
}
}
```
### Adding custom database files
As this library is auto-initialize, if you want to debug custom database files, add the following method and call
```java
public static void setCustomDatabaseFiles(Context context) {
if (BuildConfig.DEBUG) {
try {
Class> debugDB = Class.forName("com.amitshekhar.DebugDB");
Class[] argTypes = new Class[]{HashMap.class};
Method setCustomDatabaseFiles = debugDB.getMethod("setCustomDatabaseFiles", argTypes);
HashMap> customDatabaseFiles = new HashMap<>();
// set your custom database files
customDatabaseFiles.put(ExtTestDBHelper.DATABASE_NAME,
new Pair<>(new File(context.getFilesDir() + "/" + ExtTestDBHelper.DIR_NAME +
"/" + ExtTestDBHelper.DATABASE_NAME), ""));
setCustomDatabaseFiles.invoke(null, customDatabaseFiles);
} catch (Exception ignore) {
}
}
}
```
### Adding InMemory Room databases
As this library is auto-initialize, if you want to debug inMemory Room databases, add the following method and call
```java
public static void setInMemoryRoomDatabases(SupportSQLiteDatabase... database) {
if (BuildConfig.DEBUG) {
try {
Class> debugDB = Class.forName("com.amitshekhar.DebugDB");
Class[] argTypes = new Class[]{HashMap.class};
HashMap inMemoryDatabases = new HashMap<>();
// set your inMemory databases
inMemoryDatabases.put("InMemoryOne.db", database[0]);
Method setRoomInMemoryDatabase = debugDB.getMethod("setInMemoryRoomDatabases", argTypes);
setRoomInMemoryDatabase.invoke(null, inMemoryDatabases);
} catch (Exception ignore) {
}
}
}
```
### Find this project useful ? :heart:
* Support it by clicking the :star: button on the upper right of this page. :v:
### TODO
* Simplify emulator issue [Issue Link](https://github.com/amitshekhariitbhu/Android-Debug-Database/issues/6)
* And of course many more features and bug fixes.
You can connect with me on:
- [Twitter](https://twitter.com/amitiitbhu)
- [LinkedIn](https://www.linkedin.com/in/amit-shekhar-iitbhu)
- [GitHub](https://github.com/amitshekhariitbhu)
- [Facebook](https://www.facebook.com/amit.shekhar.iitbhu)
[**Read all of our blogs here.**](https://outcomeschool.com/blog)
### License
```
Copyright (C) 2024 Amit Shekhar
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
```
### Contributing to Android Debug Database
All pull requests are welcome, make sure to follow the [contribution guidelines](CONTRIBUTING.md)
when you submit pull request.
================================================
FILE: build.gradle
================================================
/*
*
* * Copyright (C) 2019 Amit Shekhar
* * Copyright (C) 2011 Android Open Source Project
* *
* * Licensed under the Apache License, Version 2.0 (the "License");
* * you may not use this file except in compliance with the License.
* * You may obtain a copy of the License at
* *
* * http://www.apache.org/licenses/LICENSE-2.0
* *
* * Unless required by applicable law or agreed to in writing, software
* * distributed under the License is distributed on an "AS IS" BASIS,
* * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* * See the License for the specific language governing permissions and
* * limitations under the License.
*
*/
// Top-level build file where you can add configuration options common to all sub-projects/modules.
plugins {
id 'com.android.application' version '7.3.0' apply false
id 'com.android.library' version '7.3.0' apply false
}
task clean(type: Delete) {
delete rootProject.buildDir
}
ext {
compileSdk = 33
targetSdk = 33
minSdk = 14
}
================================================
FILE: debug-db/.gitignore
================================================
/build
================================================
FILE: debug-db/build.gradle
================================================
apply plugin: 'com.android.library'
android {
compileSdk rootProject.ext.compileSdk
defaultConfig {
minSdk rootProject.ext.minSdk
targetSdk rootProject.ext.targetSdk
versionCode 1
versionName "1.0"
testInstrumentationRunner "androidx.test.runner.AndroidJUnitRunner"
}
buildTypes {
release {
minifyEnabled false
proguardFiles getDefaultProguardFile('proguard-android-optimize.txt'), 'proguard-rules.pro'
}
}
}
dependencies {
api project(':debug-db-base')
testImplementation 'junit:junit:4.13.2'
androidTestImplementation 'androidx.test:runner:1.5.2'
androidTestImplementation 'androidx.test.espresso:espresso-core:3.4.0'
}
================================================
FILE: debug-db/gradle.properties
================================================
ARTIFACT_ID=debug-db
================================================
FILE: debug-db/proguard-rules.pro
================================================
# Add project specific ProGuard rules here.
# You can control the set of applied configuration files using the
# proguardFiles setting in build.gradle.
#
# For more details, see
# http://developer.android.com/guide/developing/tools/proguard.html
# If your project uses WebView with JS, uncomment the following
# and specify the fully qualified class name to the JavaScript interface
# class:
#-keepclassmembers class fqcn.of.javascript.interface.for.webview {
# public *;
#}
# Uncomment this to preserve the line number information for
# debugging stack traces.
#-keepattributes SourceFile,LineNumberTable
# If you keep the line number information, uncomment this to
# hide the original source file name.
#-renamesourcefileattribute SourceFile
================================================
FILE: debug-db/src/androidTest/java/com/amitshekhar/debug/ExampleInstrumentedTest.java
================================================
package com.amitshekhar.debug;
import android.content.Context;
import android.support.test.InstrumentationRegistry;
import android.support.test.runner.AndroidJUnit4;
import org.junit.Test;
import org.junit.runner.RunWith;
import static org.junit.Assert.*;
/**
* Instrumented test, which will execute on an Android device.
*
* @see Testing documentation
*/
@RunWith(AndroidJUnit4.class)
public class ExampleInstrumentedTest {
@Test
public void useAppContext() {
// Context of the app under test.
Context appContext = InstrumentationRegistry.getTargetContext();
assertEquals("com.amitshekhar.debug.test", appContext.getPackageName());
}
}
================================================
FILE: debug-db/src/main/AndroidManifest.xml
================================================
================================================
FILE: debug-db/src/main/java/com/amitshekhar/debug/DebugDBInitProvider.java
================================================
/*
*
* * Copyright (C) 2019 Amit Shekhar
* * Copyright (C) 2011 Android Open Source Project
* *
* * Licensed under the Apache License, Version 2.0 (the "License");
* * you may not use this file except in compliance with the License.
* * You may obtain a copy of the License at
* *
* * http://www.apache.org/licenses/LICENSE-2.0
* *
* * Unless required by applicable law or agreed to in writing, software
* * distributed under the License is distributed on an "AS IS" BASIS,
* * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* * See the License for the specific language governing permissions and
* * limitations under the License.
*
*/
package com.amitshekhar.debug;
import android.content.ContentProvider;
import android.content.ContentValues;
import android.content.Context;
import android.content.pm.ProviderInfo;
import android.database.Cursor;
import android.net.Uri;
import com.amitshekhar.DebugDB;
import com.amitshekhar.debug.sqlite.DebugDBFactory;
/**
* Created by amitshekhar on 16/11/16.
*/
public class DebugDBInitProvider extends ContentProvider {
public DebugDBInitProvider() {
}
@Override
public boolean onCreate() {
DebugDB.initialize(getContext(), new DebugDBFactory());
return true;
}
@Override
public Cursor query(Uri uri, String[] projection, String selection, String[] selectionArgs, String sortOrder) {
return null;
}
@Override
public String getType(Uri uri) {
return null;
}
@Override
public Uri insert(Uri uri, ContentValues values) {
return null;
}
@Override
public int delete(Uri uri, String selection, String[] selectionArgs) {
return 0;
}
@Override
public int update(Uri uri, ContentValues values, String selection, String[] selectionArgs) {
return 0;
}
@Override
public void attachInfo(Context context, ProviderInfo providerInfo) {
if (providerInfo == null) {
throw new NullPointerException("DebugDBInitProvider ProviderInfo cannot be null.");
}
// So if the authorities equal the library internal ones, the developer forgot to set his applicationId
if ("com.amitshekhar.debug.DebugDBInitProvider".equals(providerInfo.authority)) {
throw new IllegalStateException("Incorrect provider authority in manifest. Most likely due to a "
+ "missing applicationId variable in application\'s build.gradle.");
}
super.attachInfo(context, providerInfo);
}
}
================================================
FILE: debug-db/src/main/java/com/amitshekhar/debug/sqlite/DebugDBFactory.java
================================================
package com.amitshekhar.debug.sqlite;
import android.content.Context;
import android.database.sqlite.SQLiteDatabase;
import com.amitshekhar.sqlite.DBFactory;
import com.amitshekhar.sqlite.SQLiteDB;
public class DebugDBFactory implements DBFactory {
@Override
public SQLiteDB create(Context context, String path, String password) {
return new DebugSQLiteDB(SQLiteDatabase.openOrCreateDatabase(path, null));
}
}
================================================
FILE: debug-db/src/main/java/com/amitshekhar/debug/sqlite/DebugSQLiteDB.java
================================================
package com.amitshekhar.debug.sqlite;
import android.content.ContentValues;
import android.database.Cursor;
import android.database.SQLException;
import android.database.sqlite.SQLiteDatabase;
import com.amitshekhar.sqlite.SQLiteDB;
public class DebugSQLiteDB implements SQLiteDB {
private final SQLiteDatabase database;
public DebugSQLiteDB(SQLiteDatabase database) {
this.database = database;
}
@Override
public int delete(String table, String whereClause, String[] whereArgs) {
return database.delete(table, whereClause, whereArgs);
}
@Override
public boolean isOpen() {
return database.isOpen();
}
@Override
public void close() {
database.close();
}
@Override
public Cursor rawQuery(String sql, String[] selectionArgs) {
return database.rawQuery(sql, selectionArgs);
}
@Override
public void execSQL(String sql) throws SQLException {
database.execSQL(sql);
}
@Override
public long insert(String table, String nullColumnHack, ContentValues values) {
return database.insert(table, nullColumnHack, values);
}
@Override
public int update(String table, ContentValues values, String whereClause, String[] whereArgs) {
return database.update(table, values, whereClause, whereArgs);
}
@Override
public int getVersion() {
return database.getVersion();
}
}
================================================
FILE: debug-db/src/main/res/values/strings.xml
================================================
debug-db
================================================
FILE: debug-db/src/test/java/com/amitshekhar/debug/ExampleUnitTest.java
================================================
package com.amitshekhar.debug;
import org.junit.Test;
import static org.junit.Assert.*;
/**
* Example local unit test, which will execute on the development machine (host).
*
* @see Testing documentation
*/
public class ExampleUnitTest {
@Test
public void addition_isCorrect() {
assertEquals(4, 2 + 2);
}
}
================================================
FILE: debug-db-base/build.gradle
================================================
/*
*
* * Copyright (C) 2019 Amit Shekhar
* * Copyright (C) 2011 Android Open Source Project
* *
* * Licensed under the Apache License, Version 2.0 (the "License");
* * you may not use this file except in compliance with the License.
* * You may obtain a copy of the License at
* *
* * http://www.apache.org/licenses/LICENSE-2.0
* *
* * Unless required by applicable law or agreed to in writing, software
* * distributed under the License is distributed on an "AS IS" BASIS,
* * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* * See the License for the specific language governing permissions and
* * limitations under the License.
*
*/
apply plugin: 'com.android.library'
android {
compileSdk rootProject.ext.compileSdk
defaultConfig {
minSdk rootProject.ext.minSdk
targetSdk rootProject.ext.targetSdk
versionCode 1
versionName "1.0"
testInstrumentationRunner "androidx.test.runner.AndroidJUnitRunner"
resValue("string", "PORT_NUMBER", "8080")
}
buildTypes {
release {
minifyEnabled false
proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
}
}
}
dependencies {
implementation 'com.google.code.gson:gson:2.8.5'
implementation "androidx.room:room-runtime:2.5.0"
testImplementation 'junit:junit:4.13.2'
androidTestImplementation 'androidx.test:runner:1.5.2'
androidTestImplementation 'androidx.test.espresso:espresso-core:3.4.0'
}
================================================
FILE: debug-db-base/proguard-rules.pro
================================================
# Add project specific ProGuard rules here.
# You can control the set of applied configuration files using the
# proguardFiles setting in build.gradle.
#
# For more details, see
# http://developer.android.com/guide/developing/tools/proguard.html
# If your project uses WebView with JS, uncomment the following
# and specify the fully qualified class name to the JavaScript interface
# class:
#-keepclassmembers class fqcn.of.javascript.interface.for.webview {
# public *;
#}
# Uncomment this to preserve the line number information for
# debugging stack traces.
-keepattributes SourceFile,LineNumberTable
# If you keep the line number information, uncomment this to
# hide the original source file name.
-renamesourcefileattribute SourceFile
-keepparameternames
-keepattributes Exceptions,InnerClasses,Signature,Deprecated,EnclosingMethod
# Preserve all annotations.
-keepattributes *Annotation*
# Preserve all public classes, and their public and protected fields and
# methods.
-keep public class * {
public protected *;
}
# Preserve all .class method names.
-keepclassmembernames class * {
java.lang.Class class$(java.lang.String);
java.lang.Class class$(java.lang.String, boolean);
}
# Preserve all native method names and the names of their classes.
-keepclasseswithmembernames class * {
native ;
}
# Preserve the special static methods that are required in all enumeration
# classes.
-keepclassmembers class * extends java.lang.Enum {
public static **[] values();
public static ** valueOf(java.lang.String);
}
# Explicitly preserve all serialization members. The Serializable interface
# is only a marker interface, so it wouldn't save them.
# You can comment this out if your library doesn't use serialization.
# If your code contains serializable classes that have to be backward
# compatible, please refer to the manual.
-keepclassmembers class * implements java.io.Serializable {
static final long serialVersionUID;
static final java.io.ObjectStreamField[] serialPersistentFields;
private void writeObject(java.io.ObjectOutputStream);
private void readObject(java.io.ObjectInputStream);
java.lang.Object writeReplace();
java.lang.Object readResolve();
}
# Your library may contain more items that need to be preserved;
# typically classes that are dynamically created using Class.forName:
# -keep public class mypackage.MyClass
# -keep public interface mypackage.MyInterface
# -keep public class * implements mypackage.MyInterface
================================================
FILE: debug-db-base/src/androidTest/java/com/amitshekhar/ExampleInstrumentedTest.java
================================================
/*
*
* * Copyright (C) 2019 Amit Shekhar
* * Copyright (C) 2011 Android Open Source Project
* *
* * Licensed under the Apache License, Version 2.0 (the "License");
* * you may not use this file except in compliance with the License.
* * You may obtain a copy of the License at
* *
* * http://www.apache.org/licenses/LICENSE-2.0
* *
* * Unless required by applicable law or agreed to in writing, software
* * distributed under the License is distributed on an "AS IS" BASIS,
* * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* * See the License for the specific language governing permissions and
* * limitations under the License.
*
*/
package com.amitshekhar;
import android.content.Context;
import android.support.test.InstrumentationRegistry;
import android.support.test.runner.AndroidJUnit4;
import org.junit.Test;
import org.junit.runner.RunWith;
import static org.junit.Assert.*;
/**
* Instrumentation test, which will execute on an Android device.
*
* @see Testing documentation
*/
@RunWith(AndroidJUnit4.class)
public class ExampleInstrumentedTest {
@Test
public void useAppContext() throws Exception {
// Context of the app under test.
Context appContext = InstrumentationRegistry.getTargetContext();
assertEquals("com.amitshekhar.test", appContext.getPackageName());
}
}
================================================
FILE: debug-db-base/src/main/AndroidManifest.xml
================================================
================================================
FILE: debug-db-base/src/main/assets/app.js
================================================
$( document ).ready(function() {
getDBList();
$("#query").keypress(function(e){
if(e.which == 13) {
queryFunction();
}
});
//update currently selected database
$( document ).on( "click", "#db-list .list-group-item", function() {
$("#db-list .list-group-item").each(function() {
$(this).removeClass('selected');
});
$(this).addClass('selected');
});
//update currently table database
$( document ).on( "click", "#table-list .list-group-item", function() {
$("#table-list .list-group-item").each(function() {
$(this).removeClass('selected');
});
$(this).addClass('selected');
});
});
var isDatabaseSelected = true;
function getData(tableName) {
$.ajax({url: "getAllDataFromTheTable?tableName="+tableName, success: function(result){
result = JSON.parse(result);
inflateData(result);
}});
}
function queryFunction() {
var query = $('#query').val();
$.ajax({url: "query?query="+escape(query), success: function(result){
result = JSON.parse(result);
inflateData(result);
}});
}
function downloadDb() {
if (isDatabaseSelected) {
$.ajax({url: "downloadDb", success: function(){
window.location = 'downloadDb';
}});
}
}
function deleteDb() {
if (isDatabaseSelected) {
$.ajax({url: "deleteDb", success: function(result){
result = JSON.parse(result);
if(result.isSuccessful){
console.log("Database deleted successfully");
showSuccessInfo("Database Deleted Successfully");
getDBList();
} else {
console.log("Database delete failed");
showErrorInfo("Database Delete Failed");
}
}});
}
}
function getDBList() {
$.ajax({url: "getDbList", success: function(result){
result = JSON.parse(result);
var dbList = result.rows;
$('#db-list').empty();
var isSelectionDone = false;
for(var count = 0; count < dbList.length; count++){
var dbName = dbList[count][0];
var isEncrypted = dbList[count][1];
var isDownloadable = dbList[count][2];
var dbAttribute = isEncrypted == "true" ? ' ' : "";
if(dbName.indexOf("journal") == -1 && dbName.indexOf("-wal") == -1 && dbName.indexOf("-shm") == -1){
$("#db-list").append("" + dbName + dbAttribute + "");
if(!isSelectionDone){
isSelectionDone = true;
$('#db-list').find('a').trigger('click');
}
}
}
}});
}
var lastTableName = getHashValue('table');
function openDatabaseAndGetTableList(db, isDownloadable) {
if("APP_SHARED_PREFERENCES" == db) {
$('#run-query').removeClass('active');
$('#run-query').addClass('disabled');
$('#selected-db-download').removeClass('active');
$('#selected-db-delete').removeClass('active');
$('#selected-db-download').addClass('disabled');
$('#selected-db-delete').addClass('disabled');
isDatabaseSelected = false;
$("#selected-db-info").text("SharedPreferences");
} else {
$('#run-query').removeClass('disabled');
$('#run-query').addClass('active');
$("#selected-db-info").text("Selected Database : "+db);
if("true" == isDownloadable) {
$('#selected-db-download').addClass('active');
$('#selected-db-delete').addClass('active');
$('#selected-db-download').removeClass('disabled');
$('#selected-db-delete').removeClass('disabled');
} else {
$('#selected-db-download').removeClass('active');
$('#selected-db-delete').removeClass('active');
$('#selected-db-download').addClass('disabled');
$('#selected-db-delete').addClass('disabled');
}
isDatabaseSelected = true;
}
$.ajax({url: "getTableList?database="+db, success: function(result){
result = JSON.parse(result);
var tableList = result.rows;
var dbVersion = result.dbVersion;
if("APP_SHARED_PREFERENCES" != db) {
$("#selected-db-info").text("Selected Database : "+db +" Version : "+dbVersion);
}
$('#table-list').empty()
for(var count = 0; count < tableList.length; count++){
var tableName = tableList[count];
$("#table-list").append("" + tableName + "");
}
if (lastTableName !== null) {
$('a[data-table-name=' + lastTableName + ']').trigger('click');
}
}});
}
function inflateData(result){
if(result.isSuccessful){
if(!result.isSelectQuery){
showSuccessInfo("Query Executed Successfully");
return;
}
var columnHeader = result.tableInfos;
// set function to return cell data for different usages like set, display, filter, search etc..
for(var i = 0; i < columnHeader.length; i++) {
columnHeader[i]['targets'] = i;
columnHeader[i]['data'] = function(row, type, val, meta) {
var dataType = row[meta.col].dataType;
if (type == "sort" && dataType == "boolean") {
return row[meta.col].value ? 1 : 0;
}
return row[meta.col].value;
}
}
var columnData = result.rows;
var tableId = "#db-data";
if ($.fn.DataTable.isDataTable(tableId) ) {
$(tableId).DataTable().destroy();
}
$("#db-data-div").remove();
$("#parent-data-div").append('
');
var availableButtons;
if (result.isEditable) {
availableButtons = [
{
text : 'Add',
name : 'add' // don not change name
},
{
extend: 'selected', // Bind to Selected row
text: 'Edit',
name: 'edit' // do not change name
},
{
extend: 'selected',
text: 'Delete',
name: 'delete'
}
];
} else {
availableButtons = [];
}
$(tableId).dataTable({
"data": columnData,
"columnDefs": columnHeader,
'bPaginate': true,
'searching': true,
'bFilter': true,
'bInfo': true,
"bSort" : true,
"scrollX": true,
"iDisplayLength": 10,
"dom": "Bfrtip",
select: 'single',
altEditor: true, // Enable altEditor
buttons: availableButtons
})
//attach row-updated listener
$(tableId).on('update-row.dt', function (e, updatedRowData, callback) {
var updatedRowDataArray = JSON.parse(updatedRowData);
//add value for each column
var data = columnHeader;
for(var i = 0; i < data.length; i++) {
data[i].value = updatedRowDataArray[i].value;
data[i].dataType = updatedRowDataArray[i].dataType;
}
//send update table data request to server
updateTableData(data, callback);
});
//attach delete-updated listener
$(tableId).on('delete-row.dt', function (e, updatedRowData, callback) {
var deleteRowDataArray = JSON.parse(updatedRowData);
console.log(deleteRowDataArray);
//add value for each column
var data = columnHeader;
for(var i = 0; i < data.length; i++) {
data[i].value = deleteRowDataArray[i].value;
data[i].dataType = deleteRowDataArray[i].dataType;
}
//send delete table data request to server
deleteTableData(data, callback);
});
$(tableId).on('add-row.dt', function (e, updatedRowData, callback) {
var deleteRowDataArray = JSON.parse(updatedRowData);
console.log(deleteRowDataArray);
//add value for each column
var data = columnHeader;
for(var i = 0; i < data.length; i++) {
data[i].value = deleteRowDataArray[i].value;
data[i].dataType = deleteRowDataArray[i].dataType;
}
//send delete table data request to server
addTableData(data, callback);
});
// hack to fix alignment issue when scrollX is enabled
$(".dataTables_scrollHeadInner").css({"width":"100%"});
$(".table ").css({"width":"100%"});
}else{
if(!result.isSelectQuery){
showErrorInfo("Query Execution Failed");
}else {
showErrorInfo("Some Error Occurred");
}
}
}
//send update database request to server
function updateTableData(updatedData, callback) {
//get currently selected element
var selectedTableElement = $("#table-list .list-group-item.selected");
var filteredUpdatedData = updatedData.map(function(columnData){
return {
title: columnData.title,
isPrimary: columnData.isPrimary,
value: columnData.value,
dataType: columnData.dataType
}
});
//build request parameters
var requestParameters = {};
requestParameters.dbName = selectedTableElement.attr('data-db-name');
requestParameters.tableName = selectedTableElement.attr('data-table-name');;
requestParameters.updatedData = encodeURIComponent(JSON.stringify(filteredUpdatedData));
//execute request
$.ajax({
url: "updateTableData",
type: 'GET',
data: requestParameters,
success: function(response) {
response = JSON.parse(response);
if(response.isSuccessful){
console.log("Data updated successfully");
callback(true);
showSuccessInfo("Data Updated Successfully");
} else {
console.log("Data updated failed");
callback(false);
}
}
})
}
function deleteTableData(deleteData, callback) {
var selectedTableElement = $("#table-list .list-group-item.selected");
var filteredUpdatedData = deleteData.map(function(columnData){
return {
title: columnData.title,
isPrimary: columnData.isPrimary,
value: columnData.value,
dataType: columnData.dataType
}
});
//build request parameters
var requestParameters = {};
requestParameters.dbName = selectedTableElement.attr('data-db-name');
requestParameters.tableName = selectedTableElement.attr('data-table-name');;
requestParameters.deleteData = encodeURIComponent(JSON.stringify(filteredUpdatedData));
//execute request
$.ajax({
url: "deleteTableData",
type: 'GET',
data: requestParameters,
success: function(response) {
response = JSON.parse(response);
if(response.isSuccessful){
console.log("Data deleted successfully");
callback(true);
showSuccessInfo("Data Deleted Successfully");
} else {
console.log("Data delete failed");
callback(false);
}
}
})
}
function addTableData(deleteData, callback) {
var selectedTableElement = $("#table-list .list-group-item.selected");
var filteredUpdatedData = deleteData.map(function(columnData){
return {
title: columnData.title,
isPrimary: columnData.isPrimary,
value: columnData.value,
dataType: columnData.dataType
}
});
console.log(filteredUpdatedData);
//build request parameters
var requestParameters = {};
requestParameters.dbName = selectedTableElement.attr('data-db-name');
requestParameters.tableName = selectedTableElement.attr('data-table-name');;
requestParameters.addData = encodeURIComponent(JSON.stringify(filteredUpdatedData));
console.log(requestParameters);
//execute request
$.ajax({
url: "addTableData",
type: 'GET',
data: requestParameters,
success: function(response) {
response = JSON.parse(response);
if(response.isSuccessful){
console.log("Data Added successfully");
callback(true);
getData(requestParameters.tableName);
showSuccessInfo("Data Added Successfully");
} else {
console.log("Data Adding failed");
callback(false);
}
}
});
}
function showSuccessInfo(message){
var snackbarId = "snackbar";
var snackbarElement = $("#"+snackbarId);
snackbarElement.addClass("show");
snackbarElement.css({"backgroundColor": "#5cb85c"});
snackbarElement.html(message)
setTimeout(function(){
snackbarElement.removeClass("show");
}, 3000);
}
function showErrorInfo(message){
var snackbarId = "snackbar";
var snackbarElement = $("#"+snackbarId);
snackbarElement.addClass("show");
snackbarElement.css({"backgroundColor": "#d9534f"});
snackbarElement.html(message)
setTimeout(function(){
snackbarElement.removeClass("show");
}, 3000);
}
function getHashValue(key) {
var matches = location.hash.match(new RegExp(key + '=([^&]*)'));
return matches ? matches[1] : null;
}
================================================
FILE: debug-db-base/src/main/assets/custom.css
================================================
.padding-fifty {
padding-top: 50px;
}
.padding-twenty {
padding-top: 20px;
}
.display-none {
display: none;
}
.list-group-item {
word-break: break-all;
}
.list-group-item.selected {
background: #dff0d8 !important;
color: #3c763d !important;
font-weight: bold;
}
#snackbar {
visibility: hidden;
min-width: 250px;
margin-left: -125px;
background-color: #5cb85c;
color: #fff;
text-align: center;
border-radius: 2px;
padding: 16px;
position: fixed;
z-index: 1;
left: 50%;
bottom: 30px;
font-size: 17px;
}
#snackbar.show {
visibility: visible;
-webkit-animation: fadein 0.5s, fadeout 0.5s 2.5s;
animation: fadein 0.5s, fadeout 0.5s 2.5s;
}
@-webkit-keyframes fadein {
from {bottom: 0; opacity: 0;}
to {bottom: 30px; opacity: 1;}
}
@keyframes fadein {
from {bottom: 0; opacity: 0;}
to {bottom: 30px; opacity: 1;}
}
@-webkit-keyframes fadeout {
from {bottom: 30px; opacity: 1;}
to {bottom: 0; opacity: 0;}
}
================================================
FILE: debug-db-base/src/main/assets/dataTables.altEditor.free.js
================================================
/*! Datatables altEditor 1.0
*/
/**
* @summary altEditor
* @description Lightweight editor for DataTables
* @version 1.0
* @file dataTables.editor.lite.js
* @author kingkode (www.kingkode.com)
* @contact www.kingkode.com/contact
* @copyright Copyright 2016 Kingkode
*
* This source file is free software, available under the following license:
* MIT license - http://datatables.net/license/mit
*
* This source file is distributed in the hope that it will be useful, but
* WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY
* or FITNESS FOR A PARTICULAR PURPOSE. See the license files for details.
*
* For details please refer to: http://www.kingkode.com
*/
(function(factory) {
if (typeof define === 'function' && define.amd) {
// AMD
define(['jquery', 'datatables.net'], function($) {
return factory($, window, document);
});
} else if (typeof exports === 'object') {
// CommonJS
module.exports = function(root, $) {
if (!root) {
root = window;
}
if (!$ || !$.fn.dataTable) {
$ = require('datatables.net')(root, $).$;
}
return factory($, root, root.document);
};
} else {
// Browser
factory(jQuery, window, document);
}
}(function($, window, document, undefined) {
'use strict';
var DataTable = $.fn.dataTable;
var _instance = 0;
/**
* altEditor provides modal editing of records for Datatables
*
* @class altEditor
* @constructor
* @param {object} oTD DataTables settings object
* @param {object} oConfig Configuration object for altEditor
*/
var altEditor = function(dt, opts) {
if (!DataTable.versionCheck || !DataTable.versionCheck('1.10.8')) {
throw ("Warning: altEditor requires DataTables 1.10.8 or greater");
}
// User and defaults configuration object
this.c = $.extend(true, {},
DataTable.defaults.altEditor,
altEditor.defaults,
opts
);
/**
* @namespace Settings object which contains customisable information for altEditor instance
*/
this.s = {
/** @type {DataTable.Api} DataTables' API instance */
dt: new DataTable.Api(dt),
/** @type {String} Unique namespace for events attached to the document */
namespace: '.altEditor' + (_instance++)
};
/**
* @namespace Common and useful DOM elements for the class instance
*/
this.dom = {
/** @type {jQuery} altEditor handle */
modal: $(''),
};
/* Constructor logic */
this._constructor();
}
$.extend(altEditor.prototype, {
/* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *
* Constructor
* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * */
/**
* Initialise the RowReorder instance
*
* @private
*/
_constructor: function() {
// console.log('altEditor Enabled')
var that = this;
var dt = this.s.dt;
this._setup();
dt.on('destroy.altEditor', function() {
dt.off('.altEditor');
$(dt.table().body()).off(that.s.namespace);
$(document.body).off(that.s.namespace);
});
},
/* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *
* Private methods
* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * */
/**
* Setup dom and bind button actions
*
* @private
*/
_setup: function() {
// console.log('Setup');
var that = this;
var dt = this.s.dt;
// add modal
$('body').append('\
\
\
\
\
\
\
\
\
\
\
\
\
\
');
// add Edit Button
if (this.s.dt.button('edit:name')) {
this.s.dt.button('edit:name').action(function(e, dt, node, config) {
var rows = dt.rows({
selected: true
}).count();
that._openEditModal();
});
$(document).on('click', '#editRowBtn', function(e) {
e.preventDefault();
e.stopPropagation();
that._editRowData();
});
}
// add Delete Button
if (this.s.dt.button('delete:name')) {
this.s.dt.button('delete:name').action(function(e, dt, node, config) {
var rows = dt.rows({
selected: true
}).count();
that._openDeleteModal();
});
$(document).on('click', '#deleteRowBtn', function(e) {
e.preventDefault();
e.stopPropagation();
that._deleteRow();
});
}
// add Add Button
if (this.s.dt.button('add:name')) {
this.s.dt.button('add:name').action(function(e, dt, node, config) {
var rows = dt.rows({
selected: true
}).count();
that._openAddModal();
});
$(document).on('click', '#addRowBtn', function(e) {
e.preventDefault();
e.stopPropagation();
that._addRowData();
});
}
},
/**
* Emit an event on the DataTable for listeners
*
* @param {string} name Event name
* @param {array} args Event arguments
* @private
*/
_emitEvent: function(name, args) {
this.s.dt.iterator('table', function(ctx, i) {
$(ctx.nTable).triggerHandler(name + '.dt', args);
});
},
/**
* Open Edit Modal for selected row
*
* @private
*/
_openEditModal: function() {
var that = this;
var dt = this.s.dt;
var columnDefs = [];
for (var i = 0; i < dt.context[0].aoColumns.length; i++) {
columnDefs.push({
title: dt.context[0].aoColumns[i].sTitle,
dataType: dt.context[0].aoColumns[i].dataType,
isPrimary: dt.context[0].aoColumns[i].isPrimary,
})
}
var adata = dt.rows({
selected: true
});
var data = "";
data += "";
$('#altEditor-modal').on('show.bs.modal', function() {
$('#altEditor-modal').find('.modal-title').html('Edit Record');
$('#altEditor-modal').find('.modal-body').html('
' + data + '
');
$('#altEditor-modal').find('.modal-footer').html("\
");
});
$('#altEditor-modal').modal('show');
$('#altEditor-modal input[0]').focus();
},
_editRowData: function() {
var that = this;
var dt = this.s.dt;
var data = [];
$('form[name="altEditor-form"] input').each(function(i) {
var addToList = true;
var value = $(this).val();
if($(this).attr('type') == "radio" && $(this).prop('checked') == false) {
addToList = false;
}
value = $(this).attr('type') == "radio" ? $(this).val() == "1" : value;
if (addToList){
data.push({
"value": value,
"dataType": $(this).attr('data-type')
});
}
});
var editButtonCurrentText = $("#editRowBtn").text();
$("#editRowBtn").addClass('disabled');
$("#editRowBtn").text("Saving..");
that._emitEvent("update-row", [
JSON.stringify(data),
function(isUpdated) {
//set error message and other properties based on whether update is successfull or not
var alertAdditionClasses = "alert-success";
var alertMessage = "This record has been updated";
var alertHeading = "Success";
if (!isUpdated) {
alertAdditionClasses = "alert-danger";
alertMessage = "Error occurred while updating this record";
alertHeading = "Error";
}
//create alert element html and append it to modal
var messageHTML = '\
\
__ALERT_HEADING__!\
__ALERT_MESSAGE__.\
\
';
messageHTML = messageHTML.replace(/__ALERT_ADDITION_CLASSES__/g, alertAdditionClasses);
messageHTML = messageHTML.replace(/__ALERT_HEADING__/g, alertHeading);
messageHTML = messageHTML.replace(/__ALERT_MESSAGE__/g, alertMessage);
$('#altEditor-modal .modal-body').append(messageHTML);
//update datatable, if update is successfull
if (isUpdated) {
dt.row({
selected: true
}).data(data);
//remove existing alert elements
$('#altEditor-modal').modal('hide');
}
$("#editRowBtn").removeClass('disabled');
$("#editRowBtn").text(editButtonCurrentText);
}
]);
},
/**
* Open Delete Modal for selected row
*
* @private
*/
_openDeleteModal: function() {
var that = this;
var dt = this.s.dt;
var columnDefs = [];
for (var i = 0; i < dt.context[0].aoColumns.length; i++) {
columnDefs.push({
title: dt.context[0].aoColumns[i].sTitle
})
}
var adata = dt.rows({
selected: true
});
var data = "";
data += "";
$('#altEditor-modal').on('show.bs.modal', function() {
$('#altEditor-modal').find('.modal-title').html('Delete Record');
$('#altEditor-modal').find('.modal-body').html('
' + data + '
');
$('#altEditor-modal').find('.modal-footer').html("\
");
});
$('#altEditor-modal').modal('show');
$('#altEditor-modal input[0]').focus();
},
_deleteRow: function() {
var that = this;
var dt = this.s.dt;
var data = [];
$('form[name="altEditor-form"] input').each(function(i) {
var addToList = true;
var value = $(this).val();
value = $(this).val();
console.log("Value : " + value);
if (addToList){
data.push({
"value": value,
"dataType": $(this).attr('data-type')
});
}
});
$('#altEditor-modal .modal-body .alert').remove();
var message = '
\
Success! This record has been deleted.\
';
$('#altEditor-modal .modal-body').append(message);
that._emitEvent("delete-row", [
JSON.stringify(data),
function(isDeleted) {
if (isDeleted) {
dt.row({
selected: true
}).remove();
dt.draw();
}
//remove existing alert elements
$('#altEditor-modal').modal('hide');
}
]);
},
/**
* Open Add Modal for selected row
*
* @private
*/
_openAddModal: function() {
var that = this;
var dt = this.s.dt;
var columnDefs = [];
for (var i = 0; i < dt.context[0].aoColumns.length; i++) {
columnDefs.push({
title: dt.context[0].aoColumns[i].sTitle,
dataType: dt.context[0].aoColumns[i].sType,
isPrimary: dt.context[0].aoColumns[i].isPrimary,
value : "",
})
}
var data = "";
data += "";
$('#altEditor-modal').on('show.bs.modal', function() {
$('#altEditor-modal').find('.modal-title').html('Add Record');
$('#altEditor-modal').find('.modal-body').html('
' + data + '
');
$('#altEditor-modal').find('.modal-footer').html("\
");
});
$('#altEditor-modal').modal('show');
$('#altEditor-modal input[0]').focus();
},
_addRowData: function() {
console.log('add row')
var that = this;
var dt = this.s.dt;
var data = [];
$('form[name="altEditor-form"] input').each(function(i) {
var addToList = true;
var value = $(this).val();
if($(this).attr('type') == "radio" && $(this).prop('checked') == false) {
addToList = false;
}
value = $(this).attr('type') == "radio" ? $(this).val() == "1" : value;
if (addToList){
data.push({
"value": value,
"dataType": $(this).attr('data-type')
});
}
});
var editButtonCurrentText = $("#editRowBtn").text();
$("#addRowBtn").addClass('disabled');
$("#addRowBtn").text("Saving..");
console.log(JSON.stringify(data));
that._emitEvent("add-row", [
JSON.stringify(data),
function(isAdded) {
//set error message and other properties based on whether update is successfull or not
var alertAdditionClasses = "alert-success";
var alertMessage = "This record has been added";
var alertHeading = "Success";
if (!isAdded) {
alertAdditionClasses = "alert-danger";
alertMessage = "Error occurred while adding this record";
alertHeading = "Error";
}
//create alert element html and append it to modal
var messageHTML = '\
\
__ALERT_HEADING__!\
__ALERT_MESSAGE__.\
\
';
messageHTML = messageHTML.replace(/__ALERT_ADDITION_CLASSES__/g, alertAdditionClasses);
messageHTML = messageHTML.replace(/__ALERT_HEADING__/g, alertHeading);
messageHTML = messageHTML.replace(/__ALERT_MESSAGE__/g, alertMessage);
$('#altEditor-modal .modal-body').append(messageHTML);
//update datatable, if update is successfull
if (isAdded) {
dt.row().data(data);
//remove existing alert elements
$('#altEditor-modal').modal('hide');
}
$("#addRowBtn").removeClass('disabled');
$("#addRowBtn").text(editButtonCurrentText);
}
]);
},
_getExecutionLocationFolder: function() {
var fileName = "dataTables.altEditor.js";
var scriptList = $("script[src]");
var jsFileObject = $.grep(scriptList, function(el) {
if (el.src.indexOf(fileName) !== -1) {
return el;
}
});
var jsFilePath = jsFileObject[0].src;
var jsFileDirectory = jsFilePath.substring(0, jsFilePath.lastIndexOf("/") + 1);
return jsFileDirectory;
}
});
/**
* altEditor version
*
* @static
* @type String
*/
altEditor.version = '1.0';
/**
* altEditor defaults
*
* @namespace
*/
altEditor.defaults = {
/** @type {Boolean} Ask user what they want to do, even for a single option */
alwaysAsk: false,
/** @type {string|null} What will trigger a focus */
focus: null, // focus, click, hover
/** @type {column-selector} Columns to provide auto fill for */
columns: '', // all
/** @type {boolean|null} Update the cells after a drag */
update: null, // false is editor given, true otherwise
/** @type {DataTable.Editor} Editor instance for automatic submission */
editor: null
};
/**
* Classes used by altEditor that are configurable
*
* @namespace
*/
altEditor.classes = {
/** @type {String} Class used by the selection button */
btn: 'btn'
};
// Attach a listener to the document which listens for DataTables initialisation
// events so we can automatically initialise
$(document).on('preInit.dt.altEditor', function(e, settings, json) {
if (e.namespace !== 'dt') {
return;
}
var init = settings.oInit.altEditor;
var defaults = DataTable.defaults.altEditor;
if (init || defaults) {
var opts = $.extend({}, init, defaults);
if (init !== false) {
new altEditor(settings, opts);
}
}
});
// Alias for access
DataTable.altEditor = altEditor;
return altEditor;
}));
================================================
FILE: debug-db-base/src/main/assets/index.html
================================================
Android Debug Database
Databases
Tables
Data
Data Updated Successfully
================================================
FILE: debug-db-base/src/main/java/com/amitshekhar/DebugDB.java
================================================
/*
*
* * Copyright (C) 2019 Amit Shekhar
* * Copyright (C) 2011 Android Open Source Project
* *
* * Licensed under the Apache License, Version 2.0 (the "License");
* * you may not use this file except in compliance with the License.
* * You may obtain a copy of the License at
* *
* * http://www.apache.org/licenses/LICENSE-2.0
* *
* * Unless required by applicable law or agreed to in writing, software
* * distributed under the License is distributed on an "AS IS" BASIS,
* * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* * See the License for the specific language governing permissions and
* * limitations under the License.
*
*/
package com.amitshekhar;
import android.content.Context;
import android.util.Log;
import android.util.Pair;
import androidx.sqlite.db.SupportSQLiteDatabase;
import com.amitshekhar.server.ClientServer;
import com.amitshekhar.sqlite.DBFactory;
import com.amitshekhar.utils.NetworkUtils;
import java.io.File;
import java.util.HashMap;
/**
* Created by amitshekhar on 15/11/16.
*/
public class DebugDB {
private static final String TAG = DebugDB.class.getSimpleName();
private static final int DEFAULT_PORT = 8080;
private static ClientServer clientServer;
private static String addressLog = "not available";
private DebugDB() {
// This class in not publicly instantiable
}
public static void initialize(Context context, DBFactory dbFactory) {
int portNumber;
try {
portNumber = Integer.valueOf(context.getString(R.string.PORT_NUMBER));
} catch (NumberFormatException ex) {
Log.e(TAG, "PORT_NUMBER should be integer", ex);
portNumber = DEFAULT_PORT;
Log.i(TAG, "Using Default port : " + DEFAULT_PORT);
}
clientServer = new ClientServer(context, portNumber, dbFactory);
clientServer.start();
addressLog = NetworkUtils.getAddressLog(context, portNumber);
Log.d(TAG, addressLog);
}
public static String getAddressLog() {
Log.d(TAG, addressLog);
return addressLog;
}
public static void shutDown() {
if (clientServer != null) {
clientServer.stop();
clientServer = null;
}
}
public static void setCustomDatabaseFiles(HashMap> customDatabaseFiles) {
if (clientServer != null) {
clientServer.setCustomDatabaseFiles(customDatabaseFiles);
}
}
public static void setInMemoryRoomDatabases(HashMap databases) {
if (clientServer != null) {
clientServer.setInMemoryRoomDatabases(databases);
}
}
public static boolean isServerRunning() {
return clientServer != null && clientServer.isRunning();
}
}
================================================
FILE: debug-db-base/src/main/java/com/amitshekhar/model/Response.java
================================================
/*
*
* * Copyright (C) 2019 Amit Shekhar
* * Copyright (C) 2011 Android Open Source Project
* *
* * Licensed under the Apache License, Version 2.0 (the "License");
* * you may not use this file except in compliance with the License.
* * You may obtain a copy of the License at
* *
* * http://www.apache.org/licenses/LICENSE-2.0
* *
* * Unless required by applicable law or agreed to in writing, software
* * distributed under the License is distributed on an "AS IS" BASIS,
* * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* * See the License for the specific language governing permissions and
* * limitations under the License.
*
*/
package com.amitshekhar.model;
import java.util.ArrayList;
import java.util.List;
/**
* Created by amitshekhar on 15/11/16.
*/
public class Response {
public List