lundi 29 juin 2015

SQLiteDatabase error in android on inserting

I have a problem trying to insert some data into database (SQLiteDatabase) in android. I'm building simple notepad app and I just can't figure out what is wrong. Below is code of my project.

Notes.java

package com.cidecode.xnotes;
public class Notes {
    private long id;
    private String title;
    private String note;
    private String date;

    public Notes(){

    }

    public long getId() {
        return id;
    }

    public void setId(long id) {
        this.id = id;
    }

    public String getTitle() {
        return title;
    }

    public void setTitle(String title) {
        this.title = title;
    }

    public String getNote() {
        return note;
    }

    public void setNote(String note) {
        this.note = note;
    }

    public String getDate() {
        return date;
    }

    public void setDate(String date) {
        this.date = date;
    }

    @Override
    public String toString(){
        return title + ", " + note + ", " + date;
    } 
}

DatabaseHelper.java

package com.cidecode.xnotes;

import android.content.Context;
import android.database.sqlite.SQLiteOpenHelper;
import android.util.Log;

public class DatabaseHelper extends SQLiteOpenHelper {

    public static final String TABLE_NOTES = "notes";
    public static final String COLUMN_ID = "id";
    public static final String COLUMN_TITLE = "title";
    public static final String COLUMN_NOTE = "note";
    public static final String COLUMN_DATE = "date";

    private static final String DATABASE_NAME = "xnotes.db";
    private static final int DATABASE_VERSION = 1;

    // Create the database
    private static final String DATABASE_CREATE = "create table " + TABLE_NOTES + "(" +
            COLUMN_ID + " integer primary key autoincrement, " + COLUMN_TITLE + " text not null, " +
            COLUMN_NOTE + " text not null, " + COLUMN_DATE + " text not null);";

    // Drop table notes
    private static final String DATABASE_DROP_TABLE_NOTES = "drop table if exists " + TABLE_NOTES;

    public DatabaseHelper(Context context){
        super(context, DATABASE_NAME, null, DATABASE_VERSION);
    }

    @Override
    public void onCreate(android.database.sqlite.SQLiteDatabase db) {
        db.execSQL(DATABASE_CREATE);
    }

    @Override
    public void onUpgrade(android.database.sqlite.SQLiteDatabase db, int oldVersion, int newVersion) {
        Log.w(DatabaseHelper.class.getName(), "Upgrading database from v" + oldVersion + " to v" +
                newVersion + " which will delete all old data.");

        db.execSQL(DATABASE_DROP_TABLE_NOTES);
        onCreate(db);
    }
}

NotesDataSource.java

package com.cidecode.xnotes;

import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.widget.EditText;

import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;

public class NotesDataSource {
    private SQLiteDatabase database;
    private DatabaseHelper dbHelper;
    private String[] allColumns = {DatabaseHelper.COLUMN_ID, DatabaseHelper.COLUMN_TITLE, DatabaseHelper.COLUMN_NOTE, DatabaseHelper.COLUMN_DATE};

    public NotesDataSource(Context context){
        dbHelper = new DatabaseHelper(context);
    }

    public void open() throws SQLException{
        database = dbHelper.getWritableDatabase();
    }

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

    public Notes createNote(String title, String note, String date){
        ContentValues values = new ContentValues();
        values.put(DatabaseHelper.COLUMN_TITLE, title);
        values.put(DatabaseHelper.COLUMN_NOTE, note);
        values.put(DatabaseHelper.COLUMN_DATE, date);
        long insertId = database.insert(DatabaseHelper.TABLE_NOTES, null, values);

        Cursor cursor = database.query(DatabaseHelper.TABLE_NOTES, allColumns,
                DatabaseHelper.COLUMN_ID + " = " + insertId, null, null, null, null);
        cursor.moveToFirst();
        Notes newNotes = cursorToNote(cursor);
        cursor.close();
        return newNotes;
    }

    public List<Notes> getAllNotes(){
        List<Notes> notesList = new ArrayList<Notes>();

        Cursor cursor = database.query(DatabaseHelper.TABLE_NOTES, allColumns,
                null, null, null, null, null);

        cursor.moveToFirst();
        while (!cursor.isAfterLast()){
            Notes note = cursorToNote(cursor);
            notesList.add(note);
            cursor.moveToNext();
        }
        cursor.close();
        return notesList;
    }

    private Notes cursorToNote(Cursor cursor){
        Notes note = new Notes();
        note.setId(cursor.getLong(0));
        note.setTitle(cursor.getString(1));
        note.setNote(cursor.getString(2));
        note.setDate(cursor.getString(3));
        return note;
    }
}

AddNote.java

package com.cidecode.xnotes;

import android.database.sqlite.SQLiteDatabase;
import android.support.v7.app.ActionBarActivity;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.Window;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;

import java.sql.SQLException;


public class AddNote extends ActionBarActivity {

    private EditText title,note;
    private String s_title, s_note, s_date;
    Button b_save;
    private SQLiteDatabase database;
    private DatabaseHelper dbHelper;
    private NotesDataSource datasource;

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

        dbHelper = new DatabaseHelper(this);
        datasource = new NotesDataSource(this);
        try {
            datasource.open();
        } catch (SQLException e) {
            e.printStackTrace();
        }

        title = (EditText)findViewById(R.id.id_title);
        note = (EditText)findViewById(R.id.id_write_note_here);

        s_title = title.getText().toString();
        s_note = note.getText().toString();
        s_date = "11.11.1111";

        b_save = (Button)findViewById(R.id.id_save);
        b_save.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                datasource.createNote(s_title, s_note, s_date);
                Toast.makeText(getApplicationContext(), "Note is saved.", Toast.LENGTH_LONG).show();

            }
        });

    }

    @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_add_note, 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);
    }
}

activity_add_note.xml

<LinearLayout xmlns:android="http://ift.tt/nIICcg"
    xmlns:tools="http://ift.tt/LrGmb4"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical"
    tools:context=".MainActivity"
    android:background="#EBD28F">

    <TextView
        android:id="@+id/id_add_new_note"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="@string/s_add_new_note"
        android:gravity="center"
        android:textSize="30sp"
        android:layout_marginBottom="10dp"/>

    <EditText
        android:id="@+id/id_title"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:hint="@string/s_title"
        android:layout_marginLeft="5dp"
        android:layout_marginRight="5dp"
        android:layout_marginBottom="5dp"/>

    <EditText
        android:id="@+id/id_write_note_here"
        android:layout_width="match_parent"
        android:layout_height="fill_parent"
        android:layout_weight="1"
        android:layout_marginLeft="5dp"
        android:layout_marginRight="5dp"
        android:hint="@string/s_write_note_here"
        android:gravity="top" />

    <Button
        android:id="@+id/id_save"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_gravity="center_horizontal"
        android:layout_marginTop="5dp"
        android:layout_marginBottom="5dp"
        android:text="@string/s_save"
        android:textColor="#FFFFFF"
        android:background="#5E553A"/>

</LinearLayout>

Logcat

06-30 08:49:12.435  20736-20736/? E/SQLiteLog﹕ (1) table notes has no column named date
06-30 08:49:12.455  20736-20736/? E/SQLiteDatabase﹕ Error inserting title= date=11.11.1111 note=
    android.database.sqlite.SQLiteException: table notes has no column named date (code 1): , while compiling: INSERT INTO notes(title,date,note) VALUES (?,?,?)
            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.<init>(SQLiteProgram.java:58)
            at android.database.sqlite.SQLiteStatement.<init>(SQLiteStatement.java:31)
            at android.database.sqlite.SQLiteDatabase.insertWithOnConflict(SQLiteDatabase.java:1467)
            at android.database.sqlite.SQLiteDatabase.insert(SQLiteDatabase.java:1339)
            at com.cidecode.xnotes.NotesDataSource.createNote(NotesDataSource.java:38)
            at com.cidecode.xnotes.AddNote$1.onClick(AddNote.java:50)
            at android.view.View.performClick(View.java:4232)
            at android.view.View$PerformClick.run(View.java:17298)
            at android.os.Handler.handleCallback(Handler.java:615)
            at android.os.Handler.dispatchMessage(Handler.java:92)
            at android.os.Looper.loop(Looper.java:137)
            at android.app.ActivityThread.main(ActivityThread.java:4921)
            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:1027)
            at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:794)
            at dalvik.system.NativeStart.main(Native Method)
06-30 08:49:12.455  20736-20736/? E/SQLiteLog﹕ (1) no such column: date
06-30 08:49:12.485  20736-20736/? E/AndroidRuntime﹕ FATAL EXCEPTION: main
    android.database.sqlite.SQLiteException: no such column: date (code 1): , while compiling: SELECT id, title, note, date FROM notes WHERE id = -1
            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.<init>(SQLiteProgram.java:58)
            at android.database.sqlite.SQLiteQuery.<init>(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 com.cidecode.xnotes.NotesDataSource.createNote(NotesDataSource.java:40)
            at com.cidecode.xnotes.AddNote$1.onClick(AddNote.java:50)
            at android.view.View.performClick(View.java:4232)
            at android.view.View$PerformClick.run(View.java:17298)
            at android.os.Handler.handleCallback(Handler.java:615)
            at android.os.Handler.dispatchMessage(Handler.java:92)
            at android.os.Looper.loop(Looper.java:137)
            at android.app.ActivityThread.main(ActivityThread.java:4921)
            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:1027)
            at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:794)
            at dalvik.system.NativeStart.main(Native Method)

It tells me that something is wrong with creating database or table. Can someone help me, please?

SQL Query in Android application adds unwanted extra Fileds

I have developed an application using android studio. In my code I have written an SQL Query in the developed android application. The SQL query seems to be correct but for Some reason, It adds an extra Filed to the Column name like below. As you can see asset_description table has the word "Text". As this should not be the case.

I do not know why this is happening

enter image description here

The Column names are as shown below

 //Columns in the Asset Table
    public static final String ASSET_ID = "Assetid";
    public static final String ASSET_Name="asset_name";
    public static final String ASSET_Category ="category";
    public static final String ASSET_PurchaseDate = "Purchase_date";
    public static final String Asset_Cost ="Asset_cost";
    public static final String ASSET_STATUS ="asset_status";
    public static final String ASSET_DESCRIPTION ="assets_description";
    public static final String ASSET_Warrenty ="warrenty";

This is the table creation section

private static final String CREATE_TABLE_ASSET ="CREATE TABLE" + TABLE_ASSET + "("
            + ASSET_ID + " INTEGER NOT NULL PRIMARY KEY AUTOINCREMENT,"
            + ASSET_Name + " TEXT NOT NULL,"
            + ASSET_Category +" TEXT NOT NULL,"
            + CUSTODIAN_ID + " TEXT NOT NULL,"
            + Asset_Cost + " DOUBLE NOT NULL,"
            + ASSET_PurchaseDate + " DATE NULL,"
            + ASSET_STATUS +" TEXT NOT NULL,"
            +  ASSET_DESCRIPTION + "Text NOT NULL,"
            + ASSET_Warrenty +" DATE NOT NULL"+ ");";

Select with pattern from table in sqlite

Hi i have table with column contain this values

patern_number
0936
09154
123456

and i have number which can be anything
what i want is a select which return 1 when input number start with one of pattern else return 0
example
input number -------result
093628987 ----- ----- 1
0915 --------------------0
0222---------------------0
091546666-------------1
so can anyone help me?

Hi guys!. I have that error cursor index out of bounds exception [duplicate]

This question already has an answer here:

My cursor uses here! I have tried many times :D. I am beginner

 public NotePad getNote(int id){
       SQLiteDatabase db = this.getReadableDatabase();
       Cursor cursor = db.query(TABLE_NAME,new String[]{TITLE,TEXT,DATE,STATE},
               NOTE_ID +"=?", new String[]{String.valueOf(id)},null,null,null,null);
       if(cursor!=null)
           cursor.moveToFirst();
       NotePad notePad = new NotePad(cursor.getString(1), cursor.getString(2),
               cursor.getString(3), Integer.parseInt(cursor.getString(4)));
       cursor.close();
       db.close();
       return notePad;
    }

error in line

NotePad notePad = new NotePad(cursor.getString(1), cursor.getString(2),
               cursor.getString(3), Integer.parseInt(cursor.getString(4))); 

Set default search engine Chrome using meta table Not Working

There may be many variations to this question..but I am still unable to figure out how Chrome backend files work.

I am trying to set default search engine for Chrome, Firefox and IE using VC++ executable. I have been able to do so for Firefox and IE, but stuck in Chrome. I integrated SQLite with vc++ project and accessed Chrome's "Web Data" file to add my search engine to defaults list.

Now based on the link : Setting the Default Search Provider on Chrome via a script, I was able to add a search engine to defaults list of Chrome by adding entry to Web Data - keywords table.

Now to set it default, I added entry for key (if not present) : "Default Search Provider ID" to Web Data database and meta table.

        string query = "INSERT INTO meta (key, value) values ('Default Search Provider ID', " + std::to_string(engineId)+ ");";
        const char *sqlInsert = query.c_str();

        rc = sqlite3_exec(db, sqlInsert, NULL, NULL, &error);
        if (rc)
        {
            cerr << "Error executing SQLite3 statement: " << sqlite3_errmsg(db) << endl << endl;
            sqlite3_free(error);
            sqlite3_close(db);
        }

But this is not reflecting on Chrome. Also change in preferences file sets back the default search engine on reload of Chrome.

SQLite Android No such Column Error

I'm trying to use SQLite in android but for some reason I'm getting the no such column error. I think the error may be syntax but I can't seem to locate it.

This is my code:

         @Override
    public void onCreate(SQLiteDatabase database)
    {
        database.execSQL("create table " +
                TABLE_NAME +
                " (" +
                TABLE_ROW_ID + " integer primary key autoincrement not null," +
                TABLE_ROW_ONE + " text," +
                TABLE_ROW_TWO + " text," +
                TABLE_ROW_THREE +  " text," +
                TABLE_ROW_FOUR + " text" +
                ");");
    }

I had tried some formatting tricks like adding a space to the fourth text, or subtracting one but none of them seemed to have worked yet.

Beneath is the logcat reading.

 android.database.sqlite.SQLiteException: table database_table has no column named table_row_three (code 1): , while compiling: INSERT INTO database_table(table_row_three,table_row_two,table_row_four,table_row_one) VALUES (?,?,?,?)
        at android.database.sqlite.SQLiteConnection.nativePrepareStatement(Native Method)
        at android.database.sqlite.SQLiteConnection.acquirePreparedStatement(SQLiteConnection.java:892)
        at android.database.sqlite.SQLiteConnection.prepare(SQLiteConnection.java:503)
        at android.database.sqlite.SQLiteSession.prepare(SQLiteSession.java:726)
        at android.database.sqlite.SQLiteProgram.<init>(SQLiteProgram.java:58)
        at android.database.sqlite.SQLiteStatement.<init>(SQLiteStatement.java:31)
        at android.database.sqlite.SQLiteDatabase.insertWithOnConflict(SQLiteDatabase.java:1568)
        at android.database.sqlite.SQLiteDatabase.insert(SQLiteDatabase.java:1440)

Thank you!

Fixing async error in Node + Sqllite3

I have the following code :

// reference the http module so we can create a webserver
var http = require("http");
var sqlite3 = require('sqlite3').verbose();
var db = new sqlite3.Database('movies.db');

// create a server
http.createServer(function(req, res) 
{
    var catloc = req.url.indexOf("category");
    if (catloc > 0)
    {
        // part 1
        var page = csm1;
        var url_parts = url.parse(req.url, true);
        var query = url_parts.query;
        var category = query.type;

        // part 2
        db.each("SELECT * FROM MOVIES WHERE LOWER(CATEGORY1)='"+category+"'", function(err, row)
        {
            if (err) throw err;
            page += row.html;
        });

        // part 3
        page += csm3;
        res.writeHead(200, {'Content-Type': 'text/html'});
        res.end(page);
    }
}).listen(process.env.PORT, process.env.IP);

part1 should be executed, followed by part2, then part3. But part1+part3 is executed before part2 due to async.
I would like help on how I could set up a callback to fix this.

Any help is appreciated!