lundi 31 août 2015

How to insert into a junction table using a content provider/content values/AsyncQueryHandler

I'm trying to insert into a junction table in Android. I already set up a content provider and have been using an AsyncQueryHandler to perform a lot of my operations in classes that don't require loaders. However, I need to insert into a junction table, and I'm at a loss for how to handle querying the related tables in order to receive the _ID values to place into the junction tables via a content provider/queryhandler.

For example, from this post's answer: Automatically Create Insert Statements to Fill Junction Table in a Pre-Created DB

 insert into Name_Category values(
  (select _id from Categories where category='CAT1'),
  (select _id from Names where name='NAME1'));

(Edit) Here is an additional example: Insert into a junction table in SQLite

INSERT INTO ListsAndPlayers (ListsAndPlayersID, ListID, PlayerID)
VALUES (42,
    (SELECT ListID FROM Lists WHERE ListName = 'Los Angeles Dodgers'),
    (SELECT PlayerID FROM Players WHERE PlayerName = 'Clayton Kershaw'));

I have a very similar need in my application, and couldn't find any documentation on handling this with AsyncQueryHandlers or ContentProviders/ContentValues. What would the equivalent of this be using one of those?

Does anyone have suggestions for how they have handled this?

Thanks!

Unable to import a csv into a table in SQLite: no such table error

I have a wireshark dump in .csv format that I want to analyze. I tried importing the CSV file as described here. These are the commands I ran from the command line-

sqlite> create table network(no,time,source,dest,proto,info);
sqlite> .separator ",";
sqlite> .import E:\\Pavan\\_DataScience\\MP1\\network_data1\\challenge_network\\TestNetworkData.csv network;
Error: no such table: network;
sqlite> .tables
network
sqlite>

The .table command clearly shows that the network table is indeed present. I am not getting why the import command fails.

PS: I am running the sqlite3 executable downloaded from the official site on Windows.

Remake Django Model Everytime

I started making my project without realizing that every time I change my model data it adds to the existing data. I thought it would remake the table based on the new model.

Is there any way to do what I've described above easily? If not how would you suggest I do something like this?

Thank you in advance! If you have any question I would be happy to help!

SQLite On Github Pages

I wanted to know if it was posible to install SQLite 3 on github pages, as I do not have access to the terminal.

database file not opening after merging projects

I am working with Android Studio and java. I created a test project that can copy an existing SQLite database into a program. The project also can append the copied database and read it back. This project works perfectly and does what I need for my main program. I added the test project to my main program by copy pasting each java class to my main project. Now, the program can no longer open the file. I have the same permission in both manifest files, so I should have access to the path and I know the path is OK since it works in the test project. The two changes I made when coping from the test project to the main project is the path name was updated with the main projects name and the putinformation method is called from main in the test program and from a second class in the main program. Below is the code calling putinformation and the entire DatabaseOperations class with the putinformation method. Alternatively, if it was possible to just run the test project from my main project that would be OK as long as I can pass back the results of the database searches.

public class updateDatabase extends Activity {

EditText name,Kal;
String name, kal_value;
Button store, read, copydatabase;
Context ctx = this;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.update_database_screen);
    name = (EditText) findViewById(R.id.nameeditText);
    Kal = (EditText) findViewById(R.id.kaleditText);
    store = (Button) findViewById(R.id.saveButton);
    read = (Button) findViewById(R.id.readButton);
    copydatabase = (Button) findViewById(R.id.copyButton);
    copydatabase.setOnClickListener(new View.OnClickListener() {

        @Override
        public void onClick(View v) {
            Log.d("updateDatabase"," started copydatabase ");
            DataBaseHelper myDbHelper; //= new DataBaseHelper(ctx);
            myDbHelper = new DataBaseHelper(ctx);

            try {
                myDbHelper.createDataBase();
            } catch (IOException ioe) {
                throw new Error("Unable to create database");
            }
            try {
                Log.d("updateDatabase"," started try myDbHelper.openDataBase() ");
                myDbHelper.openDataBase();
            }catch(SQLException sqle){
                sqle.printStackTrace();
            }
        }
    });

    store.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            name = name.getText().toString();
            kal_value = Kal.getText().toString();
            DatabaseOperations DB = new DatabaseOperations(ctx);
            DB.putInformation(DB, name, kal_value);
            Toast.makeText(getBaseContext(), "Successfully instered data", Toast.LENGTH_LONG).show();
            name.setText("");
            .setText("");
        }
    });

.....

public class DatabaseOperations extends SQLiteOpenHelper { public static final int database_version = 1; public String CREATE_QUERY = "CREATE TABLE "+ TableInfo.TABLE_NAME+"("+ TableInfo.NAME+" TEXT, "+ TableInfo.KAL+" TEXT) ;";

public DatabaseOperations(Context context) {
    super(context, TableData.TableInfo.DB_PATH+TableData.TableInfo.DATABASE_NAME, null, database_version);
}

@Override
public void onCreate(SQLiteDatabase sdb) {
    boolean dbExist = DataBaseHelper.checkDataBase();
    if (!dbExist)  sdb.execSQL(CREATE_QUERY);
}
public void putInformation(DatabaseOperations dop, String name, String kcal){
    Log.d("Database Operations", "started putInformation");
    SQLiteDatabase SQ = dop.getWritableDatabase();
    Log.d("Database Operations", "before if statement");
    if (!dbExist)  SQ.execSQL(CREATE_QUERY);
    ContentValues cv = new ContentValues();
    cv.put(TableInfo.NAME,name);
    cv.put(TableInfo.KAL, kal);
    long k = SQ.insert(TableData.TableInfo.TABLE_NAME, null, cv);
    Log.d("Database Operations", "one row inserted");
}

The error code follows:

08-31 16:55:53.581    2428-2428/? D/Database Operations﹕ Database created
08-31 16:55:53.581    2428-2428/? D/Database Operations﹕ started putInformation
08-31 16:55:53.584    2428-2428/? E/SQLiteLog﹕ (14) cannot open file at line 30046 of [9491ba7d73]
08-31 16:55:53.584    2428-2428/? E/SQLiteLog﹕ (14) os_unix.c:30046: (2) open(/data/data/com.taavtech.scale_rev_0/databases/food_try.sqlite) -
08-31 16:55:53.585    2428-2428/? E/SQLiteDatabase﹕ Failed to open database '/data/data/com.taavtech.scale_rev_0/databases/food_try.sqlite'.
    android.database.sqlite.SQLiteCantOpenDatabaseException: unknown error (code 14): Could not open database
            at android.database.sqlite.SQLiteConnection.nativeOpen(Native Method)
            at android.database.sqlite.SQLiteConnection.open(SQLiteConnection.java:209)
            at android.database.sqlite.SQLiteConnection.open(SQLiteConnection.java:193)
            at android.database.sqlite.SQLiteConnectionPool.openConnectionLocked(SQLiteConnectionPool.java:463)
            at android.database.sqlite.SQLiteConnectionPool.open(SQLiteConnectionPool.java:185)
            at android.database.sqlite.SQLiteConnectionPool.open(SQLiteConnectionPool.java:177)
            at android.database.sqlite.SQLiteDatabase.openInner(SQLiteDatabase.java:806)
            at android.database.sqlite.SQLiteDatabase.open(SQLiteDatabase.java:791)
            at android.database.sqlite.SQLiteDatabase.openDatabase(SQLiteDatabase.java:694)
            at android.app.ContextImpl.openOrCreateDatabase(ContextImpl.java:1142)
            at android.content.ContextWrapper.openOrCreateDatabase(ContextWrapper.java:267)
            at android.database.sqlite.SQLiteOpenHelper.getDatabaseLocked(SQLiteOpenHelper.java:223)
            at android.database.sqlite.SQLiteOpenHelper.getWritableDatabase(SQLiteOpenHelper.java:163)
            at com.taavtech.scale_rev_0.DatabaseOperations.putInformation(DatabaseOperations.java:49)
            at com.taavtech.scale_rev_0.updateDatabase$2.onClick(updateDatabase.java:78)
            at android.view.View.performClick(View.java:4756)
            at android.view.View$PerformClick.run(View.java:19749)
            at android.os.Handler.handleCallback(Handler.java:739)
            at android.os.Handler.dispatchMessage(Handler.java:95)
            at android.os.Looper.loop(Looper.java:135)
            at android.app.ActivityThread.main(ActivityThread.java:5221)
            at java.lang.reflect.Method.invoke(Native Method)
            at java.lang.reflect.Method.invoke(Method.java:372)
            at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:899)
            at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:694)
08-31 16:55:53.585    2428-2428/? D/AndroidRuntime﹕ Shutting down VM
    --------- beginning of crash
08-31 16:55:53.585    2428-2428/? E/AndroidRuntime﹕ FATAL EXCEPTION: main
    Process: com.microchip.mldpterminal2, PID: 2428
    android.database.sqlite.SQLiteCantOpenDatabaseException: unknown error (code 14): Could not open database
            at android.database.sqlite.SQLiteConnection.nativeOpen(Native Method)
            at android.database.sqlite.SQLiteConnection.open(SQLiteConnection.java:209)
            at android.database.sqlite.SQLiteConnection.open(SQLiteConnection.java:193)
            at android.database.sqlite.SQLiteConnectionPool.openConnectionLocked(SQLiteConnectionPool.java:463)
            at android.database.sqlite.SQLiteConnectionPool.open(SQLiteConnectionPool.java:185)
            at android.database.sqlite.SQLiteConnectionPool.open(SQLiteConnectionPool.java:177)
            at android.database.sqlite.SQLiteDatabase.openInner(SQLiteDatabase.java:806)
            at android.database.sqlite.SQLiteDatabase.open(SQLiteDatabase.java:791)
            at android.database.sqlite.SQLiteDatabase.openDatabase(SQLiteDatabase.java:694)
            at android.app.ContextImpl.openOrCreateDatabase(ContextImpl.java:1142)
            at android.content.ContextWrapper.openOrCreateDatabase(ContextWrapper.java:267)
            at android.database.sqlite.SQLiteOpenHelper.getDatabaseLocked(SQLiteOpenHelper.java:223)
            at android.database.sqlite.SQLiteOpenHelper.getWritableDatabase(SQLiteOpenHelper.java:163)
            at com.taavtech.scale_rev_0.DatabaseOperations.putInformation(DatabaseOperations.java:49)
            at com.taavtech.scale_rev_0.updateDatabase$2.onClick(updateDatabase.java:78)
            at android.view.View.performClick(View.java:4756)
            at android.view.View$PerformClick.run(View.java:19749)
            at android.os.Handler.handleCallback(Handler.java:739)
            at android.os.Handler.dispatchMessage(Handler.java:95)
            at android.os.Looper.loop(Looper.java:135)
            at android.app.ActivityThread.main(ActivityThread.java:5221)
            at java.lang.reflect.Method.invoke(Native Method)
            at java.lang.reflect.Method.invoke(Method.java:372)
            at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:899)

Encountering ObjectDisposedException when trying to read from SQLiteDataReader

I am trying to read through a stored SQLiteDataReader object. In theory, it "should" work because the object is stored in a variable before it is referenced (and doesn't hit an error until the reference line is reached), but maybe I have the wrong idea.

I'm trying to keep my application in a neatly layered architecture. So, each database table having its own C# class with its own methods for select, insert, update, and delete; only the data layer knows how to communicate with the database, etc.

I was running into connection issues earlier when I tried to make one static SQLiteConnection object that all the data layer classes could reference (so as to keep it open and minimize overhead, if any). So I'm trying to go with the using block to make sure the connection is properly disposed each time I need to access the database, and hoping that this won't cause performance issues.

So basically, here is the method in my DatabaseConnection class that handles basic query execution:

public SQLiteDataReader ExecuteQuery(string sql)
{
    SQLiteDataReader rdr = null;
    using(SQLiteConnection conn = new SQLiteConnection(ConnectionString))
    {
        conn.Open();
        SQLiteCommand cmd = conn.CreateCommand();
        cmd.CommandText = sql;
        rdr = cmd.ExecuteReader();
    }
    return rdr;
}

And here is the code that calls that method. I'll use an object/record of the Associate table as an example.

public class Associate
{
    public int RowId { get; private set; }
    public int Id { get; set; }
    public string Name { get; set; }

    private string password;
    public string Password
    {
        get
        {
            return password;
        }
        set
        {
            password = Hash(value); // external password hashing method
        }
    }

    public Associate() { } // default constructor with default values

    public Associate(int id)
    {
        this.Id = id;
        Select();
    }

    // select, insert, update, delete methods
    private void Select() { ... }

    // these are non-queries and return true/false based on success
    public bool Insert() { ... }
    public bool Update() { ... }
    public bool Delete() { ... }

    /* Method that causes the error */
    public static Associate[] GetAll()
    {
        DatabaseConnection con = new DatabaseConnection();
        SQLiteDataReader rdr = con.ExecuteQuery("SELECT id FROM Associate");

        List<Associate> list = new List<Associate>();

        if (rdr != null)
        {
            while (rdr.Read()) /* this line throws the exception */
            {
                int next = rdr.GetInt32(0);
                list.Add(new Associate(next));
            }
        }

        return list.ToArray();
    }
}

The idea here is that using the rdr object, I can access the column names directly so that if the database ever changes, I won't have to rewrite a bunch of code to adjust for the column indices (rdr["id"], rdr["name"], etc.)

So what I don't understand is why rdr in the calling method is having "object disposed" issues because it's stored in a variable before I reference it. I know the connection is disposed at the end of the called method, but since the returned result is stored, shouldn't it technically be able to "survive" outside the using block?

SQLite Entity Framework without App.config

It is necessary to use the SQLite Entity Framework Database-first approach for the 3d-party application plugin. I searched all the Internet, including Add a DbProviderFactory without an App.Config, http://ift.tt/1X7l4SI and many other. I have tried to use them all in different ways and combinations, but nothing helps:

"An unhandled exception of type 'System.Data.Entity.Core.MetadataException' occurred in mscorlib.dll. Additional information: Schema specified is not valid. Errors: AutosuggestModel.ssdl (2,2): error 0152: 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."

There is a test console application in the solution. With this minimal App.config it works:

<?xml version="1.0" encoding="utf-8"?>
<configuration>
  <configSections>
    <!-- For more information on Entity Framework configuration, visit http://ift.tt/1eigFsq -->
    <section name="entityFramework" type="System.Data.Entity.Internal.ConfigFile.EntityFrameworkSection, EntityFramework, Version=6.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" requirePermission="false" />
  </configSections>
  <entityFramework>
    <providers>
      <provider invariantName="System.Data.SQLite.EF6" type="System.Data.SQLite.EF6.SQLiteProviderServices, System.Data.SQLite.EF6" />
    </providers>
  </entityFramework>
  <system.data>
    <DbProviderFactories>
      <add name="SQLite Data Provider" invariant="System.Data.SQLite" description=".NET Framework Data Provider for SQLite" type="System.Data.SQLite.SQLiteFactory, System.Data.SQLite" />
    </DbProviderFactories>
  </system.data>
</configuration>

The connection string has already implemented in the code. Used packages are:

<?xml version="1.0" encoding="utf-8"?>
<packages>
  <package id="EntityFramework" version="6.1.3" targetFramework="net452" />
  <package id="System.Data.SQLite" version="1.0.98.1" targetFramework="net452" />
  <package id="System.Data.SQLite.Core" version="1.0.98.1" targetFramework="net452" />
  <package id="System.Data.SQLite.EF6" version="1.0.98.1" targetFramework="net452" />
  <package id="System.Data.SQLite.Linq" version="1.0.98.1" targetFramework="net452" />
</packages>

Please, give all the required code and specify where to insert it. Thanks in advance.

OrmLite does not bring results on where

What's wrong with this line?

genericQB.where().ne(AppConstant.SYNC_STATUS_FIELD_NAME, strSyncOK);

i'm doing a simple where not equals with ORMlite and brings 0 results no errors:

full code:

dao = DaoManager.createDao(connectionSource, clazz);
QueryBuilder qB = dao.queryBuilder();
SelectArg strSyncOK = new SelectArg(AppConstant.SYNC_OK); // ==> "OK" string
qB.where().ne(AppConstant.SYNC_STATUS_FIELD_NAME, strSyncOK);
List<T> var = dao.query(qB.prepare());

When i remove the line

qB.where().ne(AppConstant.SYNC_STATUS_FIELD_NAME, strSyncOK);

all is ok when the line is there, no results found, i checked data and all data with AppConstant.SYNC_STATUS_FIELD_NAME is null

i'm missing something?

Invoke a text editor to edit query from within sqlite3 CLI?

From within psql, I can type \e or \edit to begin editing the current query buffer in Vim (or other configured text editor).

Is there an analogous feature using the sqlite3 CLI?

app that gets records from a sqlite db. I need this file to be then sent as an attachment. Not able to attach a CSV file

I have created a csv file that stores data from a sqlite database table. The csv file is stored in data/data/cache. The file is generated with no errors, but I am not able to retrieve the file and add it as an attachment to send in an email. The email sends successfully but does not have the csv file attached.

public void sendMail() {
    File csvFile = new File(getCacheDir() + "/emailtables/items.csv");
    Intent sendIntent = new Intent(Intent.ACTION_SEND);

    Uri uri = Uri.parse(csvFile.toString());
    Log.d(TAG, "Uri-path is: " + uri.getPath()); // or .toString()

    Intent i = new Intent(android.content.Intent.ACTION_SEND);
    i.setType("application/csv");
    i.putExtra(Intent.EXTRA_EMAIL, new String[]{"doggonemad11@gmail.com"});
    i.putExtra(Intent.EXTRA_SUBJECT, "Test Email - with Attachment");
    i.putExtra(Intent.EXTRA_TEXT, "This is a test Email with an Attachment.");
    i.putExtra(Intent.EXTRA_STREAM, uri);
    //startActivity(Intent.createChooser(i, "Select application"));
    startActivity(Intent.createChooser(i, "Send mail"));
}

Deploy ASP.NET MVC app with SQLite to Azure web site

I have an ASP.NET MVC 5 application including a Web API 2 service, and I published it to my Azure Web Site. The static site works just fine - and the Web API worked, too, while I was serving dummy data.

Since I've added a SQLite database (in a .db3 file inside App_Data), I cannot call my Web API Service anymore - I just get a "An error occurred" message, and I can't seem to find out how to really figure out what's going wrong.

I also installed Elmah.MVC into my application, but when I try to navigate to http://ift.tt/1N54IHd, I get another error:

You do not have permission to view this directory or page.

OK, now I'm stuck - locally on my machine - of course - it all works just fine. But this whole Azure deployment story is a big mystery to me - still.

  1. How do I find any kind of error logs so I could begin to understand what's going on?
  2. Is there any way I can see the files in the file system that make up this app? I'd like to check if all the files I'm expecting to see are really in place

C# SQLite Universal App Insert error Argument 1: cannot convert from 'MemBrainz.MainPage.Mood' to 'System.Collections.IEnumerable'

I've got this code, and it keeps coming up with the same error. Basically, I want to add "1" to the database under CurrentMood when the button is clicked. I'm getting: Argument 1: cannot convert from 'MemBrainz.MainPage.Mood' to 'System.Collections.IEnumerable'

Here's my code

public  class Mood
        {

            public int Id { get; set; }
            public int CurrentMood { get; set; }
        }

        private async void Button_Click(object sender, RoutedEventArgs e)
        {
            greetingOutput.Text = "1";


            Mood mood1 = new Mood()
            {

This is where the error is

CurrentMood = 1

            };
            SQLite.SQLiteAsyncConnection addconn = new SQLite.SQLiteAsyncConnection("mood.db");
            await addconn.InsertAllAsync(mood1);
        }
    }

No Such Table - Cordova and SQLLite

I am using this plugin in my ionic project. I am able to open the db. I can see the log:

DB opened: test.db

I created a brand new db using SQL Lite Manager (a firefox plugin) and a table called Products. I then copied the db over to my www folder of my xcode project. I noticed that the extension was called .sqlite, I renamed it to .db. Hopefully that did not create any issues.

Now whenever I try to query that table I get a "No Such Table" - Code 5. I am not sure what that means. The table exists. I tried lower case, upper case etc.., but nothing seems to work.

XCode log window shows me the below log entry, so I assume that its able to find the DB.

open full db path: /var/mobile/Containers/Data/Application/397075D2-943E-40DC-B076-5C0B5B7D1F42/Documents/test.db

Here is my code:

var db = $cordovaSQLite.openDB("test.db", 1);
var query = "SELECT * FROM 'main'.'Products'";
$cordovaSQLite.execute(db, query).then(function (res)
{ ... });

The second question is how do I check if I was able to open the db successfully from js?

Azure Mobile App, Xamarin Forms, WP81 - Unable to load sqlite3.dll

I downloaded the sample Todo project for xamarin forms within the azure portal after adding a new mobile app. I use offline sync. Everything builds fine. However, when trying to run the WP81 project on my device (cannot run the simulator, I never managed to properly enable Hyper V on my bios), it crashes of that line

var store = new MobileServiceSQLiteStore("localstore.db")

It says Unable to load sqlite3.dll.

I looked on the web and found a sqlite.dll file corresponding to my version of sqlite (3.8.7.2) and added it within my ARM/debug folder but the error remains.

Any idea? Tks.

How to append to list?

I have a table 's' containing strings:

  1. 'STRING_A'
  2. 'STRING_B'
  3. 'STRING_C'
  4. 'STRING_D'
  5. 'STRING_E'

and a list of strings that i want to insert into 's':

  1. 'STRING_C'
  2. 'STRING_D'
  3. 'STRING_E'
  4. 'STRING_B'
  5. 'STRING_A'

I want to insert only those items that do not overlap with records in the table 's'.

Result table 's':

  1. 'STRING_A'
  2. 'STRING_B'
  3. 'STRING_C'
  4. 'STRING_D'
  5. 'STRING_E'
  6. 'STRING_B'
  7. 'STRING_A'

Can it be done without leaving sql?

SQLite: Escaping Special Characters

Is there a common way within Android to escape all of the characters that aren't allowed in a SQLite database? For instance, "You\'Me'". Instead of me figuring out every single character that has isn't allowed and creating a bunch or replace statements. I'm looking for something like the following.

value = SQLite.escapeString(value);
// insert data
//Retrieve data
value = SQLite.unescapeString(cursor.getString(0));

Is this wishful thinking or is there something out there already that solves this?

How to make looping through SQLite result synchronous

I'm trying to insert the records from the JSON file to SQLite DB. After which I will redirect the user to required page.

Here is my code:

.factory('loadAutoComplete', function($q){
 var AutoComplete = {};

     AutoComplete.loadData = function(){

        try
        {
            var deferred = $q.defer();
            var response = {};

            db.transaction(function(tx) {

                    LocationList.forEach(function(loc){
                                         var query = "SELECT * FROM  tbl_Location WHERE ID = ? AND VALUE = ?";
                                         tx.executeSql(query,[loc.id, loc.value],function(tx, res){
                                                       if(res.rows.length == 0){
                                                          tx.executeSql("INSERT INTO tbl_Location (id, value) VALUES (?, ?)", [loc.id, loc.value],
                                                                        function(tx, res){
                                                                        },
                                                                        function(e){ console.log("Error: " + e.message); });
                                                             }

                                                       }, function(e){ console.log("Error: " + e.message); });
                                         });

                    tx.executeSql("SELECT COUNT(*) AS Count FROM tbl_Location", [], function(tx, res){
                                if(res.rows.length > 0)
                                    console.log("New rows added to tbl_Location:" + res.rows.item(0).Count);
                                });

                    response.success = true;

                    deferred.resolve(response);
                });
            return deferred.promise;
        }
        catch(ex)
        {
            console.log("Error:" + e.message);
            response.success = false;
            deferred.resolve(response);
        }
     }

     return AutoComplete;
     })

In Controller:

var promise = loadAutoComplete.loadData();
promise.then(function(responseData){
      $ionicLoading.hide();
      flag = response.result.toString();

      if(flag==true || flag=="true")
      {

                                                LogInService.setUserName(user.username);
                                                LogInService.fromLogin = true;
                                                if(UserInfoService.getInfo().userinfopagevisited=="yes")
                                                {
                                                    var view = $ionicViewService.getCurrentView();
                                                    $scope.$viewHistory.forcedNav = {
                                                        viewId: view.viewId,
                                                        navAction: 'moveForward',
                                                        navDirection: 'forward'
                                                    };
                                                    $state.go("incidents-list");
                                                }
                                                else
                                                {
                                                    var view = $ionicViewService.getCurrentView();
                                                    $scope.$viewHistory.forcedNav = {
                                                        viewId: view.viewId,
                                                        navAction: 'moveForward',
                                                        navDirection: 'forward'
                                                    };
                                                    $state.go("user-info");
                                                }
                                              }
                                              else
                                              {
                                                navigator.notification.alert(
                                                        $filter('translate')('login_Invalid_User_or_Password_errormsg'),
                                                        alertDismissed,
                                                        alertBox_Heading_text,
                                                        alertBox_OKButton_text
                                                );

                                              }
                                    });

Problem:

User is redirected prior to the completion of data insertion.

Required Behavior:

User should be redirected after the logic of data insertion.

Any idea where it is going wrong.

Thanks in advance

How to save in app main directory sqlite file in swift?

I have this function:

 func takeDatabase() -> FMDatabase {
    let documentsFolder = NSSearchPathForDirectoriesInDomains(.DocumentDirectory, .UserDomainMask, true)[0] as! String
    let path = documentsFolder.stringByAppendingPathComponent("test.sqlite")

    let database = FMDatabase(path: path)
    // println(path)
    if !database.open() {
        println("Unable to open database")

    }

    return database
}

I want to change the path, to be in main directory of my app. How can I do this? I try a lot, but with no results.

Thanks

cv2.imdecode always returning None

I am reading binary data [sqlite3.Binary] from a sqlite BLOB in which a JPEG image is stored.

Trying to recover the image as follows:

conn = sqlite3.connect(dbname)
c = conn.cursor()
c.execute('SELECT image, height, width FROM pictures WHERE serial_no=?', (serial_no, ))
raw, height, width = c.fetchone()
raw_str = StringIO.StringIO(raw)
arr = np.asarray(bytearray(raw_str.read()), dtype=np.uint8)
img = cv2.imdecode(arr, cv2.IMREAD_COLOR)

The last step always fails and imdecode return None.

What does work, however, is a numpy.reshape:

image = arr.copy().reshape((height, width, 3))

I've tested with both OpenCV 3.0.0 and OpenCV 2.4.11 where both yield the same, unsatisfying result.

What am I missing?

SQLite trigger for maintaining a "position" column

I have a need to maintain a "position" column in one of my tables.

Database Table Example

If row 1 (id = 1) is moved down to position 3 (id = 4) I need to update row (id = 1) with position value of 3, but then I would need to increment all of the rows with a position < 3 down by 1. This would also apply for the opposite, except the position would be incremented up by 1. How could I write a trigger to do this logic for me when the position column is updated?

android:configChanges with an Async SQLite Call in onCreate being called when orientation changes

I am populating a ListView with the contents of an SQLite database. In my onCreate method in my StartList activity I call an AsyncSQLite which reads data from a JSON url and adds the data to the SQlite database.

But every time that I change my screen orientation, my app is calling the AsyncSQLite method again. I have added android:configChanges="orientation|keyboardHidden|screenSize" to my AndroidManifest.xml but that doesn't seem to be making a difference.

Here is my onCreate method from my StartList activity:

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_start_List);

    oslist.clear();
    oslist = new ArrayList<LinkedHashMap<String, String>>();
    new AsyncSQLite().execute();
}

Here is my AndroidManifest.xml:

<activity
    android:name=".StartList"
    android:label="@string/title_activity_start_List"
    android:parentActivityName=".MainActivity"
    android:configChanges="orientation|keyboardHidden|screenSize">
    <meta-data
        android:name="android.support.PARENT_ACTIVITY"
        android:value=".MainActivity" />
</activity>

I thought that onCreate should only be called once when the activity is being created, but instead it is being called whenever I change the orientation.

How to make Sqlite save db in a given path

I want this Js script to save the Sqlite database in the same directory of the script, but instead the script saves the database into the cache of google chrome.

var db = openDatabase("listnum.db", "1.0", "Numbers", 200000);

Creating index in Android sqlite tables [duplicate]

This question already has an answer here:

I have certain tables which have fields other than primary key, where I want to create indexes. Is it possible through SqliteOpenHelper? Can I create indexes on certain columns while creating a table?

Getting SQLITE_BUSY[5] while updating a table using c++ sqlite interface

Today i have assigned to a requirement, in which a file should be continuously monitored by a process, if suppose that file is being modified i have to store the current line NO of the file in one table and a new texts that added to that file into an another table that's it. so i write a file watcher class which does what was told as a requirement it could monitor and update the two tables with the line number and the newly added text respectively,later during testing my app i have just closed the file watcher process and added some new text to the file then start the file watcher again there comes the creepy problem, during updating the new line number my update statement gives result code=5 that said it means SQLITE_BUSY how come it is possible i just have a single update statement.There is no race condition or whatever that bother concurrency is not present in my code. it especially happens when i ran my app second time at the first time the update statements works smoothly whenever the file get modified, can anyone help me get rid of this freaking behaviour

please see my below code the update stmnt is to update line NO and the insert stmnt is for inserting newly added text

 rc = sqlite3_open("test.db", &db);
    cout<<"rc"<<rc;--------------------------0
    if(rc>0){
       onej.EJ_Log("ERROR OPRNNING DB");
   }else{
      -
      sql= "UPDATE LAST_UPDATE_LINE SET Line_Number="
           +quotesql(ss.str())+" where ID=1;";--5 after restarting the app
     rc=sqlite3_exec(db, sql.c_str(), callback, 0, &zErrMsg);
     if(rc>0)
     {
         cout<<"iam in ";
         onej.EJ_Log("ERROR INSERTING LINE");
     }
     else{
     sql="INSERT INTO EJ (EJ,UPDATE_TIME) VALUES (?,?);";
     rc = sqlite3_prepare(db,sql.c_str(), sql.size(), &stmt, &pzTest);
     if(rc==SQLITE_OK)
     {

         sqlite3_bind_text(stmt, 1,text.c_str(),text.size(), 0);
         sqlite3_bind_text(stmt, 2,time.c_str(), time.size(), 0);
         sqlite3_step(stmt);
         sqlite3_finalize(stmt);
     }

     else
     {
         onej.EJ_Log("ERROR INSERTING EJ");
     }
     }
     sqlite3_close(db);
   }

CoreData - many-to-many relationship with priorities

I have conceptual question about DB schema. I have 2 entities: Team and Member.

1.Member can belong to many Teams,

2.Team can have many Members.

So it's many-to-many relationship and I've implemented it successfully. Now the client wants to have ordered Members within a Team. So Member can have priority in one team different than in the other.

How properly implemented DB schema should look like? I considering about 2 options:

  • with minimum work effort
  • the proper solution

Any hints are more than welcome. Thanks.

how to create a database and fill it in sqlite android?

I'm having a problem with creating a sqlite database for my android app. I'm using SQLiteOpenHelper class, I have successfully created the database and i am sure of that through logCat but I think I'm failing to create a table and fill it with dummy data just to simulate a login procedure.I Just want to create the database and create a table inside of it and insert some data in the table, i want to do that in the onCreate method of another activity. I will show you what i have tried.

Here is the SQLiteOpenHelper class:-

public class DBHandler extends SQLiteOpenHelper {
private static final int DATABASE_VERSION = 1;
private static final String DATABASE_NAME = "qpc.db";
public static final String TABLE_USERS = "users";
public static final String COLUMN_ID = "_id";
public static final String COLUMN_USERNAME = "username";
public static final String COLUMN_PASSWORD = "password";
public DBHandler dbHandler;


 public DBHandler(Context context, String name, SQLiteDatabase.CursorFactory factory,
                 int version) {
    super(context, DATABASE_NAME, factory, DATABASE_VERSION);
}



@Override
public void onCreate(SQLiteDatabase db) {
    String query = "CREATE TABLE " + TABLE_USERS + "("
            + COLUMN_ID + " INTEGER PRIMARY KEY AUTOINCREMENT,"
            + COLUMN_USERNAME + "Text ,"
            + COLUMN_PASSWORD + "Text );";
    db.execSQL(query);

    ContentValues contentValues = new ContentValues();
    contentValues.put(COLUMN_USERNAME,"test");
    contentValues.put(COLUMN_PASSWORD,"123");
    db.insert(TABLE_USERS,null,contentValues);

}

@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
    db.execSQL("DROP TABLE IF EXISTS " + TABLE_USERS);
    onCreate(db);
}


public void open() throws SQLException
{
    dbHandler.getWritableDatabase();
}


public void close()
{
    dbHandler.close();
}

public boolean login(String username, String password){
    SQLiteDatabase db = getReadableDatabase();
    String query = "SELECT "+ COLUMN_ID + " FROM " + TABLE_USERS +
            " WHERE username= "+ COLUMN_USERNAME +
            " AND password= "+ COLUMN_PASSWORD + ";";


    Cursor cursor = db.rawQuery(query,new String[]{username,password});
    int count = cursor.getCount();
    if(cursor != null) {
        if (count > 0) {
            return true;
        }
    }
    return false;
}

Here is how I call it in the LoginActivity

public class LoginActivity extends ActionBarActivity {
    private static Button loginBtn;
    public static EditText usernameTxt,passwordTxt;
    private static String writtenUsername,writtenPassword;
    private Users user;
    private DBHandler dbHandler;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_login);

    //identifying login button
    loginBtn = (Button) findViewById(R.id.loginButton);

    //identifying username editText
    usernameTxt = (EditText) findViewById(R.id.username);

    //identifying password editText
    passwordTxt = (EditText) findViewById(R.id.password);

    dbHandler = new DBHandler(this, null, null, 1);


    //check if database exists
   File dbtest = getApplicationContext().getDatabasePath("qpc.db");
    if(dbtest.exists())
    {
    Log.d("Database23", "exists");
    }
    else {
        Log.d("Database23", "doesn't exist");
    }
}

//handling login button
public void attemptLogin(View view){
    //getting what was written in username and password editText
    writtenUsername = usernameTxt.getText().toString();
    writtenPassword = passwordTxt.getText().toString();
    try {
        if (!writtenUsername.matches("") && !writtenPassword.matches("")) {
            if (dbHandler.login(writtenUsername, writtenPassword) == true) {
                Toast.makeText(this, "yes", Toast.LENGTH_SHORT).show();
            } else {
                Toast.makeText(this, "no", Toast.LENGTH_SHORT).show();
            }
        } else {
            Toast.makeText(this, "Please fill all fields", Toast.LENGTH_SHORT).show();
        }
    }catch(Exception e){
        Toast.makeText(this,e.getMessage(), Toast.LENGTH_LONG).show();
    }
}

Own database in Android studio SQlite no such table

I am sorry but I read some topics about sqlite but I did not solve my problem. The software is very simply below the code. Please help me to found a solution:

The database and project file, if you want I can send all project by mail.

Below the code os SQLlite for Database creation

CREATE TABLE Items ( _ID INTEGER, LastName TEXT, FirstName TEXT, Address TEXT, City TEXT, PRIMARY KEY(_ID) );

CREATE TABLE android_metadata ( locale TEXT DEFAULT 'en_US' );

MAIN ACTIVITY

package med.myapplication;

import android.content.Context;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import android.widget.TextView;

public class MainActivity extends AppCompatActivity {

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        setContentView(R.layout.main);
        Context context = getApplicationContext();
        SQLiteAdapter miodb = new SQLiteAdapter(this);

        final TextView mioTextView1 = (TextView) findViewById(R.id.textView);

        miodb.openToRead();
        String contenutoletto = miodb.queueAll();
        miodb.close();
        mioTextView1.setText(contenutoletto);
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(R.menu.menu_main, menu);
        return true;
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        // Handle action bar item clicks here. The action bar will
        // automatically handle clicks on the Home/Up button, so long
        // as you specify a parent activity in AndroidManifest.xml.
        int id = item.getItemId();

        //noinspection SimplifiableIfStatement
        if (id == R.id.action_settings) {
            return true;
        }

        return super.onOptionsItemSelected(item);
    }
}

The SQLiteAdapter ---> The app blocks on cursor = sqLiteDatabase.query("Items",null,null,null,null,null,null);

package med.myapplication;

import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteException;
import android.database.sqlite.SQLiteOpenHelper;

import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;


public class SQLiteAdapter  {
    public static String DB_PATH = "/data/data/med.myapplication/databases/";
    public static final String MYDATABASE_NAME = "NuovoDB.db";
    public static final String MYDATABASE_TABLE = "Items";
    public static final int MYDATABASE_VERSION = 1;
    public static final String KEY_CONTENT = "Colonna";


    private SQLiteHelper sqLiteHelper;
    private SQLiteDatabase sqLiteDatabase;

    private Context context;

    public SQLiteAdapter(Context c){
        context = c;
    }

    public SQLiteAdapter openToRead() throws android.database.SQLException {
        sqLiteHelper = new SQLiteHelper(context, MYDATABASE_NAME, null, MYDATABASE_VERSION);
        sqLiteDatabase = sqLiteHelper.getReadableDatabase();
        return this;
    }

    public SQLiteAdapter openToWrite() throws android.database.SQLException {
        sqLiteHelper = new SQLiteHelper(context, MYDATABASE_NAME, null, MYDATABASE_VERSION);
        sqLiteDatabase = sqLiteHelper.getWritableDatabase();
        return this;
    }

    public void close(){
        sqLiteHelper.close();
    }

    public long insert(String content){

        ContentValues contentValues = new ContentValues();
        contentValues.put(KEY_CONTENT, content);
        return sqLiteDatabase.insert(MYDATABASE_TABLE, null, contentValues);
    }

    public int deleteAll(){
        return sqLiteDatabase.delete(MYDATABASE_TABLE, null, null);
    }

    public String queueAll(){
        //String[] columns = new String[]{KEY_CONTENT};
        String path = sqLiteDatabase.getPath();
        sqLiteDatabase.close();
        sqLiteDatabase = SQLiteDatabase.openDatabase(path,null,SQLiteDatabase.OPEN_READWRITE);
        Cursor cursor;

        long size = sqLiteDatabase.getMaximumSize();
        cursor = sqLiteDatabase.query("Items",null,null,null,null,null,null);

        String result = "";

        int index_CONTENT = cursor.getColumnIndex(KEY_CONTENT);
        for(cursor.moveToFirst(); !(cursor.isAfterLast()); cursor.moveToNext()){
            result = result + cursor.getString(index_CONTENT) + "\n";
        }

        return result;
    }

    public class SQLiteHelper extends SQLiteOpenHelper {

        public SQLiteHelper(Context context, String name,
                            SQLiteDatabase.CursorFactory factory, int version) {
            super(context, name, factory, version);
        }

        @Override
        public void onCreate(SQLiteDatabase db) {
            //db.execSQL(SCRIPT_CREATE_DATABASE);
            try {
                if (checkDataBase()) {
                }
                else
                {
                    copyDatabase();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }

        @Override
        public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {

        }

        public void copyDatabase() throws IOException {
            if (checkDataBase()) {
            }else{
                InputStream assetsDB = context.getAssets().open("NuovoDB.db");
                OutputStream dbOut = new FileOutputStream(DB_PATH + "Items");
                byte[] buffer = new byte[1024];
                int length;
                while ((length = assetsDB.read(buffer))>0){
                    dbOut.write(buffer, 0, length);
                }
                dbOut.flush();
                dbOut.close();
                assetsDB.close();
            }
        }

        public boolean checkDataBase(){
            SQLiteDatabase checkDB = null;
            try{
                String myPath = DB_PATH + MYDATABASE_NAME;
                checkDB = SQLiteDatabase.openDatabase(myPath, null, SQLiteDatabase.OPEN_READONLY);
            }catch(SQLiteException e){
                //database does't exist yet.
            }
            if(checkDB != null){
                checkDB.close();
            }
            if (checkDB != null ? true : false) return true;
            else return false;
        }

    }
}

Below the LOGCAT

E/SQLiteLog﹕ (1) no such table: E/AndroidRuntime﹕ FATAL EXCEPTION: main java.lang.RuntimeException: Unable to start activity ComponentInfo{med.myapplication/med.myapplication.MainActivity}: android.database.sqlite.SQLiteException: no such table: Items (code 1): , while compiling: SELECT * FROM Items at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2092) at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2117) at android.app.ActivityThread.access$700(ActivityThread.java:134) at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1218) at android.os.Handler.dispatchMessage(Handler.java:99) at android.os.Looper.loop(Looper.java:137) at android.app.ActivityThread.main(ActivityThread.java:4867) at java.lang.reflect.Method.invokeNative(Native Method) at java.lang.reflect.Method.invoke(Method.java:511) at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1007) at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:774) at dalvik.system.NativeStart.main(Native Method) Caused by: android.database.sqlite.SQLiteException: no such table: Items (code 1): , while compiling: SELECT * FROM Items at android.database.sqlite.SQLiteConnection.nativePrepareStatement(Native Method) at android.database.sqlite.SQLiteConnection.acquirePreparedStatement(SQLiteConnection.java:1013) at android.database.sqlite.SQLiteConnection.prepare(SQLiteConnection.java:624) at android.database.sqlite.SQLiteSession.prepare(SQLiteSession.java:588) at android.database.sqlite.SQLiteProgram.(SQLiteProgram.java:58) at android.database.sqlite.SQLiteQuery.(SQLiteQuery.java:37) at android.database.sqlite.SQLiteDirectCursorDriver.query(SQLiteDirectCursorDriver.java:44) at android.database.sqlite.SQLiteDatabase.rawQueryWithFactory(SQLiteDatabase.java:1314) at android.database.sqlite.SQLiteDatabase.queryWithFactory(SQLiteDatabase.java:1161) at android.database.sqlite.SQLiteDatabase.query(SQLiteDatabase.java:1032) at android.database.sqlite.SQLiteDatabase.query(SQLiteDatabase.java:1200) at med.myapplication.SQLiteAdapter.queueAll(SQLiteAdapter.java:70) at med.myapplication.MainActivity.onCreate(MainActivity.java:23) at android.app.Activity.performCreate(Activity.java:5047) at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1094) at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2056)             at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2117)             at android.app.ActivityThread.access$700(ActivityThread.java:134)             at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1218)             at android.os.Handler.dispatchMessage(Handler.java:99)             at android.os.Looper.loop(Looper.java:137)             at android.app.ActivityThread.main(ActivityThread.java:4867)             at java.lang.reflect.Method.invokeNative(Native Method)             at java.lang.reflect.Method.invoke(Method.java:511)             at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1007)             at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:774)             at dalvik.system.NativeStart.main(Native Method)

Database work slow on android 5

I have been working on device with android 4.4.2 with my database for some time, and I've noticed that when the same database were transfered to device with similar parameters but with Android 5.0.2, database work really sloooow. What could be the reason for that?

receive whole sqlite DB in android [duplicate]

This question already has an answer here:

I have to make a big android project and I need to work a lot with sqlite. I need to know if there is a possibility to receive a whole sqlite DB from server, I don't want to get data in objects and then to insert them in DB. If somebody did that, feel free to share the experience.

Is the order of comparisant important in a join query?

I usually code a join query as follows:

Select 'field' from 'table' join 'references' on 'table'.'id' = 'references'.'reference'

Now suddenly I wondered, does the order in which you do on 'table'.'id' = 'references'.'reference' have an impact on execution speed or not?

I mainly use sqlserver, mysql and sqlite and I can imagine there might be different implementations in those three if there is a difference at all.

So basically it boils down to:

is on 'table'.'id' = 'references'.'reference' different from on 'references'.'reference' = 'table'.'id'

This question is purely out of curiosity, I'd like to know how it is treated so I can understand it better.

dimanche 30 août 2015

create local db table structure using remote db and get all data

I have a database already defined in remote database (MySQL), it contains only 50 tables and it can be increased when user add some new classes on server side.

Part of my function is to write an Android application that will be checking if the local db existed or not, if not , it will create the table based on the remote's db table structure into sqlite, and if existed then fetch the newly added tables and any changes of other tables. I want to make like this one control panel. The problem is, how can I create a table same as the one in my remote database without hard coding the sql statement. How can I do this?

Detecting User Switch in Android

I have a requirement of detecting user switch in an Android application. Basically whenever there is a switch from Owner to Restricted Profile User or vice versa, I am planning to store the previous user in SQLite database and query and verify if there is a switch. I have already tried How to detect switching between users but it did not help me as my requirement is a bit different (Requirement of Application Kill on Profile Switch). Is there any Android API to query and get the current user ?

Copy Db from assets folder containing non english characters in android sqllite

I am copying a db from assets folder. This db contains non english characters.

I get the following Error 08-31 10:44:54.728: E/DefaultDatabaseErrorHandler(8391) : Corruption reported by sqlite on database: /data/data/com.test.testpack/databases/mydbname 08-31 10:44:54.738: E/DefaultDatabaseErrorHandler(8391): deleting the database file: /data/data/com.test.testpack/databases/mydbname

How to get pairs from sqlite

I am a database and I am just playing with sqlite3 for a group project.

I have two tables that look something like this:

Table 1:

tv_show_id, tv_show_rating

Table 2:

tv_show_id, cast_id

Each tv_show has 1 unique id, but in table two there are multiple cast_ids for each tv_show

So we have something like this:

Table 1: 1234, 90 5678, 88

Table 2: 1234, "person 1" 1234, "person 2" 5678, "person 1" 5678, "person 3"

I want the following results: (person a, person b, # of shows together)

(person 1, person 2, 1) (person 1, person 3, 1) (person 2, person 1, 1) (person 2, person 3, 0) (person 3, person 1, 1) (person 3, person 2, 0)

How can i use JOINS to get these results?

THANK YOU!

Why does DbFlow can not save objects without being assigned to a variable?

Code below works as expected

Customer x = new Customer();
x.name = "yasin";
x.save();

But this leads to an app crash

new Customer() {
  {
     name = "yasin";
  }
}.save();

Error detail in logcat:

com.raizlabs.android.dbflow.structure.InvalidDBConfiguration: 
Table: com.example.yasin.myapplication.MainActivityFragment$1$1 is not
registered with a Database. Did you forget the @Table annotation?

Why does this happen? Is it some bug with DbFlow or there is something I don't know about Java language?

django.db.utils.OperationalError: parser stack overflow

I have a re-usable django application which should support python2.7, python 3.x and pypy. I developed it in python 2.7 at the beginning and all of my tests are worked very well. I also made them worked in python3.3 too. But I have a problem with python3.4, pypy, pypy3;

django.db.utils.OperationalError: parser stack overflow

My tests run on sqlite3. I check the trace, I just could guess that it is about query size. I couldn't find any solution to solve this problem.

I overrided builtin sqlite3 code in my python3.4 environment to pring which sql, does it raise the error for. It is really big sql. It really doesn't matter, you don't need to check the sql, I just post it in here to show how it is big. This can also be bigger than that. Because queryset is building on runtime in for loop.

By the way, as I told it before, There is no problem with python2.7 and python3.3. Problem raises for others.

Are there any configuration to handle this?

Here is the sql:

SELECT "river_approvement".
"id", "river_approvement".
"content_type_id", "river_approvement".
"object_id", "river_approvement".
"field", "river_approvement".
"meta_id", "river_approvement".
"transactioner_id", "river_approvement".
"transaction_date", "river_approvement".
"status", "river_approvement".
"skip", "river_approvement".
"order", "river_approvement".
"enabled"
FROM "river_approvement"
INNER JOIN "river_approvementmeta"
ON("river_approvement".
    "meta_id" = "river_approvementmeta".
    "id") INNER JOIN "river_transition"
ON("river_approvementmeta".
    "transition_id" = "river_transition".
    "id") WHERE("river_approvement".
    "field" = ? AND "river_transition".
    "source_state_id"
    IN(SELECT AB0.
        "id"
        FROM "river_state"
        AB0 WHERE AB0.
        "id"
        IN(SELECT AA2.
            "destination_state_id"
            FROM "river_approvement"
            AA0 INNER JOIN "river_approvementmeta"
            AA1 ON(AA0.
                "meta_id" = AA1.
                "id") INNER JOIN "river_transition"
            AA2 ON(AA1.
                "transition_id" = AA2.
                "id") WHERE(AA0.
                "field" = ? AND AA2.
                "source_state_id"
                IN(SELECT Z0.
                    "id"
                    FROM "river_state"
                    Z0 WHERE Z0.
                    "id"
                    IN(SELECT Y2.
                        "destination_state_id"
                        FROM "river_approvement"
                        Y0 INNER JOIN "river_approvementmeta"
                        Y1 ON(Y0.
                            "meta_id" = Y1.
                            "id") INNER JOIN "river_transition"
                        Y2 ON(Y1.
                            "transition_id" = Y2.
                            "id") WHERE(Y0.
                            "field" = ? AND Y2.
                            "source_state_id"
                            IN(SELECT X0.
                                "id"
                                FROM "river_state"
                                X0 WHERE X0.
                                "id"
                                IN(SELECT W2.
                                    "destination_state_id"
                                    FROM "river_approvement"
                                    W0 INNER JOIN "river_approvementmeta"
                                    W1 ON(W0.
                                        "meta_id" = W1.
                                        "id") INNER JOIN "river_transition"
                                    W2 ON(W1.
                                        "transition_id" = W2.
                                        "id") WHERE(W0.
                                        "field" = ? AND W2.
                                        "source_state_id"
                                        IN(SELECT V0.
                                            "id"
                                            FROM "river_state"
                                            V0 WHERE V0.
                                            "id"
                                            IN(SELECT U2.
                                                "destination_state_id"
                                                FROM "river_approvement"
                                                U0 INNER JOIN "river_approvementmeta"
                                                U1 ON(U0.
                                                    "meta_id" = U1.
                                                    "id") INNER JOIN "river_transition"
                                                U2 ON(U1.
                                                    "transition_id" = U2.
                                                    "id") WHERE(U0.
                                                    "field" = ? AND U2.
                                                    "source_state_id"
                                                    IN( ? ) AND U0.
                                                    "object_id" = ? AND U0.
                                                    "content_type_id" = ? ))) AND W0.
                                        "object_id" = ? AND W0.
                                        "content_type_id" = ? ))) AND Y0.
                            "object_id" = ? AND Y0.
                            "content_type_id" = ? ))) AND AA0.
                "object_id" = ? AND AA0.
                "content_type_id" = ? ))) AND "river_approvement".
    "object_id" = ? AND "river_approvement".
    "content_type_id" = ? )

UPDATE Query not Working with Android App

I am writing an Android app that needs to execute an UPDATE query on a SQLite database, but for some reason, the query is not having any effect when I run it.

Here's the function that is supposed to execute the query.

public void query()
{
    try
    {
        cursor = this.db.rawQuery("UPDATE data SET saved=1 WHERE number=1", null);
    }
    catch(SQLiteException e)
    {
        System.out.println("Database Query Failed: " + e.getCause().getMessage());
    }
}

Although the query does not work, I do not get any output from the catch clause, and adding an additional catch to check for Exception does not output anything either.

What's the problem? How can I get UPDATE queries to work? I have not tried executing an INSERT query, but I will need to do that as well later on. Will I have similar issues with all queries that write to the database?

How to Execute SQLite Queries on Firefox Mobile Profile Data

Thanks for your time.

I am on Firefox Mobile.

I plan to use a restartless approach using the add-on node.js tools.

I need to pull profile data in my app, some of which requires direct SQL due to spotty mobile support according to: http://ift.tt/1PFyEqT

I plan to use indexed-db, thinking that this will give me the ability to run SQLite queries against existing user profile data (mostly needed for reading).

Am I on the right track? I have also seen simple-storage. Is that a better tool?

How to broadcast a database present on a mobile through LAN?

I have a database with a single table named sensors on an android mobile, being continuously updated with real time sensor readings.

I want to make a web server on the mobile so that I can read these readings (database) from another computer on the LAN by entering the mobile's ip.

Is my approach correct? If so, please guide me how to acheive this.

Submitting several commands to sqlite3 in a single command at cli

On Mac OS Yosemite I use the following version of SQLite:

# sqlite3 --version
3.8.5 2014-08-15 22:37:57 c8ade949d4a2eb3bba4702a4a0e17b405e9b6ace

And I have 2 commands which run fine at sqlite3 prompt:

.read android.sql
.import words.txt dict

The first command above creates 3 tables I need in my Android app.

The second command above fills the dict table from a text file.

How can I run both commands at the cli?

I have tried following separators: semicolon, slash and \\n but this does not work:

echo ".read android.sql / .import words.txt dict" | sqlite3 my.db 
Usage: .read FILE

Cordova/Ionic pre populated SQLite database issue

So I have a Ionic app I want to deploy with pre populated SQLite database(tried populating it manually, but it's way to slow). So I decided to use the Cordova-sqlite-storage plugin(http://ift.tt/1O3yCJy). I have a dump file witch opens just fine with no errors, but when I try to fetch anything I get no results. Anyways, here's my code:

In app.js:

app.run(function($ionicPlatform) {
    $ionicPlatform.ready(function() {
        db = window.sqlitePlugin.openDatabase({name: "mydb", createFromLocation: 1});
    });
})

In controllers.js

.controller("HomeController", function($scope,Test){
    $scope.test = function(){
        Test.getAlchohol().then(function(res){
            console.log(res.length);
        });
    };
})

My db fetching service:

.factory('Test', function($cordovaSQLite){
    var arr = [];
    return{
        getAlchohol:function(){
            var query = "SELECT * FROM Alchohol";
            return $cordovaSQLite.execute(db, query, []).then(function(res){
                arr = res.rows;
                return arr;
            }, function(err){
                console.error(err);
            });
        }
    }
})

And my dump file goes something like this:

PRAGMA synchronous = OFF;
PRAGMA journal_mode = MEMORY;
BEGIN TRANSACTION;
CREATE TABLE "Alchohol" (
  "id" int(11) NOT NULL ,
  "intoxication" int(11) NOT NULL,
  "text_id_1" int(11) NOT NULL,
  "text_id_2" int(11) NOT NULL,
  "text_id_3" int(11) NOT NULL,
  PRIMARY KEY ("id")
);
INSERT INTO "Alchohol" VALUES (1,0,20,21,22);
INSERT INTO "Alchohol" VALUES (2,1,18,19,22);
INSERT INTO "Alchohol" VALUES (3,2,23,24,25);
INSERT INTO "Alchohol" VALUES (4,3,26,24,25);
INSERT INTO "Alchohol" VALUES (5,4,27,28,25);
INSERT INTO "Alchohol" VALUES (6,5,29,30,25);
INSERT INTO "Alchohol" VALUES (7,6,29,31,32);
INSERT INTO "Alchohol" VALUES (8,7,33,31,34);
INSERT INTO "Alchohol" VALUES (9,8,35,31,36);
INSERT INTO "Alchohol" VALUES (10,9,33,31,37);
END TRANSACTION;

I've tried every possible solution I found online and nothing worked for me. Any help will be greatly appreciated..

Save database with Sqlit3 extesion in DB Browse

I'm using DB Browser to make a database

But when I Save it , it saved with sql extension

I need to save it with .sqlit3 extension to use it in android app

How can I use it

Is it good to use Core Data with Swift?

Hi Everyone,

I'm working on a project where I need to store data locally and for that I'm actually thinking of using CoreData but when I did little research on it, I found some blog and post saying "the tools are still immature. In general, the tools around Xcode and Swift are somewhat unstable, and though they are improving all the time, it can be frustrating".

Now, I'm lil confuse about using core data or Shall I go with SQLite?

So please guys, who have already used CoreData with Swift, guide me through the challenges I might face with CoreData or in making the better choice.

Update function not working correctly [duplicate]

This question already has an answer here:

I made a class DBHelper.java for implementing SQLiteDatabase. But it is not working and giving the error:

android.database.sqlite.SQLiteException: no such column: Reading1 (code 1): , while compiling: UPDATE sensors SET Reading3=?,Status=?,Reading2=?,Reading1=?,Reading4=? WHERE Name = ?

I can't seem to find the way around this.

My code is:

public class DBHelper extends SQLiteOpenHelper {
public static final String DATABASE_NAME = "Readings.db";
public static final String SENSORS_TABLE_NAME = "sensors";
public static final String SENSORS_COLUMN_ID = "Id";
public static final String SENSORS_COLUMN_NAME = "Name";
public static final String SENSORS_COLUMN_1 = "Reading1";
public static final String SENSORS_COLUMN_2 = "Reading2";
public static final String SENSORS_COLUMN_3 = "Reading3";
public static final String SENSORS_COLUMN_4 = "Reading4";
public static final String SENSORS_COLUMN_STATUS = "Status";

public DBHelper(Context context) {
    super(context, DATABASE_NAME, null, 1);
}

@Override
public void onCreate(SQLiteDatabase db) {
    // TODO Auto-generated method stub
    db.execSQL("CREATE TABLE " + SENSORS_TABLE_NAME + "(" + SENSORS_COLUMN_ID + " INTEGER PRIMARY KEY," + SENSORS_COLUMN_NAME + " TEXT" +
                    SENSORS_COLUMN_1 + " REAL," + SENSORS_COLUMN_2 + " REAL," +
                    SENSORS_COLUMN_3 + " REAL," + SENSORS_COLUMN_4 + " REAL," + SENSORS_COLUMN_STATUS + " INTEGER)"
    );
    db.setLocale(Locale.getDefault());
    db.setVersion(1);
}

@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
    // TODO Auto-generated method stub
    db.execSQL("DROP TABLE IF EXISTS " + SENSORS_TABLE_NAME);
    onCreate(db);
}

public boolean insertSensor(String name, boolean status) {
    SQLiteDatabase db = this.getWritableDatabase();
    ContentValues contentValues = new ContentValues();
    contentValues.put("Name", name);
    contentValues.put("Reading1", 0);
    contentValues.put("Reading2", 0);
    contentValues.put("Reading3", 0);
    contentValues.put("Reading4", 0);
    contentValues.put("Status", status);
    db.insert("sensors", null, contentValues);
    return true;
}

public Cursor getData(String Name) {
    SQLiteDatabase db = this.getReadableDatabase();
    Cursor res = db.rawQuery("select * from sensors where Name='" + Name + "'", null);
    return res;
}

public boolean updateSensor(String Name, float Reading1, float Reading2, float Reading3, float Reading4, boolean Status) {
    SQLiteDatabase db = this.getWritableDatabase();
    ContentValues contentValues = new ContentValues();
    contentValues.put(SENSORS_COLUMN_1, Reading1);
    contentValues.put(SENSORS_COLUMN_2, Reading2);
    contentValues.put(SENSORS_COLUMN_3, Reading3);
    contentValues.put(SENSORS_COLUMN_4, Reading4);
    contentValues.put(SENSORS_COLUMN_STATUS, Status);
    db.update("sensors", contentValues, "Name = ?", new String[]{Name});
    return true;
}

}

android sql update not working

try {
        open();
        ContentValues values = new ContentValues();
        values.put(column_name, value);
        database.beginTransaction();
        database.update(MySQLiteHelper.TABLE_NAME, values, MySQLiteHelper.COLUMN_ID + " = " + whereClause,null);
        database.setTransactionSuccessful();
    } catch (SQLException e) {
        e.printStackTrace();
    } finally {
        database.endTransaction();
    }
    close();

The previous code would be equal to this query :

UPDATE options SET instant = 0 WHERE _id = 1

But the change is never applied. I check the table before and after the update but the values are the same, can anyone suggest anything?

SQLite extracting day from date issue

I have a DATE field in my database with format 'YYYY-MM-DD'. Now I want to extract only 'day' from that day i.e. 'DD'. My table name is 'date' and the column name where date is stored is 'lastDonated'. How do i do it... please look these codes for more details.

public String day() {
    String b = "";
    SQLiteDatabase db = getWritableDatabase();
    String query = "???(what to place in here?)";

    Cursor c = db.rawQuery(query, null);
    c.moveToFirst();

    b = c.getString(c.getColumnIndex("lastDonated"));

    c.moveToNext();

    return b;

}

samedi 29 août 2015

DSQLITE_THREADSAFE=2 option of SQLIte

I need to understand usage of DSQLITE_THREADSAFE=2 option in SQLite. Can anyone provide a simple c program in which multi-threads access the same database using SQLite.

Android Studios SQLiteDatabase Manuel Input

I am working on an app screen that just list Restaurant names. I was going to use Recycle view but I know that not a good place to store long term data. Therefore I am using the SQLiteDataBase. I already made the Database but I can't find how to manually input data without having the user of the app do it. Any help will be greatly appreciated. (I am still fairly new to Android Studios)

Creating Android database journal file with SQLite browser

I'm creating a database file with SQLiteBrowser in order to have better visibility of my database structure and create the databases for my apps faster. However, I know that SQL on Android creates a journal file for rolling back on if a process has been interrupted. If I use the database file I've created, will Android produce a journal file for my database once my app is run or will I have to create it through other means?

Sum Sqlite Problems

I want to get the sum of the amount when the status is equal to "G" but I value returned is only the first data.

CODE:

impVentas = bd2.rawQuery("SELECT ROUND(SUM(MONTO),2) FROM CUERPO WHERE ESTADO='G' AND ENCA_ID="+idFact, null);

This code returns only the first data CUERPO and I need all the data.

SQLite DB Size Column Data Type Considerations

I'm working with an SQLite DB where all columns are of NVARCHAR data type.

Coming from MS SQL background I know that NVARCHAR has additional baggage associated with it, my first impulse is to refactor most column types to have concrete string lengths enforced (most are under 50 chars long).

But at the same time I know that SQLite treats things a bit differently.

So my question is should I change/refactor the column types? And by doing so is there anything to gain in terms of disk space or performance in SQLite?

DB runs on Android/iOS devices.

Thanks!

How show process dialog for get data from Sqlite and show in listview

I want to when the button is clicked, a dialog processor is displayed as long as the list view full list after the jump view the other processor lines to be displayed. please guide me .

this code

    button.setOnClickListener(new OnClickListener() {

        @Override
        public void onClick(View v) {


         openandquery();
        displayResultList();



        }
    });


public void openandquery() {

     baseHelper= new DataBaseHelper(contex);
     boolean exists=  baseHelper.checkDataBase();


      if (exists){

     message.messages(contex, "True : There database ");

        try {
            boolean open= baseHelper.openDataBase();


                  if (open)
                  {
                  message.messages(contex, "True : database open");

                      Cursor cursor= baseHelper.getTestData(edittext.getText().toString());
                        countf=cursor.getCount();
                      if (countf<=0)message.messages(contex, "Not Found");
                  }

                      else 
                      message.messages(contex, "False : NO database open");
        } catch (SQLException e) {

            message.messages(contex, "Error Open  : " + e.getMessage());

        }   


      }

         else 
                  message.messages(contex, "False : There is no database");

    }





private void displayResultList() {

        try {

        array=baseHelper.results;
        tView.setText("Size : " +array.size());

            try {


                 arrayAdapter=new display();
                arrayAdapter.notifyDataSetChanged();
                listV.setAdapter(arrayAdapter);

            } catch (Exception e) {
             message.messages(contex, e.getMessage());
            }

            listV.setTextFilterEnabled(true);

        } catch (Exception e) {
             message.messages(contex, e.getMessage());
        }



        }

this code called in openandquery

 public Cursor getTestData(String phone)
    { 

        String  sql ="SELECT * FROM cusomer WHERE address!='' and key='"+p;
         message.message(mContext, ":"+p+":");
        try
        {
             if (p.isEmpty())
             {sql="SELECT * FROM cusomer WHERE address!=''";


             }


            Cursor mCur = mDataBase.rawQuery(sql, null);

            message.message(mContext, mCur.getCount()+"");
            if (mCur!=null)
            {

                if (mCur.moveToFirst()){
                              try {

                    do{
                          String d=mCur.getString(mCur.getColumnIndex("address"));
                          String p= mCur.getString(mCur.getColumnIndex("phone")); 
                          int    k=mCur.getInt(mCur.getColumnIndex("key"));
                          int    i=mCur.getInt(mCur.getColumnIndex("_id"));
                          long t=mCur.getLong(mCur.getColumnIndex("registertime"));

                          results.add(new msgstore(d,p,k,i,t));


                      }while(mCur.moveToNext());



                } catch (Exception e) {
                    message.message(mContext, e.getMessage());

                }
                }

           mCur.close();

            }



                return mCur;





        }
        catch (SQLException mSQLException) 
        {
            message.message(mContext, "getTestData >>"+ mSQLException.toString());

            throw mSQLException;
        }






    }

Android: date formatting method sets time to incorrect time zone

I wrote a date formatting method that is used in a few different views within the app. The problem is that the method returns a time that is four hours behind the time that is inputted by the user.

Here's the relevant part of the method I use to set the original timestamp via the app's Date and TimePicker widgets.

calendar.set(Calendar.MONTH, datePicker.getMonth());
                                calendar.set(Calendar.DAY_OF_MONTH, datePicker.getDayOfMonth());
                                calendar.set(Calendar.YEAR, datePicker.getYear());

                                calendar.set(Calendar.HOUR_OF_DAY, timePicker.getCurrentHour());
                                calendar.set(Calendar.MINUTE, timePicker.getCurrentMinute());

                                // Bitmask used to determine timestamp format
                                int displayMask = DateUtils.FORMAT_SHOW_TIME | DateUtils.FORMAT_SHOW_DATE | DateUtils.FORMAT_SHOW_YEAR;
                                String timestamp = DateUtils.formatDateTime(editActivity.getApplicationContext(), calendar.getTimeInMillis(), displayMask);
                                mEditDueDate.setText(timestamp); 

For Example, the would return July 27, 2015, 9:50 PM

This timestamp is then saved in a SQLite database as a datetime string via

public DateTime getTaskDueDate() {
        mDueDate = (EditText) getActivity().findViewById(R.id.task_due_date);
        SimpleDateFormat sdf = new SimpleDateFormat("MMMM dd, yyyy, h:mm a", Locale.US);
        Date parseDate;
        try {
        parseDate = sdf.parse(mDueDate.getText().toString());
    } catch (ParseException e) {
            Log.getStackTraceString(e);
            return null;
        }
        return new DateTime(parseDate);
    }

The formatting method I use in other parts of the app is,

public String formatDueDate(String queryResponse) {
        DateFormat iso8601Format = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSSZ", Locale.US);
        Date date = new Date();
        try {
             date = iso8601Format.parse(queryResponse);
        } catch (ParseException e) {
            Log.e("TAG", "Parsing ISO8601 datetime failed", e);
        }

        long when = date.getTime();
        int flags = 0;
        flags |= android.text.format.DateUtils.FORMAT_SHOW_TIME;
        flags |= android.text.format.DateUtils.FORMAT_SHOW_DATE;
        flags |= android.text.format.DateUtils.FORMAT_ABBREV_MONTH;
        flags |= android.text.format.DateUtils.FORMAT_SHOW_YEAR;

       return android.text.format.DateUtils.formatDateTime(mContext,
                when + TimeZone.getDefault().getOffset(when), flags);

    }

However, this returns July 27 2015, 4:50 PM. Why does formatDueDatereturn a timestamp that is always four hours behind the user inputted timestamp?

How to display in a ListView specific data stored in a external txt?

everybody! I'll ask you again how to implement a ListView in my main activity that shows all entries from KEY_WORD column. Please, I need a full explanation - the nuts and bolts of process (step by step, because I'm a newbie). I just want to solve this.

This is a screenshot from my application. I have a Searchview function that works perfectly. The application is ok and it's based on Searchable Dictionary.

without listview

But as you see, there is no ListView on the screen. I know how to create a Layout for this. But the problem is the Listview doesn't get the entries from KEY_WORD column (database). I don't know how to do this. I need some help - step by step, please guys.

This is a screenshot how I want to show in my application. It should load and display all words stored in my database from WORD column in a list.

with listview

And this is my entire source code:

BancoDicionario.java (Main Activity)

public class BancoDictionary extends Activity {

private TextView mTextView;
private ListView mListView;

@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.main);

    mTextView = (TextView) findViewById(R.id.text);
    mListView = (ListView) findViewById(R.id.list);

    handleIntent(getIntent());
}

@Override
protected void onNewIntent(Intent intent) {
    handleIntent(intent);
}

private void handleIntent(Intent intent) {
    if (Intent.ACTION_VIEW.equals(intent.getAction())) {
        Intent wordIntent = new Intent(this, WordActivity.class);
        wordIntent.setData(intent.getData());
        startActivity(wordIntent);
    } else if (Intent.ACTION_SEARCH.equals(intent.getAction())) {
        String query = intent.getStringExtra(SearchManager.QUERY);
        showResults(query);
    }
}

private void showResults(String query) {

    Cursor cursor = managedQuery(DictionaryProvider.CONTENT_URI, null, null,
                            new String[] {query}, null);

    if (cursor == null) {
        mTextView.setText(getString(R.string.no_results, new Object[] {query}));
    } else {
        int count = cursor.getCount();
        String countString = getResources().getQuantityString(R.plurals.search_results,
                                count, new Object[] {count, query});
        mTextView.setText(countString);

        String[] from = new String[] { DictionaryDatabase.KEY_WORD,
                                       DictionaryDatabase.KEY_DEFINITION };

        int[] to = new int[] { R.id.word,
                               R.id.definition };

        SimpleCursorAdapter words = new SimpleCursorAdapter(this,
                                      R.layout.result, cursor, from, to);
        mListView.setAdapter(words);

        mListView.setOnItemClickListener(new OnItemClickListener() {

            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                Intent wordIntent = new Intent(getApplicationContext(), WordActivity.class);
                Uri data = Uri.withAppendedPath(DictionaryProvider.CONTENT_URI,
                                                String.valueOf(id));
                wordIntent.setData(data);
                startActivity(wordIntent);
            }
        });
    }
}

@Override
public boolean onCreateOptionsMenu(Menu menu) {
    MenuInflater inflater = getMenuInflater();
    inflater.inflate(R.menu.main, menu);

    if(Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB){
        SearchManager searchManager = (SearchManager) getSystemService(Context.SEARCH_SERVICE);
        SearchView searchView = (SearchView) menu.findItem(R.id.search).getActionView();
        searchView.setSearchableInfo(searchManager.getSearchableInfo(getComponentName()));
        searchView.setIconifiedByDefault(false);
    }

    return true;
}

@Override
public boolean onOptionsItemSelected(MenuItem item) {
    switch (item.getItemId()) {
        case R.id.search:
            onSearchRequested();
            return true;
        default:
            return false;
    }
}
}

DictionaryDatabase.java

public class DictionaryDatabase {
private static final String TAG = "DictionaryDatabase";

public static final String KEY_WORD = SearchManager.SUGGEST_COLUMN_TEXT_1;
public static final String KEY_DEFINITION = SearchManager.SUGGEST_COLUMN_TEXT_2;

private static final String DATABASE_NAME = "dictionary";
private static final String FTS_VIRTUAL_TABLE = "FTSdictionary";
private static final int DATABASE_VERSION = 2;

private final DictionaryOpenHelper mDatabaseOpenHelper;
private static final HashMap<String,String> mColumnMap = buildColumnMap();

public DictionaryDatabase(Context context) {
    mDatabaseOpenHelper = new DictionaryOpenHelper(context);
}

private static HashMap<String,String> buildColumnMap() {
    HashMap<String,String> map = new HashMap<String,String>();
    map.put(KEY_WORD, KEY_WORD);
    map.put(KEY_DEFINITION, KEY_DEFINITION);
    map.put(BaseColumns._ID, "rowid AS " +
            BaseColumns._ID);
    map.put(SearchManager.SUGGEST_COLUMN_INTENT_DATA_ID, "rowid AS " +
            SearchManager.SUGGEST_COLUMN_INTENT_DATA_ID);
    map.put(SearchManager.SUGGEST_COLUMN_SHORTCUT_ID, "rowid AS " +
            SearchManager.SUGGEST_COLUMN_SHORTCUT_ID);
    return map;
}

public Cursor getWord(String rowId, String[] columns) {
    String selection = "rowid = ?";
    String[] selectionArgs = new String[] {rowId};

    return query(selection, selectionArgs, columns);

}

public Cursor getWordMatches(String query, String[] columns) {
    String selection = KEY_WORD + " MATCH ?";
    String[] selectionArgs = new String[] {query+"*"};

    return query(selection, selectionArgs, columns);

}

private Cursor query(String selection, String[] selectionArgs, String[] columns) {

    SQLiteQueryBuilder builder = new SQLiteQueryBuilder();
    builder.setTables(FTS_VIRTUAL_TABLE);
    builder.setProjectionMap(mColumnMap);

    Cursor cursor = builder.query(mDatabaseOpenHelper.getReadableDatabase(),
            columns, selection, selectionArgs, null, null, null);

    if (cursor == null) {
        return null;
    } else if (!cursor.moveToFirst()) {
        cursor.close();
        return null;
    }
    return cursor;
}

private static class DictionaryOpenHelper extends SQLiteOpenHelper {

    private final Context mHelperContext;
    private SQLiteDatabase mDatabase;

    private static final String FTS_TABLE_CREATE =
                "CREATE VIRTUAL TABLE " + FTS_VIRTUAL_TABLE +
                " USING fts3 (" +
                KEY_WORD + ", " +
                KEY_DEFINITION + ");";

    DictionaryOpenHelper(Context context) {
        super(context, DATABASE_NAME, null, DATABASE_VERSION);
        mHelperContext = context;
    }

    @Override
    public void onCreate(SQLiteDatabase db) {
        mDatabase = db;
        mDatabase.execSQL(FTS_TABLE_CREATE);
        loadDictionary();
    }

    private void loadDictionary() {
        new Thread(new Runnable() {
            public void run() {
                try {
                    loadWords();
                } catch (IOException e) {
                    throw new RuntimeException(e);
                }
            }
        }).start();
    }

    private void loadWords() throws IOException {
        Log.d(TAG, "Loading words...");
        final Resources resources = mHelperContext.getResources();
        InputStream inputStream = resources.openRawResource(R.raw.definitions);
        BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream));

        try {
            String line;
            while ((line = reader.readLine()) != null) {
                String[] strings = TextUtils.split(line, "//");
                if (strings.length < 2) continue;
                long id = addWord(strings[0].trim(), strings[1].trim());
                if (id < 0) {
                    Log.e(TAG, "unable to add word: " + strings[0].trim());
                }
            }
        } finally {
            reader.close();
        }
        Log.d(TAG, "DONE loading words.");
    }


    public long addWord(String word, String definition) {
        ContentValues initialValues = new ContentValues();
        initialValues.put(KEY_WORD, word);
        initialValues.put(KEY_DEFINITION, definition);

        return mDatabase.insert(FTS_VIRTUAL_TABLE, null, initialValues);
    }

    @Override
    public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
        Log.w(TAG, "Upgrading database from version " + oldVersion + " to "
                + newVersion + ", which will destroy all old data");
        db.execSQL("DROP TABLE IF EXISTS " + FTS_VIRTUAL_TABLE);
        onCreate(db);
    }
}

}

DictionaryProvider.java

public class DictionaryProvider extends ContentProvider {
String TAG = "DictionaryProvider";

public static String AUTHORITY = "com.ec.idiomas.searchabledict.DictionaryProvider";
public static final Uri CONTENT_URI = Uri.parse("content://" + AUTHORITY + "/dictionary");

public static final String WORDS_MIME_TYPE = ContentResolver.CURSOR_DIR_BASE_TYPE +
                                              "/vnd.ec.idiomas.searchabledict";
public static final String DEFINITION_MIME_TYPE = ContentResolver.CURSOR_ITEM_BASE_TYPE +
                                                   "/vnd.eci.idiomas.searchabledict";

private DictionaryDatabase mDictionary;

private static final int SEARCH_WORDS = 0;
private static final int GET_WORD = 1;
private static final int SEARCH_SUGGEST = 2;
private static final int REFRESH_SHORTCUT = 3;
private static final UriMatcher sURIMatcher = buildUriMatcher();

private static UriMatcher buildUriMatcher() {
    UriMatcher matcher =  new UriMatcher(UriMatcher.NO_MATCH);
    matcher.addURI(AUTHORITY, "dictionary", SEARCH_WORDS);
    matcher.addURI(AUTHORITY, "dictionary/#", GET_WORD);
    matcher.addURI(AUTHORITY, SearchManager.SUGGEST_URI_PATH_QUERY, SEARCH_SUGGEST);
    matcher.addURI(AUTHORITY, SearchManager.SUGGEST_URI_PATH_QUERY + "/*", SEARCH_SUGGEST);

    matcher.addURI(AUTHORITY, SearchManager.SUGGEST_URI_PATH_SHORTCUT, REFRESH_SHORTCUT);
    matcher.addURI(AUTHORITY, SearchManager.SUGGEST_URI_PATH_SHORTCUT + "/*", REFRESH_SHORTCUT);
    return matcher;
}

@Override
public boolean onCreate() {
    mDictionary = new DictionaryDatabase(getContext());
    return true;
}

@Override
public Cursor query(Uri uri, String[] projection, String selection, String[] selectionArgs,
                    String sortOrder) {

    switch (sURIMatcher.match(uri)) {
        case SEARCH_SUGGEST:
            if (selectionArgs == null) {
              throw new IllegalArgumentException(
                  "selectionArgs must be provided for the Uri: " + uri);
            }
            return getSuggestions(selectionArgs[0]);
        case SEARCH_WORDS:
            if (selectionArgs == null) {
              throw new IllegalArgumentException(
                  "selectionArgs must be provided for the Uri: " + uri);
            }
            return search(selectionArgs[0]);
        case GET_WORD:
            return getWord(uri);
        case REFRESH_SHORTCUT:
            return refreshShortcut(uri);
        default:
            throw new IllegalArgumentException("Unknown Uri: " + uri);
    }
}

private Cursor getSuggestions(String query) {
  query = query.toLowerCase();
  String[] columns = new String[] {
      BaseColumns._ID,
      DictionaryDatabase.KEY_WORD,

      SearchManager.SUGGEST_COLUMN_INTENT_DATA_ID};

  return mDictionary.getWordMatches(query, columns);
}

private Cursor search(String query) {
  query = query.toLowerCase();
  String[] columns = new String[] {
      BaseColumns._ID,
      DictionaryDatabase.KEY_WORD,
      DictionaryDatabase.KEY_DEFINITION};

  return mDictionary.getWordMatches(query, columns);
}

private Cursor getWord(Uri uri) {
  String rowId = uri.getLastPathSegment();
  String[] columns = new String[] {
      DictionaryDatabase.KEY_WORD,
      DictionaryDatabase.KEY_DEFINITION};

  return mDictionary.getWord(rowId, columns);
}

private Cursor refreshShortcut(Uri uri) {

  String rowId = uri.getLastPathSegment();
  String[] columns = new String[] {
      BaseColumns._ID,
      DictionaryDatabase.KEY_WORD,
      DictionaryDatabase.KEY_DEFINITION,
      SearchManager.SUGGEST_COLUMN_SHORTCUT_ID,
      SearchManager.SUGGEST_COLUMN_INTENT_DATA_ID};

  return mDictionary.getWord(rowId, columns);
}

@Override
public String getType(Uri uri) {
    switch (sURIMatcher.match(uri)) {
        case SEARCH_WORDS:
            return WORDS_MIME_TYPE;
        case GET_WORD:
            return DEFINITION_MIME_TYPE;
        case SEARCH_SUGGEST:
            return SearchManager.SUGGEST_MIME_TYPE;
        case REFRESH_SHORTCUT:
            return SearchManager.SHORTCUT_MIME_TYPE;
        default:
            throw new IllegalArgumentException("Unknown URL " + uri);
    }
}

@Override
public Uri insert(Uri uri, ContentValues values) {
    throw new UnsupportedOperationException();
}

@Override
public int delete(Uri uri, String selection, String[] selectionArgs) {
    throw new UnsupportedOperationException();
}

@Override
public int update(Uri uri, ContentValues values, String selection, String[] selectionArgs) {
    throw new UnsupportedOperationException();
}



}

WordActivity.java

public class WordActivity extends Activity {
@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.word);

    if(Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB){
        ActionBar actionBar = getActionBar();
        actionBar.setDisplayHomeAsUpEnabled(true);
    }

    Uri uri = getIntent().getData();
    Cursor cursor = managedQuery(uri, null, null, null, null);

    if (cursor == null) {
        finish();
    } else {
        cursor.moveToFirst();

        TextView word = (TextView) findViewById(R.id.word);
        TextView definition = (TextView) findViewById(R.id.definition);

        int wIndex = cursor.getColumnIndexOrThrow(DictionaryDatabase.KEY_WORD);
        int dIndex = cursor.getColumnIndexOrThrow(DictionaryDatabase.KEY_DEFINITION);

        word.setText(cursor.getString(wIndex));
        definition.setText(Html.fromHtml(cursor.getString(dIndex), new ImageGetter(), null));
    }
}

@Override
public boolean onCreateOptionsMenu(Menu menu) {
    MenuInflater inflater = getMenuInflater();
    inflater.inflate(R.menu.main, menu);

    if(Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB){
        SearchManager searchManager = (SearchManager) getSystemService(Context.SEARCH_SERVICE);
        SearchView searchView = (SearchView) menu.findItem(R.id.search).getActionView();
        searchView.setSearchableInfo(searchManager.getSearchableInfo(getComponentName()));     
        searchView.setIconifiedByDefault(false);

    }

    return true;
}

@Override
public boolean onOptionsItemSelected(MenuItem item) {
    switch (item.getItemId()) {
        case R.id.search:
            onSearchRequested();
            return true;
        case android.R.id.home:
            Intent intent = new Intent(this, BancoDictionary.class);
            intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
            startActivity(intent);
            return true;
        default:
            return false;
    }
}


private class ImageGetter implements Html.ImageGetter {

    public Drawable getDrawable(String source) {
            int id;
            if (source.equals("idiom.png")) {
                   id = R.drawable.idiom;
            }

            else {
                return null;
            }

           Drawable d = getResources().getDrawable(id);
           d.setBounds(0,0,d.getIntrinsicWidth(),d.getIntrinsicHeight());
           return d;
         }
    };
    }

checkbox value as boolean can't access the database - android

I made a form which should be filled by a user in my application, some of the variables numeric and some boolean , the data thats coming from the user is going to db that I've created. I made the checkBox's boolean(true/false) , and edittext's numeric (int) . For some reason, it gives me an exception, and a lot of crashes.

Here are some of my code :

public void addArea(View view) {
    Area area = new Area();

    SQLiteDatabase areasDB = openOrCreateDatabase("AREA_DATABASE.sqlite", MODE_PRIVATE, null);
    areasDB.execSQL("CREATE TABLE IF NOT EXISTS areas_table(name TEXT, smoking_area INTEGER" +
            "outside_or_inside INTEGER, num_of_tables INTEGER" +
            "num_of_diners INTEGER)");

    area.setName(areaName.getText().toString());

    name = areaName.getText().toString();

    outside = chkOut.isChecked();
    inside = chkIn.isChecked();
    smokingArea = chkSmoking.isChecked();
    Integer.parseInt(numOFTables = editNumTables.getText().toString());
    Integer.parseInt(numOFDiners = maxDiners.getText().toString());


    if (areaName.getText().toString().isEmpty()||
            editNumTables.getText().toString().isEmpty() ||
            maxDiners.getText().toString().isEmpty()){


        AlertDialog alertDialog = new AlertDialog.Builder(Area_creating_activity.this).create();
        alertDialog.setTitle("Oops,");
        alertDialog.setMessage("You forgot to fill something");
        alertDialog.setButton("OK", new DialogInterface.OnClickListener() {

            @Override
            public void onClick(DialogInterface dialog, int which) {


            }
        });

        alertDialog.show();



    } else {

        areasDB.execSQL("INSERT INTO areas_table VALUES('" + name + "','" + outside + "','" + inside+ "','" + smokingArea + "','"
                                                            + numOFTables + "','" + numOFDiners + "')");

        AlertDialog alertSucsess = new AlertDialog.Builder(Area_creating_activity.this).create();
        alertSucsess.setTitle("Congrats,");
        alertSucsess.setMessage(name + " Has been created");
        alertSucsess.setButton("OK", new DialogInterface.OnClickListener() {

            @Override
            public void onClick(DialogInterface dialog, int which) {

                startActivity(new Intent(getApplicationContext(), Activity_Zone.class));

            }
        });

        alertSucsess.show();

    }

    areasDB.close();
}

one of the errors i get :

java.lang.IllegalStateException: Could not execute method of the activity
        at android.view.View$1.onClick(View.java:3846)
        at android.view.View.performClick(View.java:4478)
        at android.view.View$PerformClick.run(View.java:18698)
        at android.os.Handler.handleCallback(Handler.java:733)
        at android.os.Handler.dispatchMessage(Handler.java:95)
        at android.os.Looper.loop(Looper.java:149)
        at android.app.ActivityThread.main(ActivityThread.java:5257)
        at java.lang.reflect.Method.invokeNative(Native Method)
        at java.lang.reflect.Method.invoke(Method.java:515)
        at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:793)
        at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:609)
        at dalvik.system.NativeStart.main(Native Method)
 Caused by: java.lang.reflect.InvocationTargetException
        at java.lang.reflect.Method.invokeNative(Native Method)
        at java.lang.reflect.Method.invoke(Method.java:515)
        at android.view.View$1.onClick(View.java:3841)
            at android.view.View.performClick(View.java:4478)
            at android.view.View$PerformClick.run(View.java:18698)
            at android.os.Handler.handleCallback(Handler.java:733)
            at android.os.Handler.dispatchMessage(Handler.java:95)
            at android.os.Looper.loop(Looper.java:149)
            at android.app.ActivityThread.main(ActivityThread.java:5257)
            at java.lang.reflect.Method.invokeNative(Native Method)
            at java.lang.reflect.Method.invoke(Method.java:515)
            at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:793)
            at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:609)
            at dalvik.system.NativeStart.main(Native Method)
 Caused by: java.lang.NullPointerException
        at com.example.mika.waiter.Area_creating_activity.addArea(Area_creating_activity.java:58)
            at java.lang.reflect.Method.invokeNative(Native Method)
            at java.lang.reflect.Method.invoke(Method.java:515)
            at android.view.View$1.onClick(View.java:3841)
            at android.view.View.performClick(View.java:4478)
            at android.view.View$PerformClick.run(View.java:18698)
            at android.os.Handler.handleCallback(Handler.java:733)
            at android.os.Handler.dispatchMessage(Handler.java:95)
            at android.os.Looper.loop(Looper.java:149)
            at android.app.ActivityThread.main(ActivityThread.java:5257)
            at java.lang.reflect.Method.invokeNative(Native Method)
            at java.lang.reflect.Method.invoke(Method.java:515)
            at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:793)
            at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:609)
            at dalvik.system.NativeStart.main(Native Method)