getWritableDatabase closing my program - java

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

Related

How to delete a user from sqlite database in android studio?

Im trying to figure out how I can delete one user at a time by typing in the edittext the users username and clicking deleting which I then want all the users information (username, usernum, password, birthdate, phone, address) to be deleted from the database. Below is my code and for some reason it isnt working can any one please please help me!! Im very desperate and ive been trying to figure out the problem for hours.
DatabaseHelperUser class:
public class DatabaseHelperUser extends SQLiteOpenHelper {
public static final String DATABASE_NAME = "User.db";
public static final String TABLE_NAME = "User_table";
public static final String COL1 = "ID";
public static final String COL2 = "UserNum";
public static final String COL3 = "UserName";
public static final String COL4 = "Password";
public static final String COL5 = "BirthDate";
public static final String COL6 = "Phone";
public static final String COL7 = "Address";
public DatabaseHelperUser(Context context) {
super(context, DATABASE_NAME, null, 1);
}
#Override
public void onCreate(SQLiteDatabase db) {
db.execSQL("create table " + TABLE_NAME + " (ID INTEGER PRIMARY KEY AUTOINCREMENT, UserNum TEXT,UserName Text,Password Text,BirthDate Text,Phone Text,Address Text)");
}
#Override
public void onUpgrade(SQLiteDatabase db, int i, int i1) {
db.execSQL("DROP TABLE IF EXISTS " + TABLE_NAME);
onCreate(db);
}
public Cursor getData() {
SQLiteDatabase db = this.getWritableDatabase();
Cursor res = db.rawQuery("select * from " + TABLE_NAME, null);
return res;
}
public boolean deleteData(String UserName) {
SQLiteDatabase db = this.getWritableDatabase();
return db.delete(TABLE_NAME, "UserName" + "=?" + UserName, null) > 0;
}
}
RemoveUser class:
public class RemoveUser extends AppCompatActivity {
Button btdelete;
EditText txtUser;
DatabaseHelperUser myDb;
private String selectedName;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_remove_user);
btdelete = (Button) findViewById(R.id.butRemove);
txtUser = (EditText) findViewById(R.id.etxtUserName);
myDb = new DatabaseHelperUser(this);
btdelete.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
boolean delete = myDb.deleteData(txtUser.getText().toString());
if(delete == true)
Toast.makeText(RemoveUser.this,"User has been deleted", Toast.LENGTH_LONG).show();
else
Toast.makeText(RemoveUser.this,"User has not been deleted", Toast.LENGTH_LONG).show();
}
});
}
}
You must pass the variable UserName as the 3d argument of the method delete(), so it will replace the placeholder ? when the statement is executed:
public boolean deleteData(String UserName) {
SQLiteDatabase db = this.getWritableDatabase();
return db.delete(TABLE_NAME, "UserName = ?", new String[] {UserName}) > 0;
}

Retrieve Data As String From SQLite Database in Android Studio

I want to save name in the SQLite Database and later in another activity I want to retrieve that name as a String Value. But I am not being able to get data from the database. Help me please. My code is given below,
Database Helper:
private static final String TAG = "DatabaseHelper";
private static final String TABLE_NAME = "user";
private static final String COL1 = "ID";
private static final String COL2 = "name";
public void onCreate(SQLiteDatabase db) {String createTable =
"CREATE TABLE " + TABLE_NAME + " (ID INTEGER PRIMARY KEY
AUTOINCREMENT, " + COL2 +" TEXT)";
db.execSQL(createTable);}
public boolean addData(String item) {
SQLiteDatabase db = this.getWritableDatabase();
ContentValues contentValues = new ContentValues();
contentValues.put(COL2, item);
Log.d(TAG, "addData: Adding " + item + " to " + TABLE_NAME);
long result = db.insert(TABLE_NAME, null, contentValues);
if (result == -1) {
return false;
} else {
return true;
}
}
MainActivity:
mDatabaseHelper=new DatabaseHelper(this);
Username=(EditText)findViewById(R.id.user);
saveBtn=(Button)findViewById(R.id.button);
saveBtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
String newEntry = Username.getText().toString();
AddData(newEntry);
Username.setText("");
Intent intent = new Intent(MainActivity.this, HomeActivity.class);
startActivity(intent);
}
});
}
public void AddData(String newEntry) {
boolean insertData = mDatabaseHelper.addData(newEntry);
}
}
HomeActivity:
public class HomeActivity extends AppCompatActivity {
DatabaseHelper mDatabaseHelper;
String Username;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_home);
mDatabaseHelper = new DatabaseHelper(this);
}
}
Here, in this home activity i want to get the username as a string but I don't know how to do that. Help me please...
To retrieve data, you run a query that extracts the data into a Cursor. The Cursor will consist of 0-n rows and will have as many columns as defined in the query. You then move through the rows and use the appropriate Cursor get????? methods to get the actual data.
As an example you could add the following method to your DatabaseHelper :-
public String getName(long id) {
String rv = "not found";
SqliteDatabase db = this.getWritableDatabase();
String whereclause = "ID=?";
String[] whereargs = new String[]{String.valueOf(id)};
Cursor csr = db.query(TABLE_NAME,null,whereclause,whereargs,null,null,null);
if (csr.moveToFirst()) {
rv = csr.getString(csr.getColumnIndex(COL2));
}
return rv;
}
The above can then be used by String name = mDatabaseHelper.getName(1);.
Note that this assumes that a row with an ID of 1 exists.
Your Database Helper:
private static final String TAG = "DatabaseHelper";
private static final String TABLE_NAME = "user";
private static final String COL1 = "ID";
private static final String COL2 = "name";
private static final String createTable = "CREATE TABLE " + TABLE_NAME + " (" + COL1 +" INTEGER PRIMARY KEY AUTOINCREMENT, " + COL2 +" TEXT)"; // You have written ID inplace of COL1
public DatabaseHelper(Context context)
{
super(context,DB_NAME,null,1);
}
public void onCreate(SQLiteDatabase db)
{
db.execSQL(createTable);
}
public boolean insertData(String name) {
SQLiteDatabase sqLiteDatabase = this.getWritableDatabase();
ContentValues contentValues1 = new ContentValues();
contentValues1.put(COL2,name);
long result1 = sqLiteDatabase.insert(TABLE_NAME,null,contentValues1);
return result1 != -1;
}
public Cursor viewData()
{
SQLiteDatabase sqLiteDatabase = this.getReadableDatabase();
Cursor cursor ;
String query = "Select * from " +TABLE_NAME;
cursor= sqLiteDatabase.rawQuery(query, null);
return cursor;
}
Your Main Activity:
mDatabaseHelper=new DatabaseHelper(this);
Username=(EditText)findViewById(R.id.user);
saveBtn=(Button)findViewById(R.id.button);
saveBtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
String newEntry = Username.getText().toString();
mDatabaseHelper.insertData(newEntry);
Username.setText("");
Intent intent = new Intent(MainActivity.this, HomeActivity.class);
startActivity(intent);
}
});
}
}
Your Home Activity:
public class HomeActivity extends AppCompatActivity {
DatabaseHelper mDatabaseHelper;
String Username;
ArrayList<String> listItem;
ArrayAdapter adapter;
ListView listView;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_home);
mDatabaseHelper = new DatabaseHelper(this);
listView = (ListView) findViewById(R.id.listView);
listItem = new ArrayList<>();
viewData1();
}
private void viewData1() {
Cursor cursor = mDatabaseHelper.viewData();
if (cursor.getCount() == 0) {
Toast.makeText(this, "No data to show", Toast.LENGTH_SHORT).show();
} else {
while (cursor.moveToNext()) {
Log.i("message","Data got");
listItem.add(cursor.getString(1)); // Adding data received to a Listview
}
adapter = new ArrayAdapter<>(this, android.R.layout.simple_list_item_1, listItem);
listView.setAdapter(adapter);
}
}
}
check it out this library
it is very easy to implement
https://github.com/wisdomrider/SqliteClosedHelper

SQLite database error during execSQL()

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";

ListView does not show items that are stored in an SQLite database

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

Check if data was written in SQLite Database

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

Categories