I want to open my database with SQLite. But when attempting to take data from a TextInputEditText and put it into the database it throws NPE at db = this.getWritableDatabase();
Seems that most of the time this is caused by the context being null. But it is not null and I checked it with debugger. (myDB = new DatabaseHelper(this);)
(I have tried all other questions about this problem and my situation must be different because they did not help.)
MainActivity.java
public class MainActivity extends AppCompatActivity {
DatabaseHelper myDB;
TextInputEditText inputEmail;
TextInputEditText inputPass;
Button btn_login;
Button btn_signup;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
try {
myDB = new DatabaseHelper(this);
} catch (Exception e) {
System.out.print("Exception occurred");
}
btn_signup = findViewById(R.id.btn_signup);
btn_login = findViewById(R.id.btn_login);
addData();
}
public void addData() {
btn_signup.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
inputEmail = findViewById(R.id.editTextEmail);
inputPass = findViewById(R.id.editTextPass);
//try {
myDB.insertData(inputEmail.getText().toString(),
inputPass.getText().toString());
Toast.makeText(MainActivity.this, "Data Inserted",
Toast.LENGTH_LONG).show();
// } catch (Exception e) {
// e.printStackTrace();
// }
}
});
}
DatabaseHelper.java
public class DatabaseHelper extends SQLiteOpenHelper {
public static final String DATABASE_NAME = "Login_android.db";
public static final String TABLE_NAME = "login_table.db";
public static final String COL1 = "ID";
public static final String COL2 = "EMAIL";
public static final String COL3 = "PASSWORD";
public DatabaseHelper(Context context) {
super(context, DATABASE_NAME, null, 1);
//SQLiteDatabase db = this.getWritableDatabase();
}
#Override
public void onCreate(SQLiteDatabase db) {
db.execSQL("CREATE TABLE " + TABLE_NAME +" (ID INTEGER PRIMARY KEY
AUTOINCREMENT, EMAIL TEXT, PASSWORD TEXT)");
}
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
db.execSQL("DROP TABLE IF EXISTS " + TABLE_NAME);
onCreate(db);
}
public boolean insertData(String email, String password) {
SQLiteDatabase db = null;
try {
db = this.getWritableDatabase();
} catch (Exception e) {
e.printStackTrace();
}
//db.isOpen();
ContentValues contentValues = new ContentValues();
contentValues.put(COL2, email);
contentValues.put(COL3, password);
long result = db.insert(TABLE_NAME, null, contentValues);
if (result == -1) {
return false;
} else {
return true;
}
}
}
Exception
12-06 23:39:12.799 26304-26304/com.example.ryan.temporaryname E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.example.ryan.temporaryname, PID: 26304
java.lang.NullPointerException: Attempt to invoke virtual method 'long android.database.sqlite.SQLiteDatabase.insert(java.lang.String, java.lang.String, android.content.ContentValues)' on a null object reference
at com.example.ryan.temporaryname.DatabaseHelper.insertData(DatabaseHelper.java:45)
at com.example.ryan.temporaryname.MainActivity$1.onClick(MainActivity.java:64)
at android.view.View.performClick(View.java:6294)
at android.view.View$PerformClick.run(View.java:24770)
at android.os.Handler.handleCallback(Handler.java:790)
at android.os.Handler.dispatchMessage(Handler.java:99)
at android.os.Looper.loop(Looper.java:164)
at android.app.ActivityThread.main(ActivityThread.java:6494)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:438)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:807)
I think the problem is about TABLE_NAME - "login_table.db" suggests a table named "db" in a database named "login_table", which does not exist, and a null database object is returned.
Please try to change the name.
i think you should ( if this is not a test sqlite app) create a singleton by create a App() class and initialize the database in there.Try to firgure out your problem too
Related
I have got stuck in the above-mentioned error message in Android Studio. My Database is a simple one
1st column: Name TEXT PRIMARY KEY
2nd column: Price TEXT
I have already gone through the answers to the same question in StackOverflow but couldn't resolve the error.
I am quoting my DataBaseHelper class and insertActivity here:
private static final String DATABASE_NAME = "ItemDatabase";
private static final int DATABASE_VERSION = 1;
private static final String TABLE_NAME = "Items";
private static final String COLUMN_NAME = "Name";
private static final String COLUMN_PRICE = "Price";
DataBaseHelper(Context context)
{
super(context, DATABASE_NAME, null, DATABASE_VERSION);
}
#Override
public void onCreate(SQLiteDatabase sqLiteDatabase) {
sqLiteDatabase.execSQL("CREATE TABLE IF NOT EXISTS "+ TABLE_NAME + "(" + COLUMN_NAME + " TEXT NOT NULL PRIMARY KEY, " + COLUMN_PRICE + " TEXT);");
}
#Override
public void onUpgrade(SQLiteDatabase sqLiteDatabase, int i, int i1) {
String sql = "DROP TABLE IF EXISTS " + TABLE_NAME + ";";
sqLiteDatabase.execSQL(sql);
onCreate(sqLiteDatabase);
}
boolean addItem(String itemName, String itemPrice) {
ContentValues contentValues = new ContentValues();
contentValues.put(COLUMN_NAME, itemName);
contentValues.put(COLUMN_PRICE, itemPrice);
SQLiteDatabase db = this.getWritableDatabase();
boolean b = db.insert(TABLE_NAME, null, contentValues) != -1;
db.close();
return b;
}
Cursor getPrice(String itemName) {
SQLiteDatabase db = this.getReadableDatabase();
return db.rawQuery(" SELECT Price FROM Items WHERE Name= ? ", new String[]{itemName});
}
Cursor updatePrice(String itemName, String itemPrice)
{
SQLiteDatabase db = this.getReadableDatabase();
return db.rawQuery(" UPDATE Items SET Price= ? WHERE Name= ? ", new String[]{itemPrice,itemName});
}
public List<String> getName(){
List<String> list = new ArrayList<String>();
String selectQuery = "SELECT * FROM " + TABLE_NAME;
SQLiteDatabase db = this.getReadableDatabase();
Cursor cursor = db.rawQuery(selectQuery, null);
if (cursor.moveToFirst()) {
do {
list.add(cursor.getString(0));
} while (cursor.moveToNext());
}
cursor.close();
db.close();
return list;
}
}
public class insertActivity extends AppCompatActivity {
EditText itemName,itemPrice;
Button buttonInsert;
boolean b;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_insert);
itemName= findViewById(R.id.itemName);
itemPrice= findViewById(R.id.itemPrice);
buttonInsert=findViewById(R.id.buttonInsert);
final String Name=itemName.getText().toString();
final String Price=itemPrice.getText().toString();
final DataBaseHelper dataBaseHelper =new DataBaseHelper(getApplicationContext());
buttonInsert.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
try {
b = dataBaseHelper.addItem(Name,Price);
}catch (Exception e)
{
e.printStackTrace();
}
if( b )
{
Toast.makeText(getApplicationContext(),"Item Inserted Successfully ",Toast.LENGTH_SHORT).show();
}
else
Toast.makeText(getApplicationContext(),"Item Insertion Failed ",Toast.LENGTH_SHORT).show();
}
});
}
}
error:
W/System.err: at android.database.sqlite.SQLiteConnection.nativeExecuteForChangedRowCount(Native Method)
at android.database.sqlite.SQLiteConnection.executeForChangedRowCount(SQLiteConnection.java:746)
W/System.err: at android.database.sqlite.SQLiteSession.executeForChangedRowCount(SQLiteSession.java:754)
at android.database.sqlite.SQLiteStatement.executeUpdateDelete(SQLiteStatement.java:64)
at android.database.sqlite.SQLiteDatabase.executeSql(SQLiteDatabase.java:1770)
at android.database.sqlite.SQLiteDatabase.execSQL(SQLiteDatabase.java:1698)
at com.anirbit.anirbitadak.nirman.DataBaseHelper.addItem(DataBaseHelper.java:45)
W/System.err: at com.anirbit.anirbitadak.nirman.insertActivity$1.onClick(insertActivity.java:39)
at android.view.View.performClick(View.java:6597)
at android.view.View.performClickInternal(View.java:6574)
at android.view.View.access$3100(View.java:778)
at android.view.View$PerformClick.run(View.java:25881)
W/System.err: at android.os.Handler.handleCallback(Handler.java:873)
at android.os.Handler.dispatchMessage(Handler.java:99)
W/System.err: at android.os.Looper.loop(Looper.java:164)
at android.app.ActivityThread.main(ActivityThread.java:6649)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:493)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:826)```
These lines:
final String Name=itemName.getText().toString();
final String Price=itemPrice.getText().toString();
assign to the variables Name and Price the text of the EditTexts itemName and itemPrice when the insertActivity loads (maybe they are just empty strings) and they are never changed.
So when you click the button the listener by calling dataBaseHelper.addItem(Name,Price) tries to insert the same values in the table and this results to the error you get because since the column Name is the Primary Key of the table it must be unique.
What you must do is move these lines inside the listener:
buttonInsert.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
final String Name=itemName.getText().toString();
final String Price=itemPrice.getText().toString();
try {
................................................
}
so when you click the button the correct values are retrieved from the EditTexts and then inserted in the table.
I would like to ask anyone to please help me to modify my database connection code. What I have now is it's a part of one of my method class and it will make a connection every time I call it ( which I know its very inefficient). But when I try to move the connection part out from the method it breaks the code. I just wonder if I could make a static class somewhere so I can reuse it in other method as well.
Thanks so much for any help in advance, it is really appreciated.
Here is the method code:
public void getListDetail(){
//listDetailData.clear();
ShoppingListDatabase databaseConnection = new ShoppingListDatabase(this);
final SQLiteDatabase db = databaseConnection.open();
final ArrayList<ShoppingItem> lists = ShoppingListItemTable.selectAllItems(db, selectedID);
databaseConnection.close();
//create a list adapter and set adapter
ShoppingListItemAdapter adapter = new ShoppingListItemAdapter(this, R.layout.activity_item_detail_list, lists);
ListView_ListDetail = findViewById(R.id.ListView_ListDetail);
ListView_ListDetail.setAdapter(adapter);
adapter.notifyDataSetChanged();
// ((ArrayAdapter<String>)ListView_ListDetail.getAdapter()).notifyDataSetChanged();
}
Database class:
package com.puyakul.prin.psychic_shopping;
import android.content.Context;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
import android.provider.ContactsContract;
import android.util.Log;
public class ShoppingListDatabase {
private static final String TAG = "ShoppingListDatabase";
private static final String DATABASE_NAME = "ShoppingListDatabase";
private static final int DATABASE_VERSION = 3;
private SQLiteDatabase mDb;
private DatabaseHelper mDbHealper;
private final Context mCtx;
public ShoppingListDatabase(Context ctx){
this.mCtx = ctx;
}
/**
* DatabaseHelper class.
*
* Database helper class to manage connections with the database.
*/
private static class DatabaseHelper extends SQLiteOpenHelper
{
DatabaseHelper(Context context){
super(context, DATABASE_NAME, null, DATABASE_VERSION);
}
#Override
public void onCreate(SQLiteDatabase db) {
Log.d(TAG, "DatabaseHelper onCreate");
db.execSQL(ShoppingListItemTable.CREATE_STATEMENT);
db.execSQL(ShoppingListTable.CREATE_STATEMENT);
}
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
Log.d(TAG, "DatabaseHelper onUpgrade");
db.execSQL("DROP TABLE IF EXISTS " + ShoppingListItemTable.TABLE_NAME);
db.execSQL("DROP TABLE IF EXISTS " + ShoppingListTable.TABLE_NAME);
onCreate(db); //this will recreate the database as if it were new
}
}
public SQLiteDatabase open(){
mDbHealper = new DatabaseHelper(mCtx);
mDb = mDbHealper.getReadableDatabase();
return mDb;
}
public void close(){
mDb = null;
}
}
I have tried to declare variables within onCreate so I can use with other methods in the class like this
//================DATABASE CONNECTION=====================//
private ShoppingListDatabase databaseConnection;
private SQLiteDatabase db = databaseConnection.open();
private String selectedList;
private int selectedID;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
this.getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_ALWAYS_HIDDEN);
setContentView(R.layout.activity_main_lists_detail);
ShoppingListDatabase databaseConnection = new ShoppingListDatabase(this);
SQLiteDatabase db = databaseConnection.open();
lists = ShoppingListItemTable.selectAllItems(db, selectedID);
and this is the error
Process: com.puyakul.prin.psychic_shopping, PID: 5635
java.lang.RuntimeException: Unable to instantiate activity ComponentInfo{com.puyakul.prin.psychic_shopping/com.puyakul.prin.psychic_shopping.MainListsDetail}: java.lang.NullPointerException: Attempt to invoke virtual method 'android.database.sqlite.SQLiteDatabase com.puyakul.prin.psychic_shopping.ShoppingListDatabase.open()' on a null object reference
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2548)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2707)
at android.app.ActivityThread.-wrap12(ActivityThread.java)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1460)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:154)
at android.app.ActivityThread.main(ActivityThread.java:6077)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:866)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:756)
Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'android.database.sqlite.SQLiteDatabase com.puyakul.prin.psychic_shopping.ShoppingListDatabase.open()' on a null object reference
at com.puyakul.prin.psychic_shopping.MainListsDetail.<init>(MainListsDetail.java:46)
at java.lang.Class.newInstance(Native Method)
at android.app.Instrumentation.newActivity(Instrumentation.java:1078)
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2538)
Opening and closing the connection can be inefficient/costly so perhaps introduce/use the following :-
public SQLiteDatabase open(){
if (mDb == null) {
mDbHealper = new DatabaseHelper(mCtx);
mDb = mDbHealper.getReadableDatabase();
}
return mDb;
}
or alternately :-
public synchronized SQLiteDatabase open(){
if (mDb == null) {
mDbHealper = new DatabaseHelper(mCtx);
mDb = mDbHealper.getReadableDatabase();
}
return mDb;
}
and never call the close, except when the main activity is being destroyed. Then you will retrieve the one connection.
Here's some example uses based upon your ShoppingListDatabase class.
First a modified class with a few extra methods inside (addShoppingList, getAllShoppingListsAsCursor and logDBTables) and just a very simple shoppinglist table :-
public class ShoppingListDatabase {
private static final String TAG = "ShoppingListDatabase";
private static final String DATABASE_NAME = "ShoppingListDatabase";
private static final int DATABASE_VERSION = 3;
private static final String TBNAME = "shoppinglist";
public static final String COL_SHOPPINGLIST_NAME = "shoppinglist_name";
private SQLiteDatabase mDb;
private DatabaseHelper mDbHealper;
private final Context mCtx;
public ShoppingListDatabase(Context ctx){
this.mCtx = ctx;
}
/**
* DatabaseHelper class.
*
* Database helper class to manage connections with the database.
*/
private static class DatabaseHelper extends SQLiteOpenHelper
{
DatabaseHelper(Context context){
super(context, DATABASE_NAME, null, DATABASE_VERSION);
}
#Override
public void onCreate(SQLiteDatabase db) {
Log.d(TAG, "DatabaseHelper onCreate");
//db.execSQL(ShoppingListItemTable.CREATE_STATEMENT);
//db.execSQL(ShoppingListTable.CREATE_STATEMENT);
String crtsql = "CREATE TABLE If NOT EXISTS " + TBNAME + "(" +
COL_SHOPPINGLIST_NAME + " TEXT " +
")";
db.execSQL(crtsql);
}
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
Log.d(TAG, "DatabaseHelper onUpgrade");
//db.execSQL("DROP TABLE IF EXISTS " + ShoppingListItemTable.TABLE_NAME);
//db.execSQL("DROP TABLE IF EXISTS " + ShoppingListTable.TABLE_NAME);
onCreate(db); //this will recreate the database as if it were new
}
}
public synchronized SQLiteDatabase open(){
if (mDb == null) {
mDbHealper = new DatabaseHelper(mCtx);
mDb = mDbHealper.getReadableDatabase();
}
return mDb;
}
public void close(){
mDb = null;
}
public long addShoppingList(String name) {
ContentValues cv = new ContentValues();
cv.put(COL_SHOPPINGLIST_NAME,name);
return mDb.insert(TBNAME,null,cv);
}
public Cursor getAllShoppingListAsCursor() {
return mDb.query(TBNAME,
null,
null,
null,
null,null,
null
);
}
public void logDBTables() {
Cursor csr = mDb.query("sqlite_master",null,null,null,null,null,null);
while (csr.moveToNext()) {
Log.d(TAG,"Item " +
csr.getString(csr.getColumnIndex("name")) +
" was created using " +
csr.getString(csr.getColumnIndex("sql"))
);
}
}
}
Here's code from an Activity (that uses the Database connection in various ways) :-
public class MainActivity extends AppCompatActivity {
ShoppingListDatabase mSL;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mSL = new ShoppingListDatabase(this);
mSL.open();
SO50312618();
SO50312618_other();
Cursor csr = mSL.getAllShoppingListAsCursor();
while(csr.moveToNext()) {
Log.d("SL INFO","Shopping List " + String.valueOf(csr.getPosition() + 1) +
" is " +
csr.getString(csr.getColumnIndex(ShoppingListDatabase.COL_SHOPPINGLIST_NAME))
);
}
}
private void SO50312618() {
ShoppingListDatabase databaseConnection = new ShoppingListDatabase(this);
SQLiteDatabase db = databaseConnection.open();
databaseConnection.logDBTables();
}
private void SO50312618_other() {
mSL.addShoppingList("List001");
mSL.addShoppingList("List002");
}
}
The results being :-
05-13 05:36:24.290 4245-4245/soanswers.soanswers D/ShoppingListDatabase: Item android_metadata was created using CREATE TABLE android_metadata (locale TEXT)
Item shoppinglist was created using CREATE TABLE shoppinglist(shoppinglist_name TEXT )
05-13 05:36:24.302 4245-4245/soanswers.soanswers D/SLĀ INFO: Shopping List 1 is List001
Shopping List 2 is List002
All the various uses will use the same single connection.
i'm trying to make simple signup/login app which uses SQLite database, so far i got this code. This is my "registration" activity which should implement users name and pin(password) to database after pushing register button i guess, sadly the app crashes.
EditText reName, rePin;
Button reRegister;
DatabaseHelper helper = new DatabaseHelper(this);
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_sign_up);
reName = (EditText)findViewById(R.id.reName);
rePin = (EditText)findViewById(R.id.rePin);
reRegister = (Button)findViewById(R.id.reRegister);
reRegister.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
String Imie = reName.getText().toString();
String Haslo = rePin.getText().toString();
Contacts c =new Contacts();
c.setName(Imie);
c.setPass(Haslo);
helper.insertContacts(c);
Intent intent = new Intent(SignUp.this, MainActivity.class);
startActivity(intent);
}
});
}
Here's also my DatabaseHelper code, i guess that the problem is somewhere in this code, but i cant really find it. What should i do or where should i find solution for this? :)
public class DatabaseHelper extends SQLiteOpenHelper {
private static final int DATABASE_VERSION = 1;
private static final String DATABASE_NAME = "contacts.db";
private static final String TABLE_NAME = "contacts";
private static final String COLUMN_ID = "id";
private static final String COLUMN_NAME = "name";
private static final String COLUMN_PASS = "pass";
SQLiteDatabase db;
private static final String TABLE_CREATE = "create table contacts (id integer primary key not null , " +
"name text not null, pass text not null);";
public DatabaseHelper(Context context){
super(context, DATABASE_NAME, null, 1);
}
public DatabaseHelper(Context context, String name, SQLiteDatabase.CursorFactory factory, int version) {
super(context, name, factory, version);
}
#Override
public void onCreate(SQLiteDatabase sqLiteDatabase) {
db.execSQL(TABLE_CREATE);
this.db = db;
}
public void insertContacts(Contacts c){
db = this.getWritableDatabase();
ContentValues values = new ContentValues();
String query = "select + from contacts";
Cursor cursor = db.rawQuery(query, null);
int count = cursor.getCount();
values.put(COLUMN_ID, count);
values.put(COLUMN_NAME, c.getName());
values.put(COLUMN_PASS, c.getPass());
db.insert(TABLE_NAME, null, values);
db.close();
}
public String searchPass(String name) {
db = this.getReadableDatabase();
String query = "select * from "+TABLE_NAME;
Cursor cursor = db.rawQuery(query, null);
String a,b;
b = "not found";
if (cursor.moveToFirst()){
do {
a =cursor.getString(2);
if (a.equals(name)){
b= cursor.getString(3);
break;
}
}
while (cursor.moveToNext());
}
return b;
}
#Override
public void onUpgrade(SQLiteDatabase sqLiteDatabase, int i, int i1) {
String query = "DROP TABLE IF EXISTS" + TABLE_NAME;
db.execSQL(query);
this.onCreate(db);
}
}
#edit - Logcat errors
12-16 13:08:14.316 3541-3541/com.example.mateusz.sqllogowanie E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.example.mateusz.sqllogowanie, PID: 3541
java.lang.NullPointerException: Attempt to invoke virtual method 'void android.database.sqlite.SQLiteDatabase.execSQL(java.lang.String)' on a null object reference
at com.example.mateusz.sqllogowanie.DatabaseHelper.onCreate(DatabaseHelper.java:36)
at android.database.sqlite.SQLiteOpenHelper.getDatabaseLocked(SQLiteOpenHelper.java:333)
at android.database.sqlite.SQLiteOpenHelper.getWritableDatabase(SQLiteOpenHelper.java:238)
at com.example.mateusz.sqllogowanie.DatabaseHelper.insertContacts(DatabaseHelper.java:42)
at com.example.mateusz.sqllogowanie.SignUp$1.onClick(SignUp.java:36)
at android.view.View.performClick(View.java:6294)
at android.view.View$PerformClick.run(View.java:24770)
at android.os.Handler.handleCallback(Handler.java:790)
at android.os.Handler.dispatchMessage(Handler.java:99)
at android.os.Looper.loop(Looper.java:164)
at android.app.ActivityThread.main(ActivityThread.java:6494)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:438)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:807)
Your SqliteDatabase object is null.
Change this:
#Override
public void onCreate(SQLiteDatabase sqLiteDatabase) {
db.execSQL(TABLE_CREATE); //db is null here
this.db = db;
}
to:
#Override
public void onCreate(SQLiteDatabase sqLiteDatabase) {
this.db = sqLiteDatabase;
db.execSQL(TABLE_CREATE);
}
Also for in your insertContacts() method change query to:
String query = "select * from contacts";
Just look into you query string insertContacts you are using + instead of *
just change query to
String query = "select * from contacts";
These are the logcat errors which repeat 3 or 4 times when I run the app. I attached the database helper:
Error inserting time_type=3 proto_blob=[B#42439540 sync_state_mod_time_millis=1466838685054 context_id=e7029963-e329-4b1b-bb6e-24bb57e0ba04 end_time=1466837904524 module_id=com.google.android.contextmanager.module.ScreenModule start_time=1466837558811 sync_state=0 context_family=7 context_name=7 version=1
android.database.sqlite.SQLiteConstraintException: column context_id is not unique (code 19)
at android.database.sqlite.SQLiteConnection.nativeExecuteForLastInsertedRowId(Native Method)
at android.database.sqlite.SQLiteConnection.executeForLastInsertedRowId(SQLiteConnection.java:782)
at android.database.sqlite.SQLiteSession.executeForLastInsertedRowId(SQLiteSession.java:788)
at android.database.sqlite.SQLiteStatement.executeInsert(SQLiteStatement.java:86)
at android.database.sqlite.SQLiteDatabase.insertWithOnConflict(SQLiteDatabase.java:1469)
at android.database.sqlite.SQLiteDatabase.insert(SQLiteDatabase.java:1339)
at bsv.a(SourceFile:445)
at bsv.b(SourceFile:420)
at bsv.a(SourceFile:370)
at bsv.a(SourceFile:147)
at bsc.a(SourceFile:157)
at bjb.a(SourceFile:64)
at bix.run(SourceFile:52)
at biv.a(SourceFile:258)
at biv.handleMessage(SourceFile:251)
at jcq.run(SourceFile:141)
at jcy.run(SourceFile:438)
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1112)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:587)
at jhi.run(SourceFile:17)
at java.lang.Thread.run(Thread.java:841)
This is the Databasehelper class:
public class databasehelper extends SQLiteOpenHelper {
public static final String DATABASE_NAME="USMS.db";
public static final String TABLE_NAME="B_LIST";
public static final String COL1="ID";
public static final String COL2="NAME";
public static final String COL3="NUMBER";
public databasehelper(Context context) {
super(context, DATABASE_NAME, null, 2);
}
#Override
public void onCreate(SQLiteDatabase db) {
db.execSQL("Create Table "+TABLE_NAME+ "(ID INTEGER PRIMARY KEY AUTOINCREMENT, name text, number text);");
}
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
db.execSQL("DROP TABLE IF EXISTS " + TABLE_NAME);
onCreate(db);
}
public boolean InsertData(String name, String number) {
SQLiteDatabase db = this.getWritableDatabase();
ContentValues values =new ContentValues();
values.put(COL2,name);
values.put(COL3,number);
Long result = db.insert(TABLE_NAME, null ,values);
if(result==-1)
return false;
else
return true;
}
}
and this is my Main Activity class:
public class MainActivity extends AppCompatActivity {
databasehelper myDb;
EditText editname,editnumber;
Button bt1;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
myDb=new databasehelper(this);
editname = (EditText)findViewById(R.id.editText);
editnumber = (EditText)findViewById(R.id.editText2);
bt1 = (Button) findViewById(R.id.button);
}
public void adddate(){
bt1.setOnClickListener(new View.OnClickListener(){
#Override
public void onClick(View v) {
boolean inserted = myDb.InsertData(editname.getText().toString(),editnumber.getText().toString());
if (inserted=true)
Toast.makeText(MainActivity.this,"data inserted",Toast.LENGTH_LONG).show();
else
Toast.makeText(MainActivity.this,"not inserted",Toast.LENGTH_LONG).show();
}
});
}
}
I hope someone can help me, thanks in advance!
I am using a simple demo program, I am creating Database, then a table and trying to add values to the table
What i am able to do::
I am able to create table in sqlite
What i am not able to do::
I am not able to insert values values into it
MainActivity.java
public class MainActivity extends Activity{
Button addUser;
SqliteAdapter helper;
EditText usrName,pwd;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
helper=new SqliteAdapter(this);
addUser=(Button) findViewById(R.id.button1);
usrName=(EditText) findViewById(R.id.editText1);
pwd=(EditText)findViewById(R.id.editText2);
}
public void addUser(View view){
Log.d("LOG-MSG", "Onclick detected");
helper.insertData(usrName.getText().toString(), pwd.getText().toString());
}
}
SqliteAdapter.java
public class SqliteAdapter{
SqliteHelper helper;
ContentValues cv;
SQLiteDatabase db;
public SqliteAdapter(Context context){
helper=new SqliteHelper(context);
}
public void insertData(String name,String password){
db=helper.getWritableDatabase();
Log.d("LOG-MSG", "insertDataMethod Entry");
try {
cv.put(SqliteHelper.NAME, name);
Log.d("LOG-MSG", "Name inserted");
cv.put(SqliteHelper.PASSWORD, password);
Log.d("LOG-MSG", "password inserted");
} catch (Exception e) {
// TODO Auto-generated catch block
Log.d("LOG-MSG-EXCEPTION", e.toString());
}
db.insert(SqliteHelper.TABLE_NAME, null, cv);
}
static class SqliteHelper extends SQLiteOpenHelper{
private Context context;
private static final String DATABASE_NAME="MyDatabase";
private final static String TABLE_NAME="MyTable";
private static final int DATABASE_VERSION=1;
private final static String ID="_id";
private final static String NAME="name";
private final static String PASSWORD="password";
private static final String CREATE_TABLE="CREATE TABLE "+TABLE_NAME+"("+ID+" INTEGER PRIMARY KEY AUTOINCREMENT, "+NAME+" VARCHAR(225), "+PASSWORD+" VARCHAR(225));";
private static final String DROP_TABLE="DROP TABLE IF EXISTS "+TABLE_NAME+"";
public SqliteHelper(Context context) {
super(context, DATABASE_NAME, null, DATABASE_VERSION);
this.context=context;
Log.d("LOG-MSG", "Constructor Called");
Message.message(context, "Constructor Called");
}
#Override
public void onCreate(SQLiteDatabase db) {
Log.d("LOG-MSG", "OnCreate Called");
Message.message(context, "OnCreate Called");
try {
db.execSQL(CREATE_TABLE);
} catch (SQLException e) {
// TODO Auto-generated catch block
Log.d("LOG-MSG-onCreate", e.toString());
}
}
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
try {
db.execSQL(DROP_TABLE);
} catch (SQLException e) {
// TODO Auto-generated catch block
Log.d("LOG-MSG-onUpgrade", e.toString());
Message.message(context, "onUpgrade Called");
}
onCreate(db);
}
}
}
Log::
04-18 13:45:19.567: D/LOG-MSG(3371): Constructor Called
04-18 13:45:20.007: D/gralloc_goldfish(3371): Emulator without GPU emulation detected.
04-18 13:45:20.107: W/TextLayoutCache(3371): computeValuesWithHarfbuzz -- need to force to single run
04-18 13:46:22.747: D/LOG-MSG(3371): Onclick detected
04-18 13:46:22.809: D/LOG-MSG(3371): insertDataMethod Entry
04-18 13:46:22.809: D/LOG-MSG-EXCEPTION(3371): java.lang.NullPointerException
04-18 13:46:22.817: I/SqliteDatabaseCpp(3371): sqlite returned: error code = 1, msg = near "null": syntax error, db=/data/data/com.example.sqlitedatabasedemo/databases/MyDatabase
{After EDIT}
MainActivity.java
public class MainActivity extends Activity{
Button addUser;
SqliteAdapter helper;
EditText usrName,pwd;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
helper=new SqliteAdapter(this);
addUser=(Button) findViewById(R.id.button1);
usrName=(EditText) findViewById(R.id.editText1);
pwd=(EditText)findViewById(R.id.editText2);
}
public void addUser(View view){
Log.d("LOG-MSG", "Onclick detected");
long recievedValue=helper.insertData(usrName.getText().toString(), pwd.getText().toString());
if(recievedValue<0){
Log.d("LOG-MSG", "NotInserted");
}else
{
Log.d("LOG-MSG", "Inserted");
}
}
}
SqliteAdapter.java
public class SqliteAdapter{
SqliteHelper helper;
ContentValues cv;
SQLiteDatabase db;
public SqliteAdapter(Context context){
helper=new SqliteHelper(context);
}
public long insertData(String name,String password){
db=helper.getWritableDatabase();
Log.d("LOG-MSG", "insertDataMethod Entry");
cv=new ContentValues();
cv.put(SqliteHelper.NAME, name);
Log.d("LOG-MSG", "Name="+name+"inserted");
cv.put(SqliteHelper.PASSWORD, password);
Log.d("LOG-MSG", "password="+password+"inserted");
long result=db.insert(SqliteHelper.TABLE_NAME, null, cv);
return result;
}
static class SqliteHelper extends SQLiteOpenHelper{
private Context context;
private static final String DATABASE_NAME="MyDatabase";
private final static String TABLE_NAME="MyTable";
private static final int DATABASE_VERSION=1;
private final static String ID="_id";
private final static String NAME="name";
private final static String PASSWORD="password";
private static final String CREATE_TABLE="CREATE TABLE "+TABLE_NAME+"("+ID+" INTEGER PRIMARY KEY AUTOINCREMENT, "+NAME+" VARCHAR(225), "+PASSWORD+" VARCHAR(225));";
private static final String DROP_TABLE="DROP TABLE IF EXISTS "+TABLE_NAME+"";
public SqliteHelper(Context context) {
super(context, DATABASE_NAME, null, DATABASE_VERSION);
this.context=context;
Log.d("LOG-MSG", "Constructor Called");
Message.message(context, "Constructor Called");
}
#Override
public void onCreate(SQLiteDatabase db) {
Log.d("LOG-MSG", "OnCreate Called");
Message.message(context, "OnCreate Called");
db.execSQL(CREATE_TABLE);
}
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
db.execSQL(DROP_TABLE);
onCreate(db);
}
}
}
Log::
04-18 14:21:59.937: D/LOG-MSG(13661): Onclick detected
04-18 14:22:00.337: D/LOG-MSG(13661): insertDataMethod Entry
04-18 14:22:00.337: D/LOG-MSG(13661): Name=usainserted
04-18 14:22:00.337: D/LOG-MSG(13661): password=obamainserted
04-18 14:22:00.377: D/LOG-MSG(13661): Inserted
problem:: When i check the DDMS ....i can see the database. when i see it in query browser there are no values inserted .... why is this happening ... ive also tried to debug possible log statements
You haven't initialized your ContentValues cv object. There's an NPE you catch and then you proceed with attempting to insert with null ContentValues reference, causing the exception that terminates the app.
Add cv = new ContentValues() to your insert code.
Don't catch Exception. Most of the time it just hides the problems you should be fixing.
Similarly in onCreate() and onUpgrade() you should not catch SQLException but just let it propagate to the caller.
It seems you are not making the instame of ContentValues . Try to do as below
public void insertData(String name,String password){
db=helper.getWritableDatabase();
Log.d("LOG-MSG", "insertDataMethod Entry");
try {
cv = new ContentValues ();
cv.put(SqliteHelper.NAME, name);
Log.d("LOG-MSG", "Name inserted");
cv.put(SqliteHelper.PASSWORD, password);
Log.d("LOG-MSG", "password inserted");
} catch (Exception e) {
// TODO Auto-generated catch block
Log.d("LOG-MSG-EXCEPTION", e.toString());
}
db.insert(SqliteHelper.TABLE_NAME, null, cv);
}
hi you have a problem that ContentValues cv is not instantiated properly.
please add the line cv = new ContentValues ();
use the following code
public class SqliteAdapter{
SqliteHelper helper;
ContentValues cv;
SQLiteDatabase db;
public SqliteAdapter(Context context){
helper=new SqliteHelper(context);
}
public void insertData(String name,String password){
db=helper.getWritableDatabase();
cv = new ContentValues ();
Log.d("LOG-MSG", "insertDataMethod Entry");
try {
cv.put(SqliteHelper.NAME, name);
Log.d("LOG-MSG", "Name inserted");
cv.put(SqliteHelper.PASSWORD, password);
Log.d("LOG-MSG", "password inserted");
} catch (Exception e) {
// TODO Auto-generated catch block
Log.d("LOG-MSG-EXCEPTION", e.toString());
}
db.insert(SqliteHelper.TABLE_NAME, null, cv);
}
static class SqliteHelper extends SQLiteOpenHelper{
private Context context;
private static final String DATABASE_NAME="MyDatabase";
private final static String TABLE_NAME="MyTable";
private static final int DATABASE_VERSION=1;
private final static String ID="_id";
private final static String NAME="name";
private final static String PASSWORD="password";
private static final String CREATE_TABLE="CREATE TABLE "+TABLE_NAME+"("+ID+" INTEGER PRIMARY KEY AUTOINCREMENT, "+NAME+" VARCHAR(225), "+PASSWORD+" VARCHAR(225));";
private static final String DROP_TABLE="DROP TABLE IF EXISTS "+TABLE_NAME+"";
public SqliteHelper(Context context) {
super(context, DATABASE_NAME, null, DATABASE_VERSION);
this.context=context;
Log.d("LOG-MSG", "Constructor Called");
Message.message(context, "Constructor Called");
}
#Override
public void onCreate(SQLiteDatabase db) {
Log.d("LOG-MSG", "OnCreate Called");
Message.message(context, "OnCreate Called");
try {
db.execSQL(CREATE_TABLE);
} catch (SQLException e) {
// TODO Auto-generated catch block
Log.d("LOG-MSG-onCreate", e.toString());
}
}
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
try {
db.execSQL(DROP_TABLE);
} catch (SQLException e) {
// TODO Auto-generated catch block
Log.d("LOG-MSG-onUpgrade", e.toString());
Message.message(context, "onUpgrade Called");
}
onCreate(db);
}
}
}