-3

Logcat

Error inserting USERNAME=raj PASSWORD=raj android.database.sqlite.SQLiteException: table User has no column named USERNAME (code 1): , while compiling: INSERT INTO User(USERNAME,PASSWORD) VALUES (?,?)

Code

package com.example.aaru.sqlapplication;

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

public class DBHelper extends SQLiteOpenHelper {
    public static final String DBNAME = "mydatabase.db";
    public static final String TABLE = "User";
    public static final String UNAME = "USERNAME";
    public static final String PASS = "PASSWORD";
    public static final String ID = "UID";

    SQLiteDatabase db=this.getWritableDatabase();

    public DBHelper(Context context) {
        super(context, DBNAME, null, 1);
        //create database when we create DBHelper object
    }

    @Override
    public void onCreate(SQLiteDatabase sqLiteDatabase) {
        //create table
        db.execSQL("create table "+TABLE+"(" + ID + " integer primary key autoincrement," + UNAME + " text," + PASS + " text)");
    }

    @Override
    public void onUpgrade(SQLiteDatabase sqLiteDatabase, int i, int i1) {
        //Delete table if table is already exists
        db.execSQL("DROP TABLE IF EXISTS User");
        onCreate(sqLiteDatabase);
    }

    public long insert(String uname, String pass){
        ContentValues values = new ContentValues();
        values.put(UNAME, uname);
        values.put(PASS, pass);
        return db.insert(TABLE, null, values);
    }
}
grine4ka
  • 2,878
  • 1
  • 19
  • 29
Raj Padvi
  • 21
  • 2

1 Answers1

3

You have multiple problems with your code.

First, your onCreate() nor onUpgrade() are not getting executed. The database file is already at version 1. You can uninstall your application to remove its old database file. When is SQLiteOpenHelper onCreate() / onUpgrade() run?

That would then trigger a NullPointerException since db is not initialized. onCreate() and onUpgrade() need to use the SQLiteDatabase passed in as parameter to the method, not a field that has not yet been initialized.

laalto
  • 150,114
  • 66
  • 286
  • 303