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?

Aucun commentaire:

Enregistrer un commentaire