jeudi 30 juillet 2015

Check record in SqLite (ionic)

Does anybody know, that how can I check an inserted record? I would like to create an intro page. When the user visits once, I wanna store it and check it.

$rootScope.insert = function(visited) {
     var query = "INSERT INTO shoplist (visited) VALUES (?)";
     $cordovaSQLite.execute(db, query, [visited]).then(function(res) {
        console.log("INSERT ID -> " + res.insertId);
     }, function (err) {
        console.error(err);
     });
}

$rootScope.insert(1);

Basically I would like to check that visited record is 0 or 1. What should I do?

Parsing a list from android sqlite to remote database using a loop

Sorry for the long post - I wasn't sure how much detail to include. Bare with me please, I am fairly new to both Android and PHP.

Part of the android app I am building requires me to save a list of users in an sqlite database. The user can then enter an activity which shows the list of users currently stored in the sqlite datebase within a listview.

I have then tried to implement a function to sync this list of users to a remote database, using Async Tasks, JSON, and a PHP service, by using a FOR LOOP to cycle through the database tables 'users'.

The problem is that the sync only works for the first item in the list. After this has been passed through to the remote database, the activity crashes. The log reads:

E/JSON Parser﹕ Error parsing data org.json.JSONException: Value data of type java.lang.String cannot be converted to JSONObject

E/AndroidRuntime﹕ FATAL EXCEPTION: AsyncTask #3 Process: example.prguru.com.pi_prototype_30, PID: 5139 java.lang.RuntimeException: An error occured while executing doInBackground() at android.os.AsyncTask$3.done(AsyncTask.java:304) ...

Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'java.lang.String org.json.JSONObject.toString()' on a null object reference at example.prguru.com.pi_prototype_30.ShowAdmins$syncUser.doInBackground(ShowAdmins.java:137) at example.prguru.com.pi_prototype_30.ShowAdmins$syncUser.doInBackground(ShowAdmins.java:87)

Line 137 in the java code is:

 Log.d("Sync Attempt", jobj.toString());

PHP CODE:

require_once 'config.php';

if(!empty($_POST)){
$row = $_POST['table_id'];
$type = $_POST['type'];
$id_num = $_POST['id_number'];
$name = $_POST['name'];
$email  = $_POST['email'];
$course = $_POST['course'];
$password = $_REQUEST['password'];

$ins = mysql_query("INSERT INTO pi_prototype_inventory_30.users (table_id, type, id_number, name, email, course, password) 
VALUES('$row','$type','$id_num','$name', '$email', '$course', '$password')");

if(!$ins)
{
    echo (mysql_error());
}
else
{
    echo ("data inserted");
}
}
else {
echo (mysql_error());
}

SYNC CLASS:

    @Override
    protected String doInBackground(String... args) {
        // TODO Auto-generated method stub
        // Check for success tag
        int success;

        DBHandler dbAdapter = DBHandler.getDBHandlerInstance(getApplicationContext());
        try {
            dbAdapter.createDataBase();
        } catch (IOException e) {
            Log.i("*** select ", e.getMessage());
        }

        dbAdapter.openDataBase();
        String query = "SELECT * FROM users";
        ArrayList<ArrayList<String>> stringList = dbAdapter.selectRecordsFromDBList(query, null);
        dbAdapter.close();

        try {

            List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(7);
            for (int i = 0; i < stringList.size(); i++) {
                ArrayList<String> list = stringList.get(i);
                nameValuePairs.add(new BasicNameValuePair("table_id", list.get(0)));
                nameValuePairs.add(new BasicNameValuePair("type", list.get(1)));
                nameValuePairs.add(new BasicNameValuePair("id_number", list.get(2)));
                nameValuePairs.add(new BasicNameValuePair("name", list.get(3)));
                nameValuePairs.add(new BasicNameValuePair("email", list.get(4)));
                nameValuePairs.add(new BasicNameValuePair("course", list.get(5)));
                nameValuePairs.add(new BasicNameValuePair("password", list.get(6)));

                Log.d("Request!", "Starting!");

                jobj = jsonParser.makeObjHttpRequest(REG_URL, "POST", nameValuePairs);

                Log.d("Sync Attempt", jobj.toString());

            }//forLoop
                success = jobj.getInt(TAG_SUCCESS);
                if (success == 1){
                    Log.d("SYNCED!", jobj.toString());
                    return jobj.getString(TAG_MESSAGE);
                }
                else {
                    Log.d("Sync failure!", jobj.getString(TAG_MESSAGE));
                    return jobj.getString(TAG_MESSAGE);
                }



        } catch (JSONException e){
            e.printStackTrace();
        }
        return null;
    }//doInBackground

Do I need to implement some sort of loop in my PHP code so it accepts more than one entry from the list? I don't know how I would go about coding that because I will never be sure how many entries will need to be synced at any one time. Or is the problem within the java code itself? I'm not quite sure how to make sense of the errors presented in the log.

Mono.Data.Sqlite throws exceptions

I'm using SQLite as database engine in my app, but at the same time the application must be cross-platform, so i have decided to use Mono.Data.Sqlite. And this what i did:

  • Installed the latest version of Mono (4.0.2 SR 2), copied Mono.Data.Sqlite.dll from Mono's directory (net4_5) to my project in Visual Studio 2015

  • Downloaded and copied precompiled sqlite3.dll library.

And then i wrote a simple app:

        const string databaseFileName = "somedata.db";
        var path = Directory.GetCurrentDirectory() + Path.DirectorySeparatorChar + databaseFileName;

        if (!File.Exists(path)) SqliteConnection.CreateFile(databaseFileName);

        var connString = string.Format("Data Source=file:{0}", databaseFileName);

        using (var conn = new SqliteConnection(connString))
        {
            conn.Open();

            /* Some code */
            conn.ChangePassword("testpassword");
            conn.Close();
        }

But i'm facing with some issues:

  • First, when i'm using Data Source=file:{0} in connection string, it throws an exception: "URI formats are not supported". Replacing it to URI=file:{0} helps, but why the first option doesn't work?

  • Second, when i call conn.ChangePassword("testpassword") it throws an exception: System.EntryPointNotFoundException: Unable to find an entry point named "sqlite3_rekey" in DLL "sqlite3"

  • Third, using URI=file:{0};Password=testpassword with the already encrypted database throws an exception: System.EntryPointNotFoundException: Unable to find an entry point named "sqlite3_key" in DLL "sqlite3"

It doesn't actually happen with official wrapper for SQLite, but happens with Mono's.

P.S. Mono's wrapper works normally when i don't use encryption and Data Source=file:{0} instead of URI=file:{0}

SQLite Windows 10 RTM universal app

With the Windows 10 RTM and Visual Studio 2015 RTM SQLite doesn't work any more.

For instance, the tutorial at http://ift.tt/1GH1zrE will not add the SQLLite.cs and SQLiteAsync.cs files to my project, also the "Microsoft Visual C++ Applocal runtime Package for Windows UAP" reference is not available for me.

The funny thing is it worked with the RC versions ...

SQLite Version: sqlite-uap-3081101.vsix (5.73 MiB)

How to get the specific error code from sqlite3_exec?

So, I need to try to lock a sqlite database and update a table. To do this, I started it off with pragma locking_mode=exclusive; begin exclusive;. As expected though, when another program has a lock on the database this fails. It returns the generic SQLITE_ERROR code. However, I'd prefer to have the exact reason, SQLITE_LOCKED. How can I determine what the more specific error from sqlite3_exec() is?

The constructor CursorLoader is undefined

I am trying to retrieve rows of locations from my SQLiteTable but I ran into a compilation error, the constructor CursorLoader is undefined. What can I do to resolve this error?

@Override
public Loader<Cursor> onCreateLoader(int arg0,
    Bundle arg1) {

    // Uri to the content provider LocationsContentProvider
    Uri uri = LocationsContentProvider.CONTENT_URI;

    // Fetches all the rows from locations table

    //return new CursorLoader(null);
   //(Context context, Uri uri, String[] projection, String selection, String[] selectionArgs, String sortOrder)

    /ERROR HERE
    return new CursorLoader(this, null, null null, null);
}

In LocationsContentProvider.java

 /** A callback method which is invoked by default content uri */
@Override
public Cursor query(Uri uri, String[] projection, String selection, String[] selectionArgs, String sortOrder) {

    if(uriMatcher.match(uri)==LOCATIONS){
        return mLocationsDB.getAllLocations();
    }
    return null;
}

App crashes when I try to get the _id in my SQLite Table?

Hi guys so here is my problem, I need to be able to access the unique ID of a row that is created because I created a second table that will "Connected" through the IDs. However here is my issue, whenever I try calling this method, my app crashes.. I was hoping the community could help me out here. Many Thanks.

public void addExerciseToDatabase(Exercises exercises){

    SQLiteDatabase db = myDBHelper.getWritableDatabase();

    ContentValues values = new ContentValues();
    ContentValues nuValues = new ContentValues();

    values.put(myDBHelper.COLUMN_BODYPARTNAME, exercises.get_bodyPart());
    values.put(myDBHelper.COLUMN_EXERCISENAME, exercises.get_exerciseName());

    db.insert(myDBHelper.TABLE_EXERCISES, null, values);

    //FOR THE NEW TABLE VALUES

    int ID = getExerciseID(exercises.get_bodyPart(),exercises.get_exerciseName());

    nuValues.put(myDBHelper.COLUMN_EXERCISENAME_ID, ID);
    nuValues.put(myDBHelper.COLUMN_NUMSETS, exercises.get_numSets());
    nuValues.put(myDBHelper.COLUMN_NUMWEIGHT, exercises.get_numWeight());
    nuValues.put(myDBHelper.COLUMN_NUMREPS, exercises.get_numReps());

    db.insert(myDBHelper.TABLE_EXERCISES_VALUE, null, nuValues);
    db.close();
}

/*~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
THIS method returns the EXERCISE ID, that corresponds to the exercise
passed and Bodypart passed
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~*/
public int getExerciseID(String exercise, String bodyPart) {

    SQLiteDatabase db = myDBHelper.getWritableDatabase();

    String query = "SELECT" + myDBHelper.COLUMN_ID + "FROM " + myDBHelper.TABLE_EXERCISES + " WHERE " +
            myDBHelper.COLUMN_BODYPARTNAME + " = " + bodyPart + " AND " +
            myDBHelper.COLUMN_EXERCISENAME + " = " + exercise ;

    Cursor c = db.rawQuery(query, null);
    c.moveToFirst();
    int exerciseID = Integer.parseInt(c.getString(0));
    /*int exerciseID = c.getInt(c.getColumnIndex(myDBHelper.COLUMN_ID));*/
    c.close();
    db.close();

    return exerciseID;
}