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
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'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";
I just implemented an SQLite database for a simple to do app for persistence. However, the problem is that when I restart the app, I do not have my data that is stored in an SQLite database. The following is my SQLite helper class:
public class DatabaseHelper extends SQLiteOpenHelper {
public static final String DATABASE_NAME = "todo.db";
public static final String TABLE_NAME = "student";
public static final String ID = "id";
public static final String TO_DO = "todo";
public DatabaseHelper(Context context) {
super(context, DATABASE_NAME, null, 1);
}
#Override
public void onCreate(SQLiteDatabase sqLiteDatabase) {
String CREATE_TO_DO_TABLE = "CREATE TABLE "
+ TABLE_NAME
+ "("
+ ID
+ " INTEGER PRIMARY KEY AUTOINCREMENT, "
+ TO_DO
+ " TEXT"
+ ")";
sqLiteDatabase.execSQL(CREATE_TO_DO_TABLE);
}
#Override
public void onUpgrade(SQLiteDatabase sqLiteDatabase, int oldVersion, int newVersion) {
sqLiteDatabase.execSQL("DROP TABLE IF EXISTS " + TABLE_NAME);
onCreate(sqLiteDatabase);
}
public boolean insertData(String todo){
SQLiteDatabase sqLiteDatabase = this.getWritableDatabase();
ContentValues contentValues = new ContentValues();
contentValues.put(TO_DO, todo);
sqLiteDatabase.insert(TABLE_NAME, null, contentValues);
return true;
}
}
And in my MainActivity.java, I'm adding my List items into the database as well as the ListView.
public class MainActivity extends AppCompatActivity {
DatabaseHelper databaseHelper;
private final int REQUEST_CODE = 10;
ArrayList <String> toDoItems = new ArrayList<>();
ArrayAdapter<String> adapter;
ListView listItems;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
listItems = (ListView) findViewById(R.id.listViewItems);
adapter = new ArrayAdapter<>(this, android.R.layout.simple_list_item_1, toDoItems);
listItems.setAdapter(adapter);
databaseHelper = new DatabaseHelper(this);
...
}
public void addItem(View v){
EditText newItem = (EditText) findViewById(R.id.itemInputEditText);
String item = newItem.getText().toString();
databaseHelper.insertData(item);
adapter.add(item);
newItem.setText("");
}
}
I believe I need to do something in the onCreate method but my addItem(View v) method is called through the button onClick.
as #cristian_franco said, the toDoItems is empty yet. What you need to do is to create another method in DatabaseHelper class like this.
public ArrayList<String> showStudents(){
ArrayList<String> list = new ArrayList<String>();
SQLiteDatabase db = this.getReadableDatabase();
String query = "SELECT * FROM " + TABLE_NAME;
Cursor cursor = db.rawQuery(query, null);
if (cursor.moveToFirst()) {
do {
list.add(cursor.getString(0)+" "+cursor.getString(1));
} while (cursor.moveToNext());
}
cursor.close();
db.close();
return list;
}
and then assign toDoItems like this
databaseHelper = new DatabaseHelper(this);
toDoItems=databaseHelper.showStudents();
Let me know if there is any mistake in my code.
implment this function for get the values,
public void getDatos(){
SQLiteDatabase database = databaseHelper.getWritableDatabase();
Cursor cursor = database.rawQuery("select * from student",null);
if (cursor.moveToFirst()) {
while (!cursor.isAfterLast()) {
String name = cursor.getString(cursor.getColumnIndex("todo"));
Toast.makeText(getApplicationContext(), name, Toast.LENGTH_LONG).show();
cursor.moveToNext();
}
}
}
yout funciion for save is correct only you need get the information
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
I want to save the Score from a Quiz in a SQLite Database and change an image in another activity if the Score is 5. There is no error shown, but even if I score 5 the image won't change... How can I log the content of my database to check if the score was added or how can I find the mistake?
DB Helper:
public class DbHelper extends SQLiteOpenHelper {
private static final int DATABASE_VERSION = 7;
private static final String DATABASE_NAME = "CE";
public static final String SCORE_TABLE = "score";
public static final String COLUMN_ID = "ID";
public static final String COLUMN_SCORE = "SCORE";
public static final String COLUMN_MARKERID = "MARKERID";
private SQLiteDatabase dbase;
public DbHelper(Context context) {
super(context, DATABASE_NAME, null, DATABASE_VERSION);
}
#Override
public void onCreate(SQLiteDatabase db) {
dbase= db;
String create_query = "CREATE TABLE IF NOT EXITS " + SCORE_TABLE + " ( "
+ COLUMN_ID + " INTEGER PRIMARY KEY AUTOINCREMENT, "
+ COLUMN_SCORE + " INTEGER, "
+ COLUMN_MARKERID + " TEXT) ";
db.execSQL(create_query);
}
public void addScore (DbHelper dbh, Integer score, String markerID) {
dbase = dbh.getWritableDatabase();
ContentValues cv = new ContentValues();
cv.put(COLUMN_SCORE, score);
cv.put(COLUMN_MARKERID, markerID);
dbase.insert(SCORE_TABLE, null, cv);
}
public Cursor getScore(DbHelper dbh) {
dbase = dbh.getReadableDatabase();
String columns[] = {COLUMN_SCORE, COLUMN_MARKERID};
Cursor cursor = dbase.query(SCORE_TABLE, columns, null, null, null, null, null);
return cursor;
}
Write the Score into the Database after completing the Quiz:
public class ResultActivity extends Activity {
String markerID;
int score;
TextView t=(TextView)findViewById(R.id.textResult);
Button saveButton = (Button) findViewById(R.id.saveButton);
Context context = this;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.result_layout);
Bundle b = getIntent().getExtras();
score = b.getInt("score");
markerID = b.getString("markerID");
}
saveButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
DbHelper dbh = new DbHelper(context);
dbh.addScore(dbh,score,markerID);
Intent intent = new Intent(ResultActivity.this, Discover.class);
intent.putExtra("MarkerID", markerID);
startActivity(intent);
}
});
}
Discover class -> Check if score is 5 and change image if:
DbHelper dbh = new DbHelper(context);
Cursor cursor = dbh.getScore(dbh);
cursor.moveToFirst();
if (cursor.moveToFirst()) {
do {
if (Integer.parseInt(cursor.getString(0))== 5 && InfoUeberschrift.toString().equals(cursor.getString(1))){
ImageDone.setImageResource(R.drawable.markerdone);
}
}
while(cursor.moveToNext());
}
cursor.close();
}
The SQLiteDatabase insert function returns a long value, so if an error has occurred it returns -1.
'the row ID of the newly inserted row, or -1 if an error occurred'
http://developer.android.com/reference/android/database/sqlite/SQLiteDatabase.html
This can be used to see if the insert is happening correctly.
Or you can wrap in try and catch and print message like so
try {
//code
} catch(SQLiteException ex) {
Log.v("Insert into database exception caught", ex.getMessage());
return -1;
}
}
When I have issues using Java and SQLite i normally do it directly with the SQLite desktop version using Shell, as I find it easier to test out table design.
Hope this helps