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";
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.
This question already has answers here:
When does SQLiteOpenHelper onCreate() / onUpgrade() run?
(15 answers)
Closed 5 years ago.
I am trying to create two tables in SQLite database in my Android application but it shows the following errors. Basically, the second table that I am trying to create won't be created. Any help would be appreciated.
This is the error that I got:
02-22 09:16:33.005 22404-22404/proed.hotelbooking E/SQLiteLog: (1) no such table: room 02-22 09:16:33.007 22404-22404/proed.hotelbooking
E/SQLiteDatabase: Error inserting room_id=1 room_price=1000 room_type=Single hotel_id=1
android.database.sqlite.SQLiteException: no such table: room (code 1): ,
while compiling: INSERT INTO room(room_id,room_price,room_type,hotel_id) VALUES (?,?,?,?)
at android.database.sqlite.SQLiteConnection.nativePrepareStatement(Native Method)
at android.database.sqlite.SQLiteConnection.acquirePreparedStatement(SQLiteConnection.java:889)
at android.database.sqlite.SQLiteConnection.prepare(SQLiteConnection.java:500)
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:1472)
at android.database.sqlite.SQLiteDatabase.insert(SQLiteDatabase.java:1343)
at proed.hotelbooking.HotelDatabaseHelper.insertRoom(HotelDatabaseHelper.java:70)
at proed.hotelbooking.RoomInfoActivity.onRoomButtonClick(RoomInfoActivity.java:42)
at java.lang.reflect.Method.invoke(Native Method)
at android.support.v7.app.AppCompatViewInflater$DeclaredOnClickListener.onClick(AppCompatViewInflater.java:288)
at android.view.View.performClick(View.java:6256)
at android.view.View$PerformClick.run(View.java:24701)
at android.os.Handler.handleCallback(Handler.java:789)
at android.os.Handler.dispatchMessage(Handler.java:98)
at android.os.Looper.loop(Looper.java:164)
at android.app.ActivityThread.main(ActivityThread.java:6541)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.Zygote$MethodAndArgsCaller.run(Zygote.java:240)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:767)
This is my database helper class. Am I missing something?
public class HotelDatabaseHelper extends SQLiteOpenHelper {
private static int DATABASE_VERSION = 1;
private static final String DATABASE_NAME = "hotels";
private static final String TABLE_NAME = "hotel";
private static final String TABLE_ROOM = "room";
private static final String col_id = "id";
private static final String col_name = "hotelName";
private static final String col_location = "location";
private static final String room_id = "room_id";
private static final String room_type = "room_type";
private static final String room_price = "room_price";
private static final String hotel_id = "hotel_id";
private static final String hotel_table = "CREATE TABLE `hotel` ( `id` INTEGER primary key not null, `hotelName` VARCHAR not null, `location` VARCHAR not null )";
private static final String room_table ="CREATE TABLE `room` ( `room_id` INTEGER primary key not null, `room_type` VARCHAR not null, `room_price` VARCHAR not null, `hotel_id` VARCHAR not null )";
SQLiteDatabase db;
private static final String info = "DATABASE";
public HotelDatabaseHelper(Context context)
{
super(context, DATABASE_NAME, null, DATABASE_VERSION);
}
#Override
public void onCreate(SQLiteDatabase db) {
db.execSQL(hotel_table);
db.execSQL(room_table);
Log.i(info, "Created!!!!!!!!!");
}
public void insertHotel(Hotels h)
{
db = this.getWritableDatabase();
ContentValues values = new ContentValues();
values.put(col_id, h.getId());
values.put(col_name, h.getHotelName());
values.put(col_location, h.getLocation());
db.insert(TABLE_NAME, null, values);
db.close();
}
public void insertRoom(Hotels hotel)
{
db = this.getWritableDatabase();
ContentValues values = new ContentValues();
values.put(room_id, hotel.getRoom_id());
values.put(room_price, hotel.getRoom_price());
values.put(room_type, hotel.getRoom_type());
values.put(hotel_id, hotel.getHotel_id());
db.insert(TABLE_ROOM, null, values);
db.close();
}
public Cursor getListContents()
{
db = this.getWritableDatabase();
Cursor data = db.rawQuery("SELECT * FROM " + TABLE_NAME, null);
return data;
}
#Override
public void onUpgrade(SQLiteDatabase sqLiteDatabase, int i, int i1) {
db.execSQL("DROP TABLE IF EXISTS "+TABLE_NAME);
db.execSQL("DROP TABLE IF EXISTS " + TABLE_ROOM);
onCreate(db);
}
}
This is my class to insert data:
public class RoomInfoActivity extends AppCompatActivity {
HotelDatabaseHelper helper = new HotelDatabaseHelper(this);
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_room_info);
}
public void onRoomButtonClick(View v)
{
if (v.getId()==R.id.addRoom) {
EditText id = findViewById(R.id.roomId);
EditText type = findViewById(R.id.roomType);
EditText price = findViewById(R.id.roomPrice);
EditText hotel_id = findViewById(R.id.hotelID);
String room_id = id.getText().toString();
String room_type = type.getText().toString();
String room_price = price.getText().toString();
String hotelID = hotel_id.getText().toString();
if (TextUtils.isEmpty(room_id) || TextUtils.isEmpty(room_type) || TextUtils.isEmpty(room_price) || TextUtils.isEmpty(hotelID)) {
Toast.makeText(this, "Please do not leave any field blank! ", Toast.LENGTH_SHORT).show();
return;
} else {
Hotels hotels = new Hotels();
hotels.setRoom_id(room_id);
hotels.setRoom_price(room_price);
hotels.setRoom_type(room_type);
hotels.setHotel_id(hotelID);
helper.insertRoom(hotels);
//Toast.makeText(this, "Data Added To The Database", Toast.LENGTH_SHORT).show();
}
}
}
public void onViewRoomButtonClick(View view)
{
if (view.getId()==R.id.viewRoom)
{
Intent intent = new Intent(RoomInfoActivity.this, ViewRoomContents.class);
startActivity(intent);
}
}
}
If you modified the database, for example add/remove table/column, you need to
uninstall the app from the emulator/device and then reinstall it.
If that not works, just go to File and click on Invalidate Caches/Restart
I've checked your DatabaseHelper and it has no problem.
Could you show the code for init database and insert data?
Maybe the issue come from initial steps.
I have a listview, when a user clicks on an item from the listview, it calls a function getRow, which takes the id of the clicked item and retrieves the Name of the clicked item.
However, when I click the item, i am able to retrieve the ID, but it doesn't want to run the query to retrieve the rest of the information.
Here is my code, and logcat:
UserDbHelper.java (class)
public class UserDbHelper extends SQLiteOpenHelper {
SQLiteDatabase db;
UserDbHelper userDb;
private static final String DATABASE_NAME = "USERINFO.db";
private static final int DATABASE_VERSION = 1;
private static final String CREATE_QUERY =
"CREATE TABLE "+ UserContract.NewUserInfo.TABLE_NAME+"("+ UserContract.NewUserInfo.USER_ROWID+" integer primary key autoincrement, "+ UserContract.NewUserInfo.USER_NAME+" TEXT,"+
UserContract.NewUserInfo.USER_MOBILE+" TEXT,"+ UserContract.NewUserInfo.USER_EMAIL+" TEXT);";
public static final String[] ALL_KEYS = new String[] {UserContract.NewUserInfo.USER_ROWID, UserContract.NewUserInfo.USER_NAME, UserContract.NewUserInfo.USER_MOBILE, UserContract.NewUserInfo.USER_EMAIL};
public UserDbHelper(Context context){
super(context,DATABASE_NAME,null,DATABASE_VERSION);
Log.d("DATABASE OPERATIONS", "DATABASE CREATED/ OPENED...");
}
#Override
public void onCreate(SQLiteDatabase sqLiteDatabase) {
sqLiteDatabase.execSQL(CREATE_QUERY);
Log.d("DATABASE OPERATIONS", "TABLE CREATED...");
}
public void addInformations(String name, String mob, String email, SQLiteDatabase sqLiteDatabase){
ContentValues contentValues = new ContentValues();
contentValues.put(UserContract.NewUserInfo.USER_NAME,name);
contentValues.put(UserContract.NewUserInfo.USER_MOBILE,mob);
contentValues.put(UserContract.NewUserInfo.USER_EMAIL,email);
sqLiteDatabase.insert(UserContract.NewUserInfo.TABLE_NAME,null,contentValues);
Log.d("DATABASE OPERATIONS", "ONE ROW INSERTED....");
}
public Cursor getInformations(SQLiteDatabase sqLiteDatabase){
Cursor cursor;
String[] projections = {UserContract.NewUserInfo.USER_NAME, UserContract.NewUserInfo.USER_MOBILE, UserContract.NewUserInfo.USER_EMAIL};
cursor = sqLiteDatabase.query(UserContract.NewUserInfo.TABLE_NAME, projections,null,null,null,null,null);
return cursor;
}
// Get a specific row (by rowId)
public Cursor getRow(long rowId) {
String where = UserContract.NewUserInfo.USER_ROWID +"="+ rowId;
Log.e("ID= ",where);
String select = "SELECT "+ UserContract.NewUserInfo.USER_NAME+" FROM "+ UserContract.NewUserInfo.TABLE_NAME+ " WHERE "+where;
Log.e("query = ", select);
db.execSQL(select);
return null;
}
#Override
public void onUpgrade(SQLiteDatabase sqLiteDatabase, int i, int i1) {
}
}
ListView.java (Activity that handles the click events)
public class ListActivity extends AppCompatActivity {
ListView listView;
SQLiteDatabase sqLiteDatabase;;
UserDbHelper user;
Cursor cursor;
ListDataAdapter listDataAdapter;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_list);
listView = (ListView) findViewById(R.id.list_view);
listDataAdapter = new ListDataAdapter(getApplicationContext(),R.layout.row_layout);
listView.setAdapter(listDataAdapter);
user = new UserDbHelper(getApplicationContext());
sqLiteDatabase = user.getReadableDatabase();
cursor = user.getInformations(sqLiteDatabase);
if(cursor.moveToFirst()){
do{
String name, mob, email;
name = cursor.getString(0);
mob = cursor.getString(1);
email = cursor.getString(2);
DataProvider dataProvider = new DataProvider(name,mob,email);
listDataAdapter.add(dataProvider);
}while(cursor.moveToNext());
}
listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> adapterView, View view, int i, long ldatabase) {
Cursor cursor = user.getRow(i);
if(cursor.moveToFirst()){
long idDb = cursor.getLong(0);
String message = "ID is: " +idDb;
Toast.makeText(ListActivity.this, message, Toast.LENGTH_SHORT).show();
}
}
});
}
}
The OnItemClickListener, gets the id of the clicked item, passes that value to the UserDbHelper class, to the function getRow, where the function takes the id, and runs a query, however when it wants to run the query it, it crashes my app.
I also printed the ID in the logcat to check if i was getting an id, which i was.
Here is the LOGCAT:
01-12 17:40:47.574 13309-13309/bluwyreinc.rohansfitness E/ID=: _id=6
01-12 17:40:47.574 13309-13309/bluwyreinc.rohansfitness E/query =: SELECT user_name FROM user_info WHERE _id=6
01-12 17:40:47.575 13309-13309/bluwyreinc.rohansfitness E/AndroidRuntime: FATAL EXCEPTION: main
Process: bluwyreinc.rohansfitness, PID: 13309
java.lang.NullPointerException: Attempt to invoke virtual method 'void android.database.sqlite.SQLiteDatabase.execSQL(java.lang.String)' on a null object reference
at bluwyreinc.rohansfitness.UserDbHelper.getRow(UserDbHelper.java:68)
at bluwyreinc.rohansfitness.ListActivity$1.onItemClick(ListActivity.java:54)
at android.widget.AdapterView.performItemClick(AdapterView.java:343)
at android.widget.AbsListView.performItemClick(AbsListView.java:1665)
at android.widget.AbsListView$PerformClick.run(AbsListView.java:4075)
at android.widget.AbsListView$10.run(AbsListView.java:6552)
at android.os.Handler.handleCallback(Handler.java:751)
at android.os.Handler.dispatchMessage(Handler.java:95)
at android.os.Looper.loop(Looper.java:154)
at android.app.ActivityThread.main(ActivityThread.java:6823)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1563)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1451)
01-12 17:40:48.090 3104-3160/? E/ActivityTrigger: activityResumeTrigger: not whiteListedbluwyreinc.rohansfitness/bluwyreinc.rohansfitness.MainActivity/1
The problem is in your this method:
public Cursor getRow(long rowId) {
String where = UserContract.NewUserInfo.USER_ROWID +"="+ rowId;
Log.e("ID= ",where);
String select = "SELECT "+ UserContract.NewUserInfo.USER_NAME+" FROM "+ UserContract.NewUserInfo.TABLE_NAME+ " WHERE "+where;
Log.e("query = ", select);
// Here db is null.
db.execSQL(select);
return null;
}
Pass it sqLiteDatabase and It should be returning the cursor, something like this:
public Cursor getRow(SQLiteDatabase sqLiteDatabase, long rowId) {
String where = UserContract.NewUserInfo.USER_ROWID +"="+ rowId;
Log.e("ID= ",where);
String select = "SELECT "+ UserContract.NewUserInfo.USER_NAME+" FROM "+ UserContract.NewUserInfo.TABLE_NAME+ " WHERE "+where;
Log.e("query = ", select);
cursor = sqLiteDatabase.query(select);
return cursor;
}
You never set any value to db field, so when you try to use it, it's null and causes your crash. You should ensure db is not null before using it
I just recently started working on a project but my program repeatedly crashes. I think it is due to getWritableDatabase. I was following a tutorial and i did everything they told me to, i even checked over my code multiple times. If u are interested in the link to the tutorial, it is https://www.youtube.com/watch?v=38DOncHIazs
public class AddExpense extends Activity {
EditText inputDate , inputDescription, inputCategory, inputAmount;
Context context;
UserDbHelper userDbHelper;
SQLiteDatabase sqLiteDatabase;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_add_expense);
inputDate = (EditText) findViewById(R.id.inputDate);
inputDescription = (EditText) findViewById(R.id.inputDescription);
inputCategory = (EditText) findViewById(R.id.inputCategory);
inputAmount = (EditText) findViewById(R.id.inputAmount);
}
public void AddExpense(View view){
String date = inputDate.getText().toString();
String description = inputDescription.getText().toString();
String category = inputCategory.getText().toString();
String amount = inputAmount.getText().toString();
userDbHelper = new UserDbHelper(context);
sqLiteDatabase = userDbHelper.getWritableDatabase();
userDbHelper.addInformations(date, description, category, amount, sqLiteDatabase);
Toast.makeText(getBaseContext(),"Data Saved", Toast.LENGTH_LONG).show();
userDbHelper.close();
}
}
And this is my database helper class
public class UserDbHelper extends SQLiteOpenHelper {
private static final String DATABASE_NAME = "EXPENSE.DB";
private static final int DATABASE_VERSION = 1;
private static final String CREATE_QUERY =
"CREATE TABLE " + ExpenseDatabase.NewExpenseItem.TABLE_NAME + " ("+ ExpenseDatabase.NewExpenseItem.DATE+" TEXT,"+ ExpenseDatabase.NewExpenseItem.DESCRIPTION+ " TEXT,"+
ExpenseDatabase.NewExpenseItem.CATEGORY+" TEXT," + ExpenseDatabase.NewExpenseItem.AMOUNT+ " TEXT);";
public UserDbHelper(Context context){
super(context,DATABASE_NAME,null,DATABASE_VERSION);
Log.e("DATABASE OPERATIONS", "Database created / opened");
}
#Override
public void onCreate(SQLiteDatabase db) {
db.execSQL(CREATE_QUERY);
Log.e("DATABASE OPERATIONS", "Table created");
}
public void addInformations(String date, String description, String category, String amount,SQLiteDatabase db ){
ContentValues contentValues = new ContentValues();
contentValues.put(ExpenseDatabase.NewExpenseItem.DATE,date);
contentValues.put(ExpenseDatabase.NewExpenseItem.DESCRIPTION, description);
contentValues.put(ExpenseDatabase.NewExpenseItem.CATEGORY, category);
contentValues.put(ExpenseDatabase.NewExpenseItem.AMOUNT, amount);
db.insert(ExpenseDatabase.NewExpenseItem.TABLE_NAME, null, contentValues);
Log.e("DATABASE OPERATIONS", "One row inserted in DB");
}
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
}
}
In my experience it is better if you just make a method in your UserDbHelper class and pass the relevant values to that method.
Try to do everything related to database in that class itself. I think it will work.
EDIT:
public void addInformation(your values){
ContentValues values = new ContentValues();
values.put();
SQLiteDatabase db = getWritableDatabase();
db.insert(TABLE,null,values);
db.close();
}
Try using this userDbHelper = new UserDbHelper(this); some you're context is not initialized. It might be the issue
what i am trying do is create a table then insert some values into it then and select.
The problem i am facing is the app is unfortunately stopping.I don't know what is the problem.
My code is:
This class calls the database handler
public class SaveEvents extends Activity {
private static final String DB_NAME = "EventDB";
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.edit_product);
Bundle extras=getIntent().getExtras();
String event=extras.getString("event");
String date=extras.getString("date");
String college=extras.getString("college");
DatabaseHandler db = new DatabaseHandler(getApplicationContext());
db.insert_data(event,date,college);
String c=db.select_data();
Toast.makeText(getApplicationContext(), "EventName: "+c+"", Toast.LENGTH_LONG).show();
}
}
Database Handler
public class DatabaseHandler extends SQLiteOpenHelper {
private static final int DATABASE_VERSION = 1;
private static final String DATABASE_NAME = "EventDB";
private static final String TABLE_NAME = "eventlist";
public DatabaseHandler(Context context) {
super(context, DATABASE_NAME, null, DATABASE_VERSION);
}
#Override
public void onCreate(SQLiteDatabase db) {
// Category table create query
String CREATE_ITEM_TABLE;
CREATE_ITEM_TABLE = "CREATE TABLE eventlist(eventname varchar(100),eventdate varchar(100),college varchar(100));";
db.execSQL(CREATE_ITEM_TABLE);
}
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
}
void insert_data(String eventname,String date,String college)
{
SQLiteDatabase db = this.getWritableDatabase();
ContentValues values = new ContentValues();
values.put("eventname", eventname);
values.put("eventdate",date);
values.put("college",college);
db.insert(TABLE_NAME,null,values);
db.close();
}
public String select_data()
{
SQLiteDatabase db = this.getWritableDatabase();
String selectQuery = "SELECT eventname FROM eventlist where eventname='techcontest'";
String c=null;
Cursor cursor = db.rawQuery(selectQuery, null);
cursor.moveToFirst();
c=cursor.getString(0);
return c;
}
}
My logcat shows
03-16 20:00:19.116 8378-8378/com.example.android E/SQLiteLog﹕ (1) no such table: eventlist
03-16 20:00:19.122 8378-8378/com.example.android E/SQLiteDatabase﹕ Error inserting college=acs university eventdate=2-02-15 eventname=techocontest
android.database.sqlite.SQLiteException: no such table: eventlist (code 1): , while compiling: INSERT INTO eventlist(college,eventdate,eventname) VALUES (?,?,?)
It doesn't look like you are closing the database in the select_data() method.