Showing posts with label sqlite. Show all posts
Showing posts with label sqlite. Show all posts

Monday, September 17, 2018

Error when reading from pre-populated SQLite database in Ionic project

Leave a Comment

I'm receiving an error when I try to read from a pre-populated SQLite database: sqlite3_prepare_v2 failure: no such table 'plant'

From what I understand SQLite looks for the mydb.db file in the /www folder by default, then creates an empty database when it doesn't find the pre-populated mydb.db file. This is why it can't find the 'plant' table, because the newly created blank database obviously doesn't contain a 'plant' table. However I can confirm that the database is in the /www folder, and that it contains the 'plant' table when I run sqlite3 mydb.db then .tables in the terminal.

I can't figure out why it's not reading from the pre-populated mydb.db file.

Folder structure (from root):

/src -/app --/app.component.ts /www -/mydb.db 

app.component.ts:

  constructor(public platform: Platform, private sqlite: SQLite ) {     platform.ready().then(() => {       this.getData();     });   }    getData() {     this.sqlite.create({       name: 'mydb.db',       location: 'default'     }).then((db: SQLiteObject) => {       db.executeSql('SELECT * FROM plant ORDER BY id ASC', [])       .then(res => {         // Do Stuff       }).catch(e => console.log("FAIL executeSql:", e));     })   } 

I've attempted many fixes that I've found on StackOverflow, like wiping the app from my device, starting a new ionic project then copying app and config files over, and setting a direct path in the database location, but it still keeps trying to read from the empty database that it creates.

1 Answers

Answers 1

The Cordova-sqlite-storage plugin does not handle prepopulated databases (as of this writing). I believe you need the Cordova-sqlite-ext plugin.

From the README.md at the repo (emphasis mine):

New release in September 2018 will include the following major enhancements (litehelpers/Cordova-sqlite-storage#773):

  • browser platform support using kripken / sql.js (litehelpers/Cordova-sqlite-storage#576)

  • cordova-sqlite-storage and cordova-sqlite-ext plugin versions will be combined, no more separate plugin version needed for pre-populated databases (litehelpers/Cordova-sqlite-storage#529)

  • include typings from DefinitelyTyped (litehelpers/Cordova-sqlite-storage#768)

NB. The "will" include is the operative.

There is a similar question on the ionic forum. The last post in the thread starts:

Cordova SQLite Storage doesn’t use your app’s www folder to store data.

Mobile devices don’t allow for app executables’ data to be modified. This is to prevent installing an app that overwrites code in another app (imagine installing WhatsApp and it corrupts all other messaging apps so you can’t use them). It also makes it impossible for code to be injected into the app and take over the OS if your app security isn’t great.

The post goes on with a proposed workaround.

Another thread on the ionic forum seems to indicate that you can use cordova-sqlite-ext in your app. You could search that forum for cordova-sqlite-ext, there are several posters that have it working. There are also many results for cordova-sqlite-ext on this forum that could get you in the right direction.

And to be honest, I do not think it is actually creating an empty database. Unless "/www/mydb.db" is an empty database after you run the app (which would surprise me). While it's true that sqlite will create the database named at the command line if it doesn't exist, I suspect that in this case it is just the behaviour when it cannot access the named database.

Read More

Sunday, August 12, 2018

Migrate SQLite Database from Titanium to Ionic in iOS App

Leave a Comment

I am updating the app store with an Ionic version of an old Titanium/Alloy app. The Alloy sql.js sync adapter has:

var ALLOY_DB_DEFAULT = "_alloy_"; 

A backup of a phone running the old app made with iExplorer contains the file:

(App)/Library/Private Documents/_alloy_.sql 

Can I access this database like this in Ionic?

    db = window.sqlitePlugin.openDatabase({       name: '_alloy_.sql',       location: 1,     }) 

I am trying to run the old app and test the migration, but Titanium Studio is very difficult to get going at this point. My migration works well if I just stuff the old _alloy_.sql file into the iOS Simulator at:

~/Library/Developer/CoreSimulator/Devices/<id>/data/Containers/Data/Application/<id>/Library/ 

1 Answers

Answers 1

Old thread response, hopefully someone still finds the answer useful.

We've solved our own bounty.

The database is stored in the IOS Library in the 'Private Data' directory with the filename _alloy_.sql

let tiAppOptions = {name: "Private Documents/_alloy_.sql", iosDatabaseLocation: 'Library'};  this.sqlite.create(tiAppOptions).then((db: SQLiteObject) => {     db.executeSql("SELECT * from table_name", {}).then((data) => {         //do something with the data.     }); }, err => {    console.log(err); }); 

Android is stored in the 'default' location with filename _alloy_.sql

Read More

Saturday, July 28, 2018

ionic executeSql doesn't work

Leave a Comment

I actually try to make an mobile app with SQLite. I juste try to create two tables:

constructor(private sqlite:SQLite,public modalCtrl: ModalController,public navCtrl: NavController, private navParam: NavParams, private databaseprovider: DatabaseProvider, private employeesProvider: EmployeeProvider) {     this.createDetabaseFile(); }  private createDetabaseFile() : void {     this.sqlite.create({           name: DATABASE_FILE_NAME,           location: 'default'     }).then((dbRes: SQLiteObject) => {         alert("bdd créée");         this.db = dbRes;         this.createTables();     }) }  private createTables() : void {     this.db.executeSql('CREATE table IF NOT EXISTS  symbole(id INTEGER NOT NULL ,name TEXT)',{})         .then(() => {             alert("table symbole created");             this.db.executeSql('CREATE table IF NOT EXISTS representationPhoto(name VARCHAR(32))',{})                 .then(() => {                     alert("table representationPhoto created");                 })             .catch(e => alert("erreur creation table"));         })         .catch(e => alert("erreur creation table")); } 

And db.executeSql() seem not working, indeed, the alert("table symbole created"); don't appear, however alert("bdd créée") appear, and the program don't triggered the catch.

Have you an idea?

ps: sorry for my bad english

2 Answers

Answers 1

Kindly try declaring db variable above createDetabaseFile function it seems to me the problem because you are using this.db without declaring it in the class scope.

Try doing this:

public db: any; // above createDetabaseFile function 

Answers 2

You're missing platform ready block before handling SQLite.Try this:

import { Platform } from 'ionic-angular'; constructor(private platform: Platform, ...other imports) {  this.platform.ready().then(() => {   this.createDetabaseFile();  }) } 
Read More

Friday, June 29, 2018

Inter-App Data Migration (migrating data to new app version)

Leave a Comment

I currently have a Swift iOS app on Apple's App Store. I have many users and I would like to make a new version and help current users migrate to the new version. FYI: the new version is an Ionic app.

Data-wise, my app is using Core Data without any iCloud or sync support. It contains JSON data and also multiple images. So I'd need to bundle the current data and find a way of bringing it to the new ionic app version.

Basically my question is: Is there a way of writing in the app's documents directory and let the new version grab that file to import its data? Is there a way of letting both apps transmit data other than AirDrop or Custom URLs?

I don't want to upload the data remotely, I'd like to do this all locally on the device and also seamlessly so the user don't have to manually do anything.

Suggestions are welcome, thanks!

2 Answers

Answers 1

I would have just left a comment but I am unable to do so.

I was able to see that after loading a native iOS application then a Ionic project with the same bundle structure that the data within Library/Application Support/DisplayName.sqlite was still there and the data within the database still intact. (Note: this is deploying using Xcode not through the App Store)

You can see this using Xcode -> Window -> Devices and Simulators -> Devices tab -> Click on your app -> settings cog -> Download container -> after saving Show package contents

I was unable to use the Ionic SQLite native plugin to open the database for some reason. That is as far as I could get. I think it might have something to do with the space of the Application Support folder.

Answers 2

You can do the transition without using AirDrop or Custom Url. The idea is based on how ionic works. Much of the ionic functionality depends upon the plugins developed by community like working with hardware features.

Dealing with device specific features are done in native codes then JS wrapper classes are created for making a bridge between your code and native code.

I would suggest you to write native code which will access the data and files from CoreData and then use the cordova plugin tech to setup communication between the native code and the ionic code. here is a good post on Creating Custom Plugin for ionic and a sample github project

Read More

Thursday, June 7, 2018

Error printing plot extracted from SQLite blob

Leave a Comment

I have a workflow where I need to generate some data in R, generate plots for the data, save the plots, then render them later. I am using SQLite for this. It works fine, but only for ggplot2 plots. When I try to save and re-render base R plots, it does not work. Any ideas? Using R version 3.3.0. Here is my code:

library("ggplot2") library("RSQLite")  # test data dat <- data.frame(x = rnorm(50, 1, 6), y = rnorm(50, 1, 8))  # make ggplot g <- ggplot(dat, aes(x = x, y = y)) + geom_point()  # make base plot pdf("test.pdf") # need open graphics device to record plot headlessly dev.control(displaylist="enable") plot(dat) p <- serialize(recordPlot(), NULL) dev.off()  # make data frame for db insertion df1 <- data.frame(baseplot = I(list(p)), ggplot = I(list(serialize(g, NULL))))  # setup db con <- dbConnect(SQLite(), ":memory:") dbGetQuery(con, 'create table graphs (baseplot blob, ggplot blob)')  # insert the data dbGetPreparedQuery(con, 'insert into graphs (baseplot, ggplot) values (:baseplot, :ggplot)',                     bind.data=df1)  # get the data back out df2 <- dbGetQuery(con, "select * from graphs")  # print the ggplot; not sure why I need 'lapply' for this to work... lapply(df2[["ggplot"]][1], "unserialize")  # print the base plot lapply(df2[["baseplot"]][1], "unserialize") # Error: NULL value passed as symbol address 

1 Answers

Answers 1

Partial answer to record my findings: I cannot say why this is happening, but this is not related to sqlite. The same error occurs right after serializing the plot:

dat <- data.frame(x = rnorm(50, 1, 6), y = rnorm(50, 1, 8))  pdf("test.pdf") # need open graphics device to record plot headlessly dev.control(displaylist="enable") plot(dat) p <- serialize(recordPlot(), NULL) dev.off()  unserialize(p) # !! Error: NULL value passed as symbol address 
Read More

Thursday, January 18, 2018

Faster sqlite 3 query in go? I need to process 1million+ rows as fast as possible

Leave a Comment

What's the fastest way to read a sqlite3 table in golang?

package main  import (     "fmt"     "database/sql"     _ "github.com/mattn/go-sqlite3"     "log"     "time" )  func main() {     start := time.Now()      db, err := sql.Open("sqlite3", "/Users/robertking/go/src/bitbucket.org/thematicanalysis/optimization_test/robs.db")     if err != nil {         log.Fatal(err)     }     defer db.Close()     rows, err := db.Query("select * from data")     if err != nil {         log.Fatal(err)     }     defer rows.Close()      for rows.Next() {     }     err = rows.Err()     if err != nil {         log.Fatal(err)     }     fmt.Println(time.Since(start)) } 

This takes 8 seconds in Go because .Next is slow. In python a fetchall takes only 4 seconds! I'm rewriting in GO to gain performance not lose performance.

Here is the python code, I couldn't find an equivalent of fetchall in go:

import time  start = time.time() import sqlite3 conn = sqlite3.connect('/Users/robertking/go/src/bitbucket.org/thematicanalysis/optimization_test/robs.db') c = conn.cursor() c.execute("SELECT * FROM data") x = c.fetchall() print time.time() - start 

Edit: adding bounty. I'm reading the data in go, python and C, here are results. Dont want to use C, but will stick with python if GO isnt faster.:

py: 2.45s go: 2.13s (using github.com/mxk/go-sqlite/sqlite3 instead of github.com/mattn/go-sqlite3) c:  0.32s 

I feel like go should be closer to the c side of thing? anyone know how to make it faster? is it possible to avoid mutex with readonly mode?

edit:

It seems like all the sqlite3 implementations are slow (too much reflection and too many cgo calls for conversions). So i'll have to just write my own interface.

Here's the schema:

CREATE TABLE mytable (   c0   REAL,   c1   INTEGER,   c15  TEXT,   c16  TEXT,   c17  TEXT,   c18  TEXT,   c19  TEXT,   c47  TEXT,   c74  REAL DEFAULT 0,   c77  TEXT,   c101 TEXT,   c103 TEXT,   c108 TEXT,   c110 TEXT,   c125 TEXT,   c126 TEXT,   c127 REAL DEFAULT 0,   x    INTEGER     PRIMARY KEY ); 

and the query is dynamic but usually something like this:

SELECT c77,c77,c125,c126,c127,c74 from mytable 

edit:

looks like i'll fork the sqlite3 implementation and make some methods that focus on performance,

this is an example of some code which is much faster:.

package main   /*  #cgo LDFLAGS: -l sqlite3  #include "sqlite3.h" */ import "C"  import (     //"database/sql"     "log"     "reflect"     "unsafe" )  type Row struct {     v77 string     v125 string     v126 string     v127 float64     v74 float64 }  // cStr returns a pointer to the first byte in s. func cStr(s string) *C.char {     h := (*reflect.StringHeader)(unsafe.Pointer(&s))     return (*C.char)(unsafe.Pointer(h.Data)) }  func main() {     getDataFromSqlite() }  func getDataFromSqlite() {     var db *C.sqlite3     name := "../data_dbs/all_columns.db"     rc := C.sqlite3_open_v2(cStr(name+"\x00"), &db, C.SQLITE_OPEN_READONLY, nil)    var stmt *C.sqlite3_stmt;   rc = C.sqlite3_prepare_v2(db, cStr("SELECT c77,c125,c126,c127,c74 from data\x00"), C.int(-1), &stmt, nil);   rc = C.sqlite3_reset(stmt);      var result C.double     result = 0.0     rc = C.sqlite3_step(stmt)     for rc == C.SQLITE_ROW {     C.GoString((*C.char)(unsafe.Pointer(C.sqlite3_column_text(stmt, 0))))     C.GoString((*C.char)(unsafe.Pointer(C.sqlite3_column_text(stmt, 1))))     C.GoString((*C.char)(unsafe.Pointer(C.sqlite3_column_text(stmt, 2))))     C.sqlite3_column_double(stmt, 3)     result += C.sqlite3_column_double(stmt, 4)         rc = C.sqlite3_step(stmt)   }     log.Println(result) } 

2 Answers

Answers 1

Introduction

My assumption was that we have a problem with how the performance is measured here, so I wrote a little Go program to generate records and save them into a SQLite database as well as a Python and Go implementation of a little task to do on those records.

You can find the according repository at https://github.com/mwmahlberg/sqlite3perf

The data model

The records generated consist of

The table's schema is relatively simple:

sqlite> .schema CREATE TABLE bench (ID int PRIMARY KEY ASC, rand TEXT, hash TEXT); 

First I generated 1.5M records and vacuumed the sqlite database afterwards with

$ ./sqlite3perf generate -r 1500000 -v 

Next I called the Go implementation against those 1.5M records. Both the Go as well as the Python implementation basically do the same simple task:

  1. Read all entries from the database.
  2. For each row, decode the random value from hex, then create a SHA256 hex from the result.
  3. Compare the generated SHA256 hex string against the one stored in the database
  4. If they match, continue, otherwise break.

Assumptions

My assumption explicitly was that Python did some type of lazy loading and/or possibly even execution of the SQL query.

The results

Go implementation

$ ./sqlite3perf bench 2017/12/31 15:21:48 bench called 2017/12/31 15:21:48 Time after query: 4.824009ms 2017/12/31 15:21:48 Beginning loop 2017/12/31 15:21:48 Acessing the first result set      ID 0,     rand: 6a8a4ad02e5e872a,     hash: 571f1053a7c2aaa56e5c076e69389deb4db46cc08f5518c66a4bc593e62b9aa4 took 548.32µs 2017/12/31 15:21:50 641,664 rows processed 2017/12/31 15:21:52 1,325,186 rows processed 2017/12/31 15:21:53 1,500,000 rows processed 2017/12/31 15:21:53 Finished loop after 4.519083493s 2017/12/31 15:21:53 Average 3.015µs per record, 4.523936078s overall 

Note the values for "time after query" ( the time the query command took to return) and the time it took to access the first result set after the iteration over the result set was started.

Python implementation

$ python bench.py  12/31/2017 15:25:41 Starting up 12/31/2017 15:25:41 Time after query: 1874µs 12/31/2017 15:25:41 Beginning loop 12/31/2017 15:25:44 Accessing first result set     ID: 0     rand: 6a8a4ad02e5e872a     hash: 571f1053a7c2aaa56e5c076e69389deb4db46cc08f5518c66a4bc593e62b9aa4 took 2.719312 s 12/31/2017 15:25:50 Finished loop after 9.147431s 12/31/2017 15:25:50 Average: 6.098µs per record, 0:00:09.149522 overall 

Again, note the value for "time after query" and the time it took to access the first result set.

Summary

It took the Go implementation quite a while to return after the SELECT query was send, while Python seemed to be blazing fast in comparison. However, from the time it took to actually access the first result set, we can see that the Go implementation is more than 500 times faster to actually access the first result set (5.372329ms vs 2719.312ms) and about double as fast for the task at hand as the Python implementation.

Notes

  • In order to prove the assumption that Python actually does lazy loading on the result set, each and every row and column had to be accessed in order to make sure that Python is forced to actually read the value from the database.
  • I chose a hashing task because presumably the implementation of SHA256 is highly optimised in both languages.

Conclusion

Python does seem to do lazy loading of result sets and possibly does not even execute a query unless the according result set is actually accessed. In this simulated scenario, mattn's SQLite driver for Go outperforms Python's by between roughly 100% and orders of magnitude, depending on what you want to do.

Edit: So in order to have a fast processing, implement your task in Go. While it takes longer to send the actual query, accessing the individual rows of the result set is by far faster. I'd suggest starting out with a small subset of your data, say 50k records. Then, to further improve your code, use profiling to identify your bottlenecks. Depending on what you want to do during processing, pipelines for example might help, but how to improve the processing speed of the task at hand is difficult to say without actual code or a thorough description.

Answers 2

Scanning Values from the retrieved rows example read step 10.
Since Query() & QueryRow() returns a pointer to Rows and pointer to Row from the database query respectively, we can use the Scan() functions on Rows and Row struct to get access to the values in the rows struct.

for rows.Next() {   var empID sql.NullInt64  var empName sql.NullString  var empAge sql.NullInt64  var empPersonId sql.NullInt64   if err := rows.Scan(&empID, &empName, &empAge,                             &empPersonId); err != nil {           log.Fatal(err)  }   fmt.Printf("ID %d with personID:%d & name %s is age %d\n",                           empID.Int64, empPersonId.Int64, empName.String, empAge.Int64) } 

We also used the Scan() function from Row struct. Scan() is the only method declared in the Row Struct.

func (r *Row) Scan(dest ...interface{}) error 
Read More

Sunday, September 10, 2017

Periodic iCloud backup of SQLite database

Leave a Comment

Let me get this out of the way right now: yes, it was almost certainly a mistake to not use Core Data. However, I was new to iOS development when I made these decisions, and I had no idea I'd be hamstrung like this. Moreover, the app is intended to also run on Android (eventually), so I avoided platform-specific APIs wherever possible.

I have an iOS app that stores data in a local SQLite database file. The data stored in the file is provided by the user, so it's important that it be kept safe. I had plans to "do this later", and later is now here. I am quickly coming to the realization that it won't be as straightforward as I had hoped...

I now understand that it won't be possible to seamlessly synchronize data across devices, and I'm willing to accept that limitation until I manage to migrate to Core Data. However, in the meantime I'd at least like the SQLite database to be backed up periodically so users can feel safe using the app on a single device. I was thinking I would do this:

  • periodically (e.g. once a week) copy the SQLite file from local storage into cloud storage, thus ensuring it is backed up
  • when the app starts, if the local store is missing or corrupted but the file exists in the cloud storage, ask the user if they would like to copy it over

The biggest problem with this approach is that the user could run the app on multiple devices and therefore the data stored in iCloud could be from any one of those devices, but only one. To combat that, I thought I could just use a per-device, unique name for the file in cloud storage. I would generate this using UIDevice.identifierForVendor.

So my startup logic would be:

  1. Determine the unique name for the cloud file.
  2. Is the local file missing or corrupted, and if so, does the cloud file exist?

    2.1. Ask the user if they would like to restore from the cloud file. Make it really hard for them to say no because doing so will lose all their data.

    2.2. If they say yes, copy the cloud file to the local file storage.

  3. Open the local database file.

And running in the background I would occasionally copy the database file from local to cloud storage.

I would like to know whether this a sensible approach until I do Core Data integration. Also, are there any hidden "gotchas" that I'm perhaps missing?

UPDATE: as @TomHarrington pointed out in a comment, it turns out my database file is already sitting in /Documents, which is backed up to iTunes and any iCloud account. So my question morphs into this:

Should I simply ensure my database has a device-specific name so that it is not clobbered by the app running on another device connected to the same iCloud account?

1 Answers

Answers 1

I'm going to answer my question, since I ended up going down this path and finding a MASSIVE blocker. There is a bug in the UIDevice.identifierForVendor API that causes it to regenerate every time a new version of the app is installed! See here. This of course rules out using it as a device identifier. sigh

I think I'm SOL with that approach. Instead, I might generate a GUID on first execution and use that as my identifier. Problem is, I need to store that somewhere that isn't backed up to iCloud.

Ugh, I may just give up here and say my app can't be run on multiple devices until Core Data integration is done.

Read More

Saturday, September 9, 2017

Managing threads accessing a database with Java

Leave a Comment

I am working on an app that accesses an SQLite database. The problem is the DB gets locked when there is a query to it. Most of the time this is not a problem because the flow of the app is quite linear.

However I have a very long calculation process which is triggered by the user. This process involves multiple calls to the database in between calculations.

I wanted the user to get some visual feedback so I have been using Javafx progressIndicator and a Service from the Javafx.Concurrency framework. The problem is this leaves the user free to move around the app and potentially triggering other calls to the database.

This caused an exception that the database file is locked. I would like a way to stop that thread from running when this case happens however I have not been able to find any clear examples online. Most of them are oversimplified and I would like a way which is scalable. I've tried using the cancel() method but this does not guarantee that the thread will be cancelled in time.

Because I am not able to check in all parts of the code for isCancelled sometimes there is a delay between the time the thread is canceled and the time it effectively stops.

So I thought of the following solution but I would like to know if there is a better way in terms of efficiency and avoiding race conditions and hanging.

    // Start service     final CalculatorService calculatorService = new CalculatorService();      // Register service with thread manager     threadManager.registerService(CalculatorService);      // Show the progress indicator only when the service is running     progressIndicator.visibleProperty().bind(calculatorService.runningProperty());  calculatorService.setOnSucceeded(new EventHandler<WorkerStateEvent>() {         @Override         public void handle(WorkerStateEvent workerStateEvent) {             System.out.println("SUCCEEDED");             calculatorService.setStopped(true);         }     });      // If something goes wrong display message     calculatorService.setOnFailed(new EventHandler<WorkerStateEvent>() {         @Override         public void handle(WorkerStateEvent workerStateEvent) {             System.out.println("FAILED");             calculatorService.setStopped(true);         }     });      // Restart the service     calculatorService.restart();  

This is my service class which I have subclassed to include methods that can be used to set the state of the service (stopped or not stopped)

    public class CalculatorService extends Service implements CustomService {     private AtomicBoolean stopped;     private CalculatorService serviceInstance;      public FindBundleService() {         stopped = new AtomicBoolean(false);         instance = this;     }      @Override     protected Task<Results> createTask() {         return new Task<Result>() {              @Override             protected Result call() throws Exception {                 try {                     Result = calculationMethod(this, serviceInstance);                     return Result;                 } catch (Exception ex) {                     // If the thread is interrupted return                     setStopped(true);                     return null;                 }             }         };     }      @Override     public boolean isStopped() {         return stopped.get();     }      @Override     public void setStopped(boolean stopped) {         this.stopped.set(stopped);     } } 

The service implements this interface which I defined

public interface CustomService {      /**      * Method to check if a service has been stopped      *       * @return      */     public boolean isStopped();      /**      * Method to set a service as stopped      *       * @param stopped      */     public void setStopped(boolean stopped);  } 

All services must register themselves with the thread manager which is a singleton class.

public class ThreadManager {      private ArrayList<CustomService> services;      /**      * Constructor      */     public ThreadManager() {         services = new ArrayList<CustomService>();     }      /**      * Method to cancel running services      */     public boolean cancelServices() {         for(CustomService service : services) {             if(service.isRunning()) {                 ((Service) service).cancel();                 while(!service.isStopped()) {                     // Wait for it to stop                 }             }         }         return true;     }       /**      * Method to register a service      */     public void registerService(CustomService service) {         services.add(service);     }      /**      * Method to remove a service      */     public void removeService(CustomService service) {         services.remove(service);     }  } 

In any place in the app if we want to stop the service we call cancelServices(). This will set the state to cancelled I'm checking for this in my calculationMethod() then setting the state to stopped just before returning (effectively ending the thread).

if(task.isCancelled()) {         service.setStopped(true);         return null; } 

4 Answers

Answers 1

(I will assume you are using JDBC for your database queries and that you have control over the code running the queries)

I would centralize all database accesses in a singleton class which would keep the last PreparedStatement running the current query in a single thread ExecutorService. You could then ask that singleton instance things like isQueryRunning(), runQuery(), cancelQuery() that would be synchronized so you can decide to show a message to the user whenever the computation should be canceled, cancel it and start a new one.

Something like (add null checks and catch (SQLException e) blocks):

public class DB {      private Connection cnx;     private PreparedStatement lastQuery = null;     private ExecutorService exec = Executors.newSingleThreadExecutor(); // So you execute only one query at a time      public synchronized boolean isQueryRunning() {         return lastQuery != null;     }      public synchronized Future<ResultSet> runQuery(String query) {         // You might want to throw an Exception here if lastQuery is not null (i.e. a query is running)         lastQuery = cnx.preparedStatement(query);         return exec.submit(new Callable<ResultSet>() {             public ResultSet call() {                 try {                     return lastQuery.executeQuery();                 } finally { // Close the statement after the query has finished and return it to null, synchronizing                     synchronized (DB.this) {                         lastQuery.close();                         lastQuery = null;                     }                 }             }             // Or wrap the above Future<ResultSet> so that Future.cancel() will actually cancel the query     }      public synchronized void cancelQuery() {         lastQuery.cancel(); // I hope SQLite supports this         lastQuery.close();         lastQuery = null;     }  } 

Answers 2

A solution to your problem could be Thead.stop(), which has been deprecated centuries ago (you can find more on the topic here).

To implement the similar behavior it is suggested to use the Thread.interrupt(), which is (in the context of Task) the same as the the Task.cancel().

Solutions:

  • Fill your calculationMethod with isCancelled() checks.
  • Try to interrupt an underling operation through an other Thread.

The second solution is probably what you are looking for, but it depends on the actual code of the calculationMethod (which I guess you can't share).

Generic examples for killing long database operations (all of this are performed from another thread):

  • Kill the connection to the Database (assuming that the Database is smart enough to kill the operation on disconnect and then unlock the database).
  • Ask for the Database to kill an operation (eg. kill <SPID>).

EDIT:

I hadn't see that that you specified the database to SQLite when I wrote my answer. So to specify the solutions for SQLite:

  • Killing the connection will not help
  • Look for the equivalent of sqlite3_interrupt in your java SQLite interface

Answers 3

Maybe you can invoke thread instance t1, t1.interrupt() method, then in the run method of thread( Maybe calculationMethod), add a conditional statement.

 public void run() {         while (!Thread.currentThread().isInterrupted()) {             try {                 // my code goes here             } catch (IOException ex) {                 log.error(ex,ex)             }         }     } 

Answers 4

With WAL mode (write-ahead logging) you can do many queries in parallel to the sqlite database

WAL provides more concurrency as readers do not block writers and a writer does not block readers. Reading and writing can proceed concurrently.

https://sqlite.org/wal.html

Perhaps these links are of interest to you:

https://stackoverflow.com/a/6654908/1989579 https://groups.google.com/forum/#!topic/sqlcipher/4pE_XAE14TY https://stackoverflow.com/a/16205732/1989579

Read More

Thursday, August 17, 2017

Syntax diagrams for MySQL

Leave a Comment

I absolutely love the SQL syntax diagrams from the SQLite documentation.

enter image description here

I find this diagram much easier to follow than the equivalent from the MySQL docs

UPDATE [LOW_PRIORITY] [IGNORE] table_reference     SET col_name1={expr1|DEFAULT} [, col_name2={expr2|DEFAULT}] ...     [WHERE where_condition]     [ORDER BY ...]     [LIMIT row_count] 

Does anyone know if diagrams like these exist for MySQL and other dialects?

1 Answers

Answers 1

The Bison grammar for MySQL can be processed by a grammar converter to turn it into W3C notation. From that, Railroad Diagram Generator produces syntax diagrams like this:

enter image description here

The grammar still might require some tweaking in order to get what you are looking for, but maybe it provides a starting point.

When using the above tools, please allow some time for processing. The grammar is quite large, while both the converter and the diagram generator have not been optimized for speed, also they are running on a slow server.

The complete result can be found here: sql_yacc.xhtml

Read More

Sunday, August 13, 2017

SQLite Data Adapter not displaying data

Leave a Comment

I'm trying to fill a data grid view in my windows form application but nothing is being returned from the database when I execute the select query. I've looked at other questions about this topic on this site but cannot find anything that addresses my problem.

The name of the data view table is qbcMemDataView and the data source is a sqlite dataset called sqlite_dbDataSet1

Here is the code I have in place:

public Form1() {     InitializeComponent();      dbConnection = new SQLiteConnection("Data Source=sqlite_db.sqlite;Version=3");      dbConnection.Open();      string[] restrictions = new string[4];      restrictions[2] = "test_table_mom";      using (DataTable dTbl = dbConnection.GetSchema("Tables", restrictions))     {         for (int i = 0; i < dTbl.Rows.Count; i++)         {             tblChooser.Items.Add(dTbl.Rows[i].ItemArray[dTbl.Columns.IndexOf("TABLE_NAME")].ToString());         }          if (tblChooser.Items.Count > 0)         {             tblChooser.SelectedIndex = 0;         }     }   }  private void btnSelect_tbl_Click(object sender, EventArgs e) {      string sql = "SELECT id, name FROM test_table_mom";      using (SQLiteDataAdapter dbAdapter = new SQLiteDataAdapter(sql, dbConnection))     {         DataTable dataTbl = new DataTable();          dbAdapter.Fill(dataTbl);          qbcMemDataView.DataSource = dataTbl;     } } 

Also, here is a screenshot of the program running that might help better explain the issue I am having: http://imgur.com/j9ffeVi

I know there is data inside the table, I just don't know why it is not appearing in the data grid when the btnSelect_tbl_Click method is executed.

Any help would be appreciated.

Thanks!

2 Answers

Answers 1

Per the tutorial How to: Bind Data to the Windows Forms DataGridView Control, you are missing a BindingSource component that binds the data from the datasource to your table to the DataGrid.

Initialize the BindingSource at the top of your class like so:

private BindingSource bindingSource1 = new BindingSource(); 

Then near the top of your button click method before the sql add the line:

qbcMemDataView.DataSource = bindingSource1; 

and finally change the last line of code

qbcMemDataView.DataSource = dataTbl; 

to

bindingSource1.DataSource = dataTbl; 

try that and see if it works for you.

Answers 2

Note: I'm not sure if this applies to c# but maybe it's universal fix.

Android builtin adapters and such use _id as the name of the id field. The other problem is _id and id well it's not well documented in android.

About "_id" field in Android SQLite

You can use this technique renaming in the select but it gets messy and you may not catch all occurrences.

string sql = "SELECT id _id, name FROM test_table_mom"; 

My Opinion: Go back and refactor your db id to _id.

Read More

Saturday, August 12, 2017

ionic-cordova-SQLite possible to insert a Array as parameter?

Leave a Comment

I just wrote a simple function, that creates me a INSERT string out of the input the user has made, so I get something like this(working with ionic btw):

    INSERT INTO people(firstname, lastname) VALUES (??) 

Now I would like to use a Array that holds the inputvalues as parameter:

let inputvalues = ["value1", "value2"];     this.database.executeSql(this.createInserString("people",this.userData), [inputvalues]).then((data) => {         console.log("INSERTED: " + JSON.stringify(data));     }, (error) => {         console.log("ERROR-Insert: " + JSON.stringify(error.err));     }); 

Is there a way to implement something like this? (because otherwise I have to type out ever single input values and ... there are a lot ;-( )

Thank you!

1 Answers

Answers 1

i think you should separate parameters with comma:

INSERT INTO people(firstname, lastname) VALUES (?,?) 

and then use the array without "[ ]" since its already an array:

this.database.executeSql(this.createInserString("people",this.userData), inputvalues) 
Read More

Monday, June 5, 2017

Sqlite on Azure: The server was not found or was not accessible

Leave a Comment

I am using SQLite in an Asp.Net MVC 5 project which is working fine.

I uploaded the application to Microsoft Azure and I got the following error:

A network-related or instance-specific error occurred while establishing a connection to SQL Server.  The server was not found or was not accessible.  Verify that the instance name is correct and that SQL Server is configured to allow remote connections.  (provider: SQL Network Interfaces, error: 26 - Error Locating Server/Instance Specified) 

In Azure I added the following connection string:

Data Source=D:\home\site\wwwroot\Data\MyDatabase.sqlite;Password=pass 

Since there is no SqlLite database option I selected Custom: enter image description here

I checked using Azure Kudu and the file is in the right path ...

However, when I run the application I keep getting the error.

Does anyone knows how to solve this?

UPDATE

My Entity Framework class is the following:

[DbConfigurationType(typeof(Configuration))] public class Context : DbContext, IDbContext {    public Context() {     Configuration.With(x => {               x.AutoDetectChangesEnabled = true;       x.LazyLoadingEnabled = false;       x.ProxyCreationEnabled = true;       x.ValidateOnSaveEnabled = true;     });   }    public DbSet<Post> Posts { get; set; }   public DbSet<Tag> Tags { get; set; }    protected override void OnModelCreating(DbModelBuilder builder) {   }  }  public class Configuration : DbConfiguration {   public Configuration() {     SetDatabaseInitializer<Context>(null);         SetProviderServices(SqlProviderServices.ProviderInvariantName, SqlProviderServices.Instance);   } } 

And I have the following on Global.asax:

AppDomain.CurrentDomain.SetData("DataDirectory", AppDomain.CurrentDomain.BaseDirectory + "Data");  builder.RegisterType<Context>().As<IDbContext>().InstancePerRequest(); 

The connection string in Web.Config is:

<connectionStrings>   <add name="Context" providerName="System.Data.SQLite" connectionString="Data Source=|DataDirectory|\MyDatabase.sqlite;Version=3;Password=pass" /> </connectionStrings> 

1 Answers

Answers 1

I found the solution. Instead of defining a ConnectionString in Azure I need to define an Application Setting in Azure for DataDirectory where the value is the directory in Azure where the database is ...

The absolute path of the database location in Azure can be found using Kudu's Debug Console.

Following my example the DataDirectory application settings would have:

Key: DataDirectory Value: D:\home\site\wwwroot\Data 
Read More

Friday, May 5, 2017

EF6, SQLite won't work without App.confg

Leave a Comment

I'm trying to make a plug in that will use EF6.1 and SQLite for an app where I can't change the App.config so all the configuration and connection string needs to be set in code.

I found this answer that looked promising Problems using Entity Framework 6 and SQLite

So now I have a configuration class like this:

public class CollectionDbConfiguration : DbConfiguration {     public CollectionDbConfiguration()     {         SetProviderServices("System.Data.SQLite"(DbProviderServices)SQLiteProviderFactory.Instance.GetService(typeof(DbProviderServices)));         SetProviderFactory("System.Data.SQLite.EF6", SQLiteProviderFactory.Instance);         SetProviderFactory("System.Data.SQLite", SQLiteFactory.Instance);                      } } 

I have confirmed this gets hit before the context is created for the first time and all these return values.

My context looks like this

public class MyContext : DbContext {     public MyContext(string connectionString)     :   base(connectionString) { }      public DbSet<MyEntity> MyEntities { get; set; }       } 

And I have some code calling it like this:

var context = new MyContext("Data Source = mytest.db; Version = 3;"); var entities = context.MyEntities.ToList(); 

When I try and run the code it looks like the context is assuming the connection string is for SQL Server as it gives me:

Keyword not supported: 'version'.

If I remove it I then get an error that it cannot connect and its clearly trying to connect to a SQL Server database.

I tried passing in a SQLite connection by adding a constructor:

public MyContext(DbConnection connection)      : base(connection, contextOwnsConnection: true) { } 

And calling it with this:

var context = new MyContext(new SQLiteConnection("Data Source = mytest.db; Version = 3;")); var entities = context.MyEntities.ToList(); 

But then I get the error:

Unable to determine the DbProviderFactory type for connection of type 'System.Data.SQLite.SQLiteConnection'. Make sure that the ADO.NET provider is installed or registered in the application config.

So I made a factory resolver and registered that

public class FactoryResolver : IDbProviderFactoryResolver {     public DbProviderFactory ResolveProviderFactory(DbConnection connection)     {         if (connection.GetType() == typeof(SQLiteConnection))         {             return SQLiteFactory.Instance;         }          if (connection.GetType() == typeof(EntityConnection))         {             return SQLiteProviderFactory.Instance;         }          return null;     } } 

And added:

SetProviderFactoryResolver(new FactoryResolver()); 

but now I get this:

No Entity Framework provider found for the ADO.NET provider with invariant name 'System.Data.SQLite.EF6'. Make sure the provider is registered in the 'entityFramework' section of the application config file. See http://go.microsoft.com/fwlink/?LinkId=260882 for more information.

I've beet at this for two days now and I'm running out of ideas.

1 Answers

Answers 1

The minimum needed to make the constructor with connection string working is a custom IProviderInvariantName, IDbDependencyResolver and DbConfiguration:

public class SQLiteProviderInvariantName : IProviderInvariantName {     public static readonly SQLiteProviderInvariantName Instance = new SQLiteProviderInvariantName();     private SQLiteProviderInvariantName() { }     public const string ProviderName = "System.Data.SQLite.EF6";     public string Name { get { return ProviderName; } } }  class SQLiteDbDependencyResolver : IDbDependencyResolver {     public object GetService(Type type, object key)     {         if (type == typeof(IProviderInvariantName)) return SQLiteProviderInvariantName.Instance;         if (type == typeof(DbProviderFactory)) return SQLiteProviderFactory.Instance;         return SQLiteProviderFactory.Instance.GetService(type);     }      public IEnumerable<object> GetServices(Type type, object key)     {         var service = GetService(type, key);         if (service != null) yield return service;     } }  class SQLiteDbConfiguration : DbConfiguration {     public SQLiteDbConfiguration()     {         AddDependencyResolver(new SQLiteDbDependencyResolver());     } } 

Now this should work:

var context = new MyContext("Data Source = mytest.db; Version = 3;"); var entities = context.MyEntities.ToList(); 

Update: For NET4.0 you would also need a custom IDbProviderFactoryResolver:

class SQLiteDbProviderFactoryResolver : IDbProviderFactoryResolver {     public static readonly SQLiteDbProviderFactoryResolver Instance = new SQLiteDbProviderFactoryResolver();     private SQLiteDbProviderFactoryResolver() { }     public DbProviderFactory ResolveProviderFactory(DbConnection connection)     {         if (connection is SQLiteConnection) return SQLiteProviderFactory.Instance;         if (connection is EntityConnection) return EntityProviderFactory.Instance;         return null;     } } 

and add

if (type == typeof(IDbProviderFactoryResolver)) return SQLiteDbProviderFactoryResolver.Instance; 

to the SQLiteDbDependencyResolver.GetService method implementation.

Read More

Thursday, March 16, 2017

Ionic 2 SQLite Native as a Service

Leave a Comment

Anyone had success creating a service out of the SQLite ionic-native?

So one could end up with something like addItem(param), editItem(param), which calls the respective service function to handle the task?

With Storage and SqlStorage, I could do something like this:

import {Injectable} from '@angular/core'; import { Storage, SqlStorage } from 'ionic-angular';  @Injectable() export class CategoryService {        constructor() {      this.storage = new Storage(SqlStorage);      this.storage.query('CREATE TABLE IF NOT EXISTS category (id INTEGER PRIMARY KEY AUTOINCREMENT, name TEXT, type TEXT)');   }    saveCategory(data) {     let sql = 'INSERT INTO category (name, type) VALUES (?, ?)';     return this.storage.query(sql, [data.name, data.type]);   } } 

I've been reading the docs about using the SQLite in Ionic, and I'm not understanding how to do something along the lines of the above, Doc: https://ionicframework.com/docs/v2/native/sqlite/

How do you do it?

1 Answers

Answers 1

Not sure what the problem is.. here is how i use it

import { Injectable } from '@angular/core'; import { SQLite } from 'ionic-native';  @Injectable() export class DBService {      private db: SQLite;      constructor() {         this.db = null;     };      public open() {         if (window.sqlitePlugin) {             this.db = new SQLite();         } else { //handle in desktop if needed }     };  }  // other methods 
Read More

Wednesday, June 22, 2016

Populating ExpandableListView from database - not working

Leave a Comment

I have tables Receipt and Logs and table receipt has_many logs. So on my LogsRecapitulation.class I have grouping logs by sort and grade(those two columns are from table logs).

I have trying to made this via ExpandableListView. Each group of logs parent elements will consists of Sort and Grade for each group from database.

Children elements will have textViews for logs count in child element, mass, price and some calculated price. And it should look something like this:

enter image description here

I have created expandableListView layouts and adapter. But now I have trouble with populating parent and child elements from database.

Here is my code so you can see what I have done so far.

This is expandableListAadapter class:

public class ExpandableListAdapter extends BaseExpandableListAdapter {      private Context _context;     private List<String> _listDataHeader;     private HashMap<String, List<String>> _listDataChild;      public ExpandableListAdapter(Context context, List<String> listDataHeader, HashMap<String, List<String>> listDataChild) {         this._context = context;         this._listDataHeader = listDataHeader;         this._listDataChild = listDataChild;     }      @Override     public Object getChild(int groupPosition, int childPosition) {         return this._listDataChild.get(this._listDataHeader.get(groupPosition)).get(childPosition);     }      @Override     public long getChildId(int groupPosition, int childPosition) {         return childPosition;     }      @Override     public View getChildView(int groupPosition, final int childPosition, boolean isLastChild,                              View convertView, ViewGroup parent) {         final String childText = (String) getChild(groupPosition, childPosition);          if (convertView == null) {             LayoutInflater inflater = (LayoutInflater) this._context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);             convertView = inflater.inflate(R.layout.expendable_items, null);         }          TextView logsMass = (TextView) convertView.findViewById(R.id.exp_lis_mass);         TextView logsPrice = (TextView) convertView.findViewById(R.id.exp_lis_price);         TextView logsMassPrice = (TextView) convertView.findViewById(R.id.ext_lis_sum_price);         logsMass.setText(childText);         logsPrice.setText(childText);         logsMassPrice.setText(childText);          return convertView;     }      @Override     public int getChildrenCount(int groupPosition) {         return this._listDataChild.get(this._listDataHeader.get(groupPosition)).size();     }      @Override     public Object getGroup(int groupPosition) {         return this._listDataHeader.get(groupPosition);     }      @Override     public int getGroupCount() {         return this._listDataHeader.size();     }      @Override     public long getGroupId(int groupPosition) {         return groupPosition;     }      @Override     public View getGroupView(int groupPosition, boolean isExpanded, View convertView, ViewGroup parent) {         String headerTitle = (String) getGroup(groupPosition);         if (convertView == null) {             LayoutInflater inflater = (LayoutInflater) this._context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);             convertView = inflater.inflate(R.layout.expandable_group, null);         }          TextView logsSort = (TextView) convertView.findViewById(R.id.exp_gr_sort);         TextView logsGrade = (TextView) convertView.findViewById(R.id.exp_gr_grade);         TextView logsCount = (TextView) convertView.findViewById(R.id.exp_gr_logs_count);         logsSort.setText(headerTitle);         logsGrade.setText(headerTitle);         logsCount.setText(headerTitle);          return convertView;     }      @Override     public boolean hasStableIds() {         return false;     }      @Override     public boolean isChildSelectable(int groupPosition, int childPosition) {         return true;     } } 

And this is my logsRecapitulation class:

public class LogsRecapitulation extends AppCompatActivity {      ExpandableListAdapter listAdapter;     ExpandableListView expListView;     List<String> listDataHeader;     HashMap<String, List<String>> listDataChild;      @Override     protected void onCreate(Bundle savedInstanceState) {         super.onCreate(savedInstanceState);         setContentView(R.layout.expandable_layout);         //recieve RecepitID and query to group_by logs         final long forwardedId = (long) getIntent().getExtras().get(String.valueOf("recepitID"));         List<Logs> logsList = new Select().from(Logs.class).where("Receipt = " + forwardedId).groupBy("SortID, Grade").execute();         //get the listview         expListView = (ExpandableListView) findViewById(R.id.lvExp);         prepareListData();         listAdapter = new ExpandableListAdapter(this, listDataHeader, listDataChild);         expListView.setAdapter(listAdapter);     }      private void prepareListData() {      } } 

My problem now is to populate ExpendableListView with data from database. Here are my table classes:

//receipt table @Table(name = "Receipt") public class Receipt extends Model {     @Column(name="Place")     String place;     @Column(name="ShippingNumber")     String shippingNumber;     @Column(name="Warehouse")     String warehouse;     @Column(name="Carrier")     String carrier;     @Column(name="LicencePlate")     String licencePlate;     @Column(name = "Driver")     String driver;     @Column(name = "Customer")     String customer;     @Column(name= "DestWarehouse")     String destWarehouse;     @Column(name = "Employee")     String employee;     @Column(name = "PriceType")     String priceType;     @Column(name = "PriceCorrection")     Double priceCorrection;     @Column(name = "PriceCorrection2")     Double priceCorrection2;     @Column(name = "Supplier")     String supplier;     @Column(name = "CreatedAt")     Date createdAt; } //logs table @Table(name = "Logs") public class Logs extends Model {     @Column(name="PlateNumber")     String plate_number;     @Column(name="SortID")     String sort_id;     @Column(name="Grade")     String grade;     @Column(name = "Diametar")     double diameter;     @Column(name="Length")     double length;     @Column(name="CreatedAt")     Date createdAt;     @Column(name="Receipt")     Receipt receipt;     @Column(name = "Price")     Price price; } //price table @Table(name = "Price") public class Price extends Model {     @Column(name = "Sort")     String sort;     @Column(name = "Grade")     String grade;     @Column(name = "Diameter")     double diameter;     @Column(name = "LengthDG")     double lengthDG;     @Column(name = "LengthGG")     double lengthGG;     @Column(name = "StumpPriceKn")     double stumpPrice_kn;     @Column(name = "RoadPriceKn")     double roadPrice_kn; } 

Note: I'm using ActiveAndroid.

Please if anyone knows how to populate expandable listView from database please help.

Question: What should I do to successfully populate ExpandableListView from database?

1 Answers

Answers 1

I am not an expert on ActiveAndroid.But here are the steps to create an expandablelistview using cursor.

You need two methods in your db helper class to gather the rows that you'll need.

public Cursor fetchGroup() {     String query = "SELECT * FROM rooms"     return mDb.rawQuery(query, null); }  public Cursor fetchChildren(String room) {     String query = "SELECT * FROM devices WHERE id_room = '" + room + "'";     return mDb.rawQuery(query, null); } 

Then you need to configure the adapter (in your activity):

  public class MyExpandableListAdapter extends SimpleCursorTreeAdapter {     public MyExpandableListAdapter(Cursor cursor, Context context,int groupLayout,          int childLayout, String[] groupFrom, int[] groupTo, String[] childrenFrom,          int[] childrenTo) {             super(context, cursor, groupLayout, groupFrom, groupTo,                   childLayout, childrenFrom, childrenTo);         }     }      @Override     protected Cursor getChildrenCursor(Cursor groupCursor) {         Cursor childCursor = mDbHelper.fetchChildren(groupCursor.getString(groupCursor.getColumnIndex("id_room"));                     getActivity().startManagingCursor(childCursor);         childCursor.moveToFirst();         return childCursor;     } } 

And finally, call the adapter and configure it to your list (in your activity):

private void fillData() {     mGroupsCursor = mDbHelper.fetchGroup();     getActivity().startManagingCursor(mGroupsCursor);     mGroupsCursor.moveToFirst();      ExpandableListView elv = (ExpandableListView) getActivity().findViewById(android.R.id.list);      mAdapter = new MyExpandableListAdapter(mGroupsCursor, getActivity(),         R.layout.rowlayout_expgroup,                     // Your row layout for a group         R.layout.rowlayout_itemlist_exp,                 // Your row layout for a child         new String[] { "id_room" },                      // Field(s) to use from group cursor         new int[] { android.R.id.room },                 // Widget ids to put group data into         new String[] { "name_device", "state_device" },  // Field(s) to use from child cursors         new int[] { R.id.device, R.id.state });          // Widget ids to put child data into          lv.setAdapter(mAdapter);                         // set the list adapter.     } } 

So All together code

public class List_Exp extends Activity {     @Override     public void onActivityCreated(Bundle savedInstanceState) {         super.onActivityCreated(savedInstanceState);         mDbHelper = new YourDB(getActivity());         mDbHelper.open();         fillData();     }      private void fillData() {          // set list adapter here     }      public class MyExpandableListAdapter extends SimpleCursorTreeAdapter {         // Your adapter     } } 

If you want to capture click event on group/child then handle events:

lv.setOnChildClickListener(new ExpandableListView.OnChildClickListener() {     @Override     public boolean onChildClick(ExpandableListView parent, View v,         int groupPosition, int childPosition, long id) {         // Your child click code here         return true;     } });  lv.setOnGroupClickListener(new ExpandableListView.OnGroupClickListener() {     @Override     public boolean onGroupClick(ExpandableListView parent, View v,         int groupPosition, int groupPosition, long id) {         // Your group click code here         return true;     } }); 
Read More

Sunday, May 8, 2016

Invalid column deleted while trying to query a column

Leave a Comment

I am trying to execute the following query in my android app:

private static final String[] PROJECTION =             {                     Data.CONTACT_ID, Data.MIMETYPE,                     Data.DISPLAY_NAME, Phone.NUMBER,                     Phone.TYPE, StructuredName.GIVEN_NAME,                     StructuredName.MIDDLE_NAME,                     StructuredName.FAMILY_NAME,                     Data.DELETED             };   private static final String SELECTION = "(" + Data.MIMETYPE + " = ? AND "         + Phone.TYPE + " IN (?,?,?)) OR ("         + Data.MIMETYPE + " IN (?))";   private static final String[] SELECTION_ARGS =         {                 Phone.CONTENT_ITEM_TYPE,                 String.valueOf(Phone.TYPE_MOBILE),                 String.valueOf(Phone.TYPE_HOME),                 String.valueOf(Phone.TYPE_WORK),                 StructuredName.CONTENT_ITEM_TYPE         }; final Cursor cursor = mContext.getContentResolver().query(                 Data.CONTENT_URI, PROJECTION, SELECTION, SELECTION_ARGS, Data.CONTACT_ID); 

But I get the following error:

04-29 11:00:58.715  8588 15565 E DatabaseUtils: Writing exception to parcel 04-29 11:00:58.715  8588 15565 E  DatabaseUtils: java.lang.IllegalArgumentException: Invalid column deleted 04-29 11:00:58.715  8588 15565 E  DatabaseUtils:  at android.database.sqlite.SQLiteQueryBuilder.computeProjection(SQLiteQueryBuilder.java:632) 04-29 11:00:58.715  8588 15565 E  DatabaseUtils:  at android.database.sqlite.SQLiteQueryBuilder.buildQuery(SQLiteQueryBuilder.java:447) 04-29 11:00:58.715  8588 15565 E  DatabaseUtils:  at android.database.sqlite.SQLiteQueryBuilder.query(SQLiteQueryBuilder.java:387) 04-29 11:00:58.715  8588 15565 E  DatabaseUtils:  at com.android.providers.contacts.ContactsProvider2.doQuery(ContactsProvider2.java:6528) 04-29 11:00:58.715  8588 15565 E  DatabaseUtils:  at com.android.providers.contacts.ContactsProvider2.queryLocal(ContactsProvider2.java:6479) 04-29 11:00:58.715  8588 15565 E  DatabaseUtils:  at com.android.providers.contacts.ContactsProvider2.query(ContactsProvider2.java:5038) 04-29 11:00:58.715  8588 15565 E  DatabaseUtils:  at android.content.ContentProvider$Transport.query(ContentProvider.java:238) 04-29 11:00:58.715  8588 15565 E  DatabaseUtils:  at android.content.ContentProviderNative.onTransact(ContentProviderNative.java:112) 04-29 11:00:58.715  8588 15565 E  DatabaseUtils:  at android.os.Binder.execTransact(Binder.java:453) 

I want to know if the contact that I am reading is deleted or not, so the Data.DELETED column is needed for me and that seems to be causing the error. But when I checked the Android documentation, DELETED does seem to be a valid column to use with ContactsContract.Data.

0 Answers

Read More

Saturday, May 7, 2016

Displaying null values after first users login inside android

Leave a Comment

I have 3 fragments inside an app and in one of them I display users name from the SQLite database. What happens is when I register a new user and login first time with it, inside the textview where the users name suppose to appear, it displays NULL value, but when I logout and login again with the same user, name appears as it should.

After registering user, all the data is inserted inside a database, I have checked.

Any ideas what can cause this problem? I will add some code on request as I have no idea which part of the code, fragments or java files might cause this..

EDITED

I have added some code to help resolve this issue.

Login function inside the main screen (once app launches):

private void checkLogin(final String email, final String password) {     // Tag used to cancel the request     String tag_string_req = "req_login";      pDialog.setMessage("Logging in ...");     showDialog();      StringRequest strReq = new StringRequest(Request.Method.POST,             AppConfig.URL_LOGIN, new Response.Listener<String>() {          @Override         public void onResponse(String response) {              Log.d(TAG, "Login Response: " + response.toString());             hideDialog();               try {                 JSONObject jObj = new JSONObject(response);                 boolean error = jObj.getBoolean("error");                  // Check for error node in json                 if (!error) {                     // user successfully logged in                     // Create login session                     session.setLogin(true);                     // Now store the user in SQLite                     String uid = jObj.getString("uid");                      JSONObject user = jObj.getJSONObject("user");                     String name = user.getString("name");                     String email = user.getString("email");                     String created_at = user.getString("created_at");                      // Inserting row in users table                     db.addUser(name, email, uid, created_at);                      // Launch main activity                     Intent intent = new Intent(Main.this,                             Logged.class);                     startActivity(intent);                     finish();                 } else {                      error_msg.setVisibility(View.VISIBLE);                     String msg = jObj.getString("error_msg");                     error_msg.setText(msg);                 }             } catch (JSONException e) {                 // JSON error                 e.printStackTrace();                 Toast.makeText(getApplicationContext(), "Json error: " + e.getMessage(), Toast.LENGTH_LONG).show();             }          }     }, new Response.ErrorListener() {          @Override         public void onErrorResponse(VolleyError error) {             Log.e(TAG, "Login Error: " + error.getMessage());             Toast.makeText(getApplicationContext(),                     error.getMessage(), Toast.LENGTH_LONG).show();             hideDialog();         }     }) {          @Override         protected Map<String, String> getParams() {             // Posting parameters to login url             Map<String, String> params = new HashMap<String, String>();             params.put("email", email);             params.put("password", password);              return params;         }      };      // Adding request to request queue     AppController.getInstance().addToRequestQueue(strReq, tag_string_req); } 

onViewCreated func inside fragment where users name should be diplayed:

@Override public void onViewCreated(View view, Bundle savedInstanceState){      profileName = (TextView) getActivity().findViewById(R.id.profileName);       // SqLite database handler     db = new SQLiteHandler(getActivity().getApplicationContext());      // session manager     session = new SessionManager(getActivity().getApplicationContext());      if (!session.isLoggedIn()) {         logoutUser();     }      // Fetching user details from SQLite     HashMap<String, String> user = db.getUserDetails();      String name = user.get("name");      // Displaying the user details on the screen     profileName.setText(name);  } 

Register function part:

  public void onResponse(String response) {             Log.d(TAG, "Register Response: " + response.toString());             hideDialog();              try {                 JSONObject jObj = new JSONObject(response);                 boolean error = jObj.getBoolean("error");                 if (!error) {                      // User successfully stored in MySQL                     // Now store the user in sqlite                     String uid = jObj.getString("uid");                      JSONObject user = jObj.getJSONObject("user");                     String name = user.getString("name");                     String email = user.getString("email");                     String created_at = user.getString("created_at");                      // Inserting row in users table                     db.addUser(name, email, uid, created_at);                      // Launch login activity                     Intent intent = new Intent(                             Register.this,                             Main.class);                     startActivity(intent);                     finish();                 } else {                      // Error occurred in registration. Get the error                     // message                     error_msg.setVisibility(View.VISIBLE);                     String msg = jObj.getString("error_msg");                     error_msg.setText(msg);                   }             } catch (JSONException e) {                 e.printStackTrace();             }          }     }, new Response.ErrorListener() {          @Override         public void onErrorResponse(VolleyError error) {             Log.e(TAG, "Registration Error: " + error.getMessage());             Toast.makeText(getApplicationContext(),                     error.getMessage(), Toast.LENGTH_LONG).show();             hideDialog();         }     }) { 

1 Answers

Answers 1

I managed to sort this problem myself.. The problem was not in java files but in php files sending to java for some reason..

In php function I used:

$stmt->bind_result($id, $unique_id, $name, $email, $encrypted_password, $salt, $created_at, $updated_at); $user = $stmt->fetch(); 

But then changed to

$user = $stmt->get_result()->fetch_assoc();  

And that fixed the problem..

Read More

Friday, April 22, 2016

How to measure Android app data size and identify storage leaks?

Leave a Comment

I made a small Android app and have been using it for a while now. I noticed that, in the settings, on the data line of my app's characteristics, it shows about 20 MB, which seemed a lot to me. I am afraid the app has storage leaks.

I decided to investigate and measure what might take that much space. I use pretty much all the available storage options for this app: SQLite DB, Cache files (including Glide picture loading), internal files, external files, shared preferences.

So far, thanks to a question on SQLite DB, I found that my DB file takes about 500 kB. I found by scanning recursively the files and folders in folders getCacheDirs() and getFilesDir() that Glide uses about 3 MB of cache (close to what the Android settings app tells) and that I use 10 kB of data in internal and app-private external files. I have not analysed Shared Preferences size yet, but I store less than 20 key/value pairs.

My question is, which leads did I miss to find where this 19.5 MB of data I cannot locate? Did I forget some kind of storage that might take space? And, more generally, are there tools to analyse storage leaks?

4 Answers

Answers 1

There is no storage leaks.

You didn't count odex(dalvik) or oat(android runtime) file in. They are usually located at

/data/dalvik-cache/xxx.odex /data/dalvik-cache/<target-architecture>/xxx.oat 

These files are generated by system for optimization during installing time.

Also you didn't count your APK file in which located at

/data/app/xxx.yyy.zzz.apk 

The directories or files are not accessible from adb shell if the device is not rooted.

I think the storage usage show at settings include the following three parts

/data/data/xxx.yyy.zzz /data/app/xxx.yyy.zzz.apk odex or oat file 

So the storage size you counted under /data/data/xxx.yyy.zzz is always less than the total size in settings.

Answers 2

You can use MAT TOOL for optimizing memory/size issues in your app.It displays which part in your app using more memory.

Run you app in Android-studio and Go to Tools->Android->AndroidDeviceMonitor,run your scenario and in device monitor click to download your app .hprof file by follow the image I attached below download .hprof file

After that you need to convert Android-studio .hprof file to Eclipse Mat supported .hprof file by using hprof-conv.exe inside sdk->platform-tools and follow the cmd in your CMD promt

F:\Android_Studio_SDK\platform-tools>hprof-conv "C:\Users\Bala\Desktop\your_AS_file.hprof" "C:\Users\Bala\Desktop\MAT_File_Name.hprof" 

And in MAT Tool go to File -> OpenHeapDump to open your .hprof file,It will show your app memory utilize by package,class,object..etc;

Some referral link for learn about MAT Tool
link 1
link 2

Answers 3

Following @James suggestion, I started exploring the different folders, and after discussing the issue with a colleague and trying to explore many folders, I finally found that most of the data came from the cache of a former Webview I had. I am posting all my investigation, hopefully it will help.

I executed the following code when the app starts, calling analyseStorage(this) from my main activity:

public void analyseStorage(Context context) {   long totalSize = 0;   File appBaseFolder = context.getFilesDir().getParentFile();   for (File f: appBaseFolder.listFiles()) {     if (f.isDirectory()) {       long dirSize = browseFiles(f);       totalSize += dirSize;       Log.d(STORAGE_TAG, f.getPath() + " uses " + dirSize + " bytes");     } else {       totalSize += f.length();     }   }   Log.d(STORAGE_TAG, "App uses " + totalSize + " total bytes"); }  private long browseFiles(File dir) {   long dirSize = 0;   for (File f: dir.listFiles()) {     dirSize += f.length();     //Log.d(STORAGE_TAG, dir.getAbsolutePath() + "/" + f.getName() + " weighs " + f.length());     if (f.isDirectory()) {       dirSize += browseFiles(f);     }   }   return dirSize; } 

What is important is to scan specifically context.getFilesDir().getParentFile() which matches the folder /data/data/my.app.package/

After executing that code, I had the following logs:

D/storage﹕ /data/data/my.app.package/lib uses 0 bytes D/storage﹕ /data/data/my.app.package/cache uses 3371773 bytes D/storage﹕ /data/data/my.app.package/databases uses 483960 bytes D/storage﹕ /data/data/my.app.package/shared_prefs uses 604 bytes D/storage﹕ /data/data/my.app.package/app_webview uses 9139469 bytes D/storage﹕ /data/data/my.app.package/files uses 7723 bytes D/storage﹕ /data/data/my.app.package/app_ACRA-approved uses 0 bytes D/storage﹕ /data/data/my.app.package/app_ACRA-unapproved uses 0 bytes D/storage﹕ App uses 13003529 total bytes 

What I could see is:

  • The cache, used only by Glide for picture loading, takes 3MB
  • The SQLite database takes 500kB
  • The shared preferences take 600B
  • The cache for all the Webviews I used to have still takes 9MB
  • The rest of the files, under files and other folders, is mostly used by ACRA for bug tracking and take 10kB

In the end, I finally discovered that most of my data went to Webview cache, actually not stored explicitly as cache. I deleted these files and it actually reduced the size of my app by 20MB, even more than listed above. I now know what order of magnitude my app's data takes.

Answers 4

You can use a library like Leak Canary to automatically detect all memory leaks inside your app: https://corner.squareup.com/2015/05/leak-canary.html

You can also go to the DDMS in Android Studio and get more information of the storage in your app without coding anything. However, most of the leaks would be detected by Leak Canary.

Hope it helps!

Read More

Tuesday, March 29, 2016

mysqldump, avoid escape double quotes

Leave a Comment

When I have a field with double quotes, mysqldump put the escape character before. For example:

'My "test"' -> mysqldump generates a file with that field like 'My \"test\"'

The problem is that I'm using that file to import some data into a sqlite database, and SQLite doesn't remove the escape character. So I don't need that mysqldump writes escape characters, can I do that?

3 Answers

Answers 1

I am unsure what language you are using. But the concept would be the same in any programming language.

First declare a variable equal to your sqldump.

var yourVariable = sqldump; 

Then do a string.replace("\\", ""). Then use that 'cleaned' version to import your data with.

Answers 2

Which SQL mode do you use? Look at the mysqldump manual: http://dev.mysql.com/doc/refman/5.7/en/mysqldump.html

--quote-names, -Q

Quote identifiers (such as database, table, and column names) within “`” characters. If the ANSI_QUOTES SQL mode is enabled, identifiers are quoted within “"” characters. This option is enabled by default. It can be disabled with --skip-quote-names, but this option should be given after any option such as --compatible that may enable --quote-names.

--quote-names is enabled by default.

ANSI_QUOTES

Treat “"” as an identifier quote character (like the “`” quote character) and not as a string quote character. You can still use “`” to quote identifiers with this mode enabled. With ANSI_QUOTES enabled, you cannot use double quotation marks to quote literal strings, because it is interpreted as an identifier.

Answers 3

From a google search I found this which is reworking the output of mysqldump so sqlite can use it. Not tested and 5 years old but I think:

  • you may find useful information
  • it may mean other people didn't find a more elegant solution

EDIT:

As per the comments, to answer your question it looks like you don't have a choice but replace \" into ".

Here is a repo with a script which translates mysqldump files into something sqlite can digest. In particular, for your question, you can find this line:

gsub( /\\"/, "\"" ) 
Read More