Android Studio project - java

Hi i am doing an andorid studio project, when I am adding my data the application and then trying to view the data im getting an Error saying "Error, Nothing Found". I made up a SQLite Database and hope someone can help me find the error.
package ie.wit.andrew.drivingschool;
import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
public class DatabaseHelper extends SQLiteOpenHelper {
public static final String DATABASE_NAME = "Driver.db";
public static final String TABLE_NAME = "driver_table";
public static final String COL_1 = "ID";
public static final String COL_2 = "NAME";
public static final String COL_3 = "DATE OF BIRTH";
public static final String COL_4 = "LOGBOOK NUMBER"; //Making up my
//database of the
//information I will
//be entering into my
//application
public static final String COL_5 = "LESSON NUMBER";
public DatabaseHelper(Context context) {
super(context, DATABASE_NAME, null, 1); //when this constructor is
//called your Database has been
//created
}
#Override
public void onCreate(SQLiteDatabase db) {
db.execSQL("create table " + TABLE_NAME + " (ID INTEGER PRIMARY KEY
AUTOINCREMENT,NAME TEXT,DATE OF BIRTH TEXT, LOGBOOK NUMBER TEXT, LESSON
NUMBER INTEGER)");
}
#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 dateofbirth, String
logbooknumber, String lessonnumber) {
SQLiteDatabase db = this.getWritableDatabase();
ContentValues contentValues = new ContentValues();
contentValues.put(COL_2,name);
contentValues.put(COL_3,dateofbirth);
contentValues.put(COL_4,logbooknumber);
contentValues.put(COL_5,lessonnumber);
long result = db.insert(TABLE_NAME,null,contentValues); //This method
//returns -1
if (result == -1)
return false;
else
return true;
}
public Cursor getAllData() {
SQLiteDatabase db = this.getWritableDatabase();
Cursor res = db.rawQuery("select * from "+ TABLE_NAME,null);
return res;
}
}
package ie.wit.andrew.drivingschool;
import android.database.Cursor;
import android.support.v7.app.AlertDialog;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;
public class DrivingSchool extends AppCompatActivity {
DatabaseHelper myDb;
EditText editName,editDateofBirth,editLogbookNumber,editLessonNumber;
Button btnAddData;
Button btnviewAll;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_driving_school);
myDb = new DatabaseHelper(this);
editName = (EditText)findViewById(R.id.editText_name);
editDateofBirth = (EditText)findViewById(R.id.editText_dateofbirth);
editLogbookNumber = (EditText)findViewById(R.id.editText_logbooknumber);
editLessonNumber = (EditText)findViewById(R.id.editText_lessonNumber);
btnAddData = (Button)findViewById(R.id.button_add);
btnviewAll = (Button)findViewById(R.id.button_viewAll);
AddData();
viewAll();
}
public void AddData() {
btnAddData.setOnClickListener(
new View.OnClickListener() {
#Override
public void onClick(View v) {
boolean isInserted =
myDb.insertData(editName.getText().toString(),
editDateofBirth.getText().toString(),
editLogbookNumber.getText().toString(),
editLessonNumber.getText().toString());
if(isInserted = true)
Toast.makeText(DrivingSchool.this,"Data
Inserted",Toast.LENGTH_LONG).show();
else
Toast.makeText(DrivingSchool.this,"Data not
Inserted", Toast.LENGTH_LONG).show();
}
}
);
}
public void viewAll() {
btnviewAll.setOnClickListener(
new View.OnClickListener() {
#Override
public void onClick(View v){
Cursor res = myDb.getAllData();
if(res.getCount() == 0) {
//Show Message
showMessage("Error", "Nothing found");
return;
}
StringBuffer buffer = new StringBuffer();
while(res.moveToNext()) {
buffer.append("ID : "+ res.getString(0)+"\n");
buffer.append("NAME : "+ res.getString(1)+"\n");
buffer.append("DATE OF BIRTH : "+
res.getString(2)+"\n");
buffer.append("LOGBOOK NUMBER : "+
res.getString(3)+"\n\n");;
}
//showdata
showMessage("Data",buffer.toString());
}
}
);
}
public void showMessage(String title,String Message){
AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setCancelable(true);
builder.setTitle(title);
builder.setMessage(Message);
builder.show();
}
}

Try removing space from your column name's

you are providing wrong column name that's why your database is not creating, please check this link for complete guide for creating and using database in Android application
http://www.androidhive.info/2011/11/android-sqlite-database-tutorial/

Related

How to show records from sqlite database on my app in a listview

I'm creating an app for doctor's appointment.. So I want to see the booked appointments records in the listview for different activities with a delete button to delete a specific record..
this is my code for making appointments...
that is Appo.java
package com.example.medilyf;
import android.app.DatePickerDialog;
import android.content.Intent;
import android.os.Bundle;
import android.text.InputType;
import android.view.View;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.DatePicker;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;
import androidx.appcompat.app.AppCompatActivity;
import java.util.Calendar;
public class Appo extends AppCompatActivity {
DatePickerDialog picker;
EditText eText;
Button btnGet, confirm, seeappo;
TextView tvw, text, receiver_msg;
DBHelper myDB;
CheckBox android, java, angular, python;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_appo);
tvw = findViewById(R.id.textView1);
eText = findViewById(R.id.editText1);
myDB = new DBHelper(Appo.this);
android = findViewById(R.id.checkBox);
angular = findViewById(R.id.checkBox1);
java = findViewById(R.id.checkBox2);
python = findViewById(R.id.checkBox3);
text = findViewById(R.id.txt);
Button btn = findViewById(R.id.getbtn);
receiver_msg =findViewById(R.id.textView5);
// create the get Intent object
Intent intent = getIntent();
String str = intent.getStringExtra("dr_name");
// display the string into textView
receiver_msg.setText(str);
eText.setInputType(InputType.TYPE_NULL);
eText.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
final Calendar cldr = Calendar.getInstance();
int day = cldr.get(Calendar.DAY_OF_MONTH);
int month = cldr.get(Calendar.MONTH);
int year = cldr.get(Calendar.YEAR);
// date picker dialog
picker = new DatePickerDialog(Appo.this,
new DatePickerDialog.OnDateSetListener() {
#Override
public void onDateSet(DatePicker view, int year, int monthOfYear, int dayOfMonth) {
eText.setText(dayOfMonth + "/" + (monthOfYear + 1) + "/" + year);
}
}, year, month, day);
picker.show();
}
});
btnGet = findViewById(R.id.button1);
btnGet.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
String txt = eText.getText().toString();
tvw.setText(txt);
}
});
btn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
String result ="";
if (android.isChecked()) {
result += "\n9:00 - 10:30";
}
if (angular.isChecked()) {
result += "\n10:30 -11:30";
}
if (java.isChecked()) {
result += "\n11:30 -12:30";
}
if (python.isChecked()) {
result += "\n2:00 - 3:00";
}
text.setText(result);
}
});
confirm = findViewById(R.id.confirm);
confirm.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
String time = text.getText().toString();
String date = tvw.getText().toString();
if (str.equals("")) {
Toast.makeText(Appo.this, "Blank values", Toast.LENGTH_SHORT).show();
} else {
boolean booking = myDB.insertData2(str, time, date);
if (booking) {
Toast.makeText(Appo.this, "Booking Confirmed", Toast.LENGTH_SHORT).show();
} else {
Toast.makeText(Appo.this, "Booking not confirmed", Toast.LENGTH_SHORT).show();
}
}
}
});
}
public void onCheckboxClicked(View view) {
boolean checked = ((CheckBox) view).isChecked();
String str="";
// Check which checkbox was clicked
switch(view.getId()) {
case R.id.checkBox:
str = checked?"9:00 - 10:30 Selected":"9:00 - 10:30 Deselected";
break;
case R.id.checkBox1:
str = checked?"10:30 -11:30 Selected":"10:30 -11:30 Deselected";
break;
case R.id.checkBox2:
str = checked?"11:30 -12:30 Selected":"11:30 -12:30 Deselected";
break;
case R.id.checkBox3:
str = checked?"2:00 - 3:00 Selected":"2:00 - 3:00 Deselected";
break;
}
Toast.makeText(Appo.this, str, Toast.LENGTH_SHORT).show();
}
}
This is the code for sqlite database... that is DBHelper.java
package com.example.medilyf;
import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
import androidx.annotation.Nullable;
import java.util.ArrayList;
public class DBHelper extends SQLiteOpenHelper {
public static final String col1="name";
public static final String col2="username";
public static final String col3="email";
public static final String col4="PhoneNo";
public static final String col5="password";
public static final String NAME = "name";
public static final String PHONE = "phone";
public static final String col6="Appointment_id ";
public static final String col7="full_Name ";
public static final String col9="Doc_name ";
public static final String col12="ATime ";
public static final String col8="Phone_Number";
public DBHelper(#Nullable Context context) {
super(context,"Login.db",null,1);
}
#Override
public void onCreate(SQLiteDatabase myDB) {
myDB.execSQL("create Table users(name Text, username Text primary key, email Text, PhoneNo Text, password Text)");
myDB.execSQL("create table appo(Dr Text,time Text, date Text)");
}
#Override
public void onUpgrade(SQLiteDatabase myDB, int oldVersion, int newVersion) {
myDB.execSQL("Drop Table if exists users");
myDB.execSQL("Drop Table if exists appo");
}
public boolean insertData(String name, String username, String email, String PhoneNo, String password){
SQLiteDatabase myDB = this.getWritableDatabase();
ContentValues contentValues = new ContentValues();
contentValues.put(col1,name);
contentValues.put(col2,username);
contentValues.put(col3,email);
contentValues.put(col4,PhoneNo);
contentValues.put(col5,password);
long result = myDB.insert("users",null,contentValues);
return result != -1;
}
public boolean insertData2(String Dr, String time, String date){
SQLiteDatabase myDB = this.getWritableDatabase();
ContentValues contentValues = new ContentValues();
contentValues.put("Dr",Dr);
contentValues.put("time",time);
contentValues.put("date",date);
long result = myDB.insert("appo",null,contentValues);
return result != -1;
}
public boolean checkusername(String username){
SQLiteDatabase myDB = this.getWritableDatabase();
Cursor cursor = myDB.rawQuery("select * from users where username = ?", new String[] {username});
return cursor.getCount() > 0;
}
public boolean checkusernamepassword(String username, String password){
SQLiteDatabase myDB = this.getWritableDatabase();
Cursor cursor = myDB.rawQuery("select * from users where username = ? and password = ?", new String[] {username,password});
return cursor.getCount() > 0;
}
}
Can anyone help me with the code to retrieve and display the records of the appointment for another activity in list view..???

no such table: reward (code 1): , while compiling: INSERT INTO reward(Reward2,Reward1,Reward3) VALUES (?,?,?)

Hello I'm a student and doing my final year project using sql and android studio. I want to create multiple table and I've trying to follow the example but it doesn't work. the error was no table created. Here my coding
DatabaseHelper.java
package com.example.multipletable;
import android.content.ContentValues;
import android.content.Context;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
import android.util.Log;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Locale;
import androidx.annotation.Nullable;
import static android.content.ContentValues.TAG;
public class DatabaseHelper extends SQLiteOpenHelper {
private static final String DATABASE_NAME = "MultipleTable";
private static final int DATABASE_VERSION = 3;
private static final String TABLE_1 = "register";
private static final String TABLE_2 = "activity";
private static final String TABLE_3 = "reward";
String table_1 = "CREATE TABLE "+TABLE_1+" (matricno TEXT PRIMARY KEY, password TEXT, email TEXT)";
String table_2 = "CREATE TABLE "+TABLE_2+" (id INTEGER PRIMARY KEY AUTOINCREMENT, t_question TEXT, date DEFAULT CURRENT_DATE)";
String table_3 = "CREATE TABLE "+TABLE_3+" (_id INTEGER PRIMARY KEY AUTOINCREMENT, badge_green TEXT, badge_purple TEXT, badge_maroon TEXT)";
public DatabaseHelper(#Nullable Context context) {
super(context, DATABASE_NAME, null, DATABASE_VERSION);
}
#Override
public void onCreate(SQLiteDatabase db) {
db.execSQL(table_1);
}
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
Log.d(TAG, "Current version"+db.getVersion());
for (int version=oldVersion+1; version<=newVersion; version++) {
switch (version) {
case 2:
db.execSQL(table_2);
case 3:
db.execSQL(table_3);
}
}
// Log.e("DATABASE VERSION", db.getVersion()+" ");
//
// db.execSQL("DROP TABLE IF EXISTS "+TABLE_1);
// db.execSQL("DROP TABLE IF EXISTS "+TABLE_2);
// db.execSQL("DROP TABLE IF EXISTS "+TABLE_3);
//
// onCreate(db);
}
public boolean insert(String matNo, String pswd, String email) {
SQLiteDatabase db_1 = this.getWritableDatabase();
ContentValues contentValues1 = new ContentValues();
contentValues1.put("MatricNo", matNo);
contentValues1.put("Password", pswd);
contentValues1.put("Email", email);
db_1.insert(TABLE_1, null, contentValues1);
return true;
}
public boolean insert2(String question) {
SQLiteDatabase db_2 = this.getWritableDatabase();
ContentValues contentValues2 = new ContentValues();
contentValues2.put("Question", question);
contentValues2.put("Date", getDate());
db_2.insert(TABLE_2, null, contentValues2);
return true;
}
public boolean insert3(String green, String purple, String maroon) {
SQLiteDatabase db_3 = this.getWritableDatabase();
ContentValues contentValues3 = new ContentValues();
contentValues3.put("Reward1", green);
contentValues3.put("Reward2", purple);
contentValues3.put("Reward3", maroon);
db_3.insert(TABLE_3, null, contentValues3);
return true;
}
private String getDate() {
SimpleDateFormat dateFormat = new SimpleDateFormat(
"dd-MM-yyyy", Locale.getDefault());
Date date = new Date();
return dateFormat.format(date);
}
}
MainActiviti.java
package com.example.multipletable;
import androidx.appcompat.app.AppCompatActivity;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;
public class MainActivity extends AppCompatActivity {
EditText name, pswd, email;
Button btn_1;
DatabaseHelper db;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
name = findViewById(R.id.txt_name);
pswd = findViewById(R.id.txt_password);
email = findViewById(R.id.txt_email);
btn_1 = findViewById(R.id.btn_next_1);
db = new DatabaseHelper(this);
btn_1.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
String person = name.getText().toString();
String pass = pswd.getText().toString();
String mail = email.getText().toString();
Boolean insert = db.insert(person, pass, mail);
if (insert==true) {
Toast.makeText(getApplicationContext(), "Data 1 saved", Toast.LENGTH_SHORT).show();
Intent intent1 = new Intent(MainActivity.this, Activity2.class);
startActivity(intent1);
}
else {
Toast.makeText(getApplicationContext(), "Data 1 error", Toast.LENGTH_SHORT).show();
}
}
});
}
}
Activity2.java
package com.example.multipletable;
import androidx.appcompat.app.AppCompatActivity;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;
public class Activity2 extends AppCompatActivity {
EditText question;
Button btn2;
DatabaseHelper db;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_2);
question = findViewById(R.id.txt_question);
btn2 = findViewById(R.id.btn_next_2);
db = new DatabaseHelper(this);
btn2.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
String ques = question.getText().toString();
Boolean insert2 = db.insert2(ques);
if (insert2==true) {
Toast.makeText(getApplicationContext(), "Data 2 saved", Toast.LENGTH_SHORT).show();
Intent intent2 = new Intent(Activity2.this, Activity3.class);
startActivity(intent2);
}
else {
Toast.makeText(getApplicationContext(), "Data 2 error", Toast.LENGTH_SHORT).show();
}
}
});
}
}
Activity3.java
package com.example.multipletable;
import androidx.appcompat.app.AppCompatActivity;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;
public class Activity3 extends AppCompatActivity {
EditText green, purple, maroon;
Button btn3;
DatabaseHelper db;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_3);
green = findViewById(R.id.txt_green);
purple = findViewById(R.id.txt_purple);
maroon = findViewById(R.id.txt_maroon);
btn3 = findViewById(R.id.btn_next_3);
db = new DatabaseHelper(this);
btn3.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
String grn = green.getText().toString();
String ppl = purple.getText().toString();
String mrn = maroon.getText().toString();
Boolean insert3 = db.insert3(grn, ppl, mrn);
if (insert3==true) {
Toast.makeText(getApplicationContext(), "Data 3 saved", Toast.LENGTH_SHORT).show();
Intent intent3 = new Intent(Activity3.this, FINISH.class);
startActivity(intent3);
}
else {
Toast.makeText(getApplicationContext(), "Data 3 error", Toast.LENGTH_SHORT).show();
}
}
});
}
}
Can you please help me find the solution and tell me what is wrong :(
I am not sure where your error comes from but, I am assuming its on launch or when you insert the data.
I create my SQL table like below.
However, I did encounter a really annoying issue of if I change my table my app would crash as it would not find it. The fix was I needed to uninstall the app on my phone before uploading the application from android studio to my phone. Hope it helps
public class DatabaseHelper extends SQLiteOpenHelper {
public static final String DATABASE_NAME ="TESTING.db";
// Database Version
private static final int DATABASE_VERSION = 1;
public static final String TABLE_1 = "T1";
public static final String TABLE_2 = "T2";
public static final String TABLE_3 = "T3";
public static final String COL1 = "ID";
public static final String COL2 = "D1";
public static final String COL3 = "D2";
public static final String COL4 = "D3";
public static final String COL5 = "D4";
public static final String COL6 = "D5";
public static final String COL7 = "D6";
public static final String COL8 = "time";
public DatabaseHelper(Context context) {
super(context, DATABASE_NAME, null, DATABASE_VERSION);
}
#Override
public void onCreate(SQLiteDatabase db) {
// creating required tables
String Created_TABLE_1= "CREATE TABLE " + TABLE_1 + " (ID INTEGER PRIMARY KEY, " +
"D1 TEXT, D2 TEXT, D3, TEXT, D4 TEXT, D5 TEXT, D6 TEXT, TIME TEXT)";
String Created_TABLE_2= "CREATE TABLE " + TABLE_2 + " (ID INTEGER PRIMARY KEY, " +
"D1 TEXT, D2 TEXT, D3, TEXT, D4 TEXT, D5 TEXT, D6 TEXT, TIME TEXT)";
String Created_TABLE_3= "CREATE TABLE " + TABLE_3 + " (ID INTEGER PRIMARY KEY, " +
"D1 TEXT, D2 TEXT, D3, TEXT, D4 TEXT, D5 TEXT, D6 TEXT, TIME TEXT)";
db.execSQL(Created_TABLE_1);
db.execSQL(Created_TABLE_2);
db.execSQL(Created_TABLE_3);
}
Ps Stay safe all
Thank you Eugene Troyanskii, forpas and Thomas Morris. I've solved the problem. Supposed to be assign with correct name for column according to create table statement at inserting data code, but I write it different.
Again thanks guys!

Unable to delete data from SQLite

I am having issues when trying to clear the entries from a Arraylist in Android studio, not matter what code I try the app either does nothing or as with the code below crashes. I'm pulling my hair out with this as in my mind it should work.
I have also tried (not included in the code):
odb.rawquery(" delete from DATABASE_TABLE") //from memory so may not be 100%
This crashed the app and it would not reload, I'm assuming that it was successful in removing the table and not re-creating it?
It will be running on KitKat
Have I missed anything?
This is the last thing I need to make it work so any help or suggestions would be great!
TIA
Main
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import android.app.Activity;
import android.database.Cursor;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.SimpleAdapter;
public class MainActivity extends Activity {
private ListView list_lv;
private EditText col2_ed;
private Button sub_btn;
Button del_btn;
private DBclass db;
private ArrayList<String> collist_2;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
collist_2 = new ArrayList<String>();
items();
getData();
DeleteData();
}
private void items() {
sub_btn = (Button) findViewById(R.id.submit_btn);
del_btn = (Button) findViewById(R.id.delete_btn);
col2_ed = (EditText) findViewById(R.id.ed2);
list_lv = (ListView) findViewById(R.id.dblist);
sub_btn.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
submitData();
}
});
}
public void DeleteData(){
del_btn.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
db.deleteData();
}
});
}
protected void submitData() {
String b = col2_ed.getText().toString();
db = new DBclass(this);
long num;
db.open();
num = db.insertmaster(b);
db.close();
getData();
}
public void getData() {
collist_2.clear();
db = new DBclass(this);
try {
db.open();
Cursor cur = db.getAllTitles();
while (cur.moveToNext()) {
String valueofcol2 = cur.getString(2);
collist_2.add(valueofcol2);
}
}
finally {
db.close();
}
printList();
setDataIntoList();
}
private void printList() {
for (int i = 0; i < collist_2.size(); i++) {
}
}
private void setDataIntoList() {
// create the list item mapping
String[] from = new String[] { "col_2" };
int[] to = new int[] { R.id.col2tv };
// prepare the list of all records
List<HashMap<String, String>> fillMaps = new ArrayList<HashMap<String, String>>();
for (int i = 0; i < collist_2.size(); i++) {
HashMap<String, String> map = new HashMap<String, String>();
map.put("col_2", collist_2.get(i));
fillMaps.add(map);
}
// fill in the grid_item layout
SimpleAdapter adapter = new SimpleAdapter(this, fillMaps,
R.layout.custom, from, to);
list_lv.setAdapter(adapter);
}
}
DBclass
import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.SQLException;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
import android.util.Log;
public class DBclass {
public String KEY_ROWID = "_id";
public String KEY_COL2 = "col2";
private String DATABASE_NAME = "mydb";
private String DATABASE_TABLE = "mytable";
private int DATABASE_VERSION = 1;
private Context ourContext;
private DbHelper dbh;
private SQLiteDatabase odb;
private String USER_MASTER_CREATE =
"CREATE TABLE IF NOT EXISTS " + DATABASE_TABLE+ "("
+ KEY_ROWID + " INTEGER PRIMARY KEY AUTOINCREMENT," + KEY_COL2 + " VARCHAR(15) )";
private class DbHelper extends SQLiteOpenHelper {
public DbHelper(Context context) {
super(context, DATABASE_NAME, null, DATABASE_VERSION);
}
#Override
public void onCreate(SQLiteDatabase db) {
db.execSQL(USER_MASTER_CREATE);
}
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
// if DATABASE VERSION changes
// Drop old tables and call super.onCreate()999
}
}
public DBclass(Context c) {
ourContext = c;
dbh = new DbHelper(ourContext);
}
public DBclass open() throws SQLException {
odb = dbh.getWritableDatabase();
return this;
}
public void close() {
dbh.close();
}
public long insertmaster(String col2) throws SQLException{
ContentValues IV = new ContentValues();
IV.put(KEY_COL2, col2);
return odb.insert(DATABASE_TABLE, null, IV);
// returns a number >0 if inserting data is successful
}
public void updateRow(long rowID, String col2) {
ContentValues values = new ContentValues();
values.put(KEY_COL2, col2);
odb.update(DATABASE_TABLE, values, KEY_ROWID + "=" + rowID, null);
}
public void deleteData(){
odb.delete(DATABASE_TABLE, null,null);
}
public Cursor getAllTitles() {
// using simple SQL query
return odb.rawQuery("select * from " + DATABASE_TABLE, null);
}
public Cursor getallCols(String id) throws SQLException {
Cursor mCursor = odb.query(DATABASE_TABLE, new String[] { KEY_COL2 }, null, null, null, null, null);
Log.e("getallcols zmv", "opening successfull");
return mCursor;
}
public Cursor getColsById(String id) throws SQLException {
Cursor mCursor = odb.query(DATABASE_TABLE, new String[] { KEY_COL2 }, KEY_ROWID + " = " + id, null, null, null, null);
Log.e("getallcols zmv", "opening successfull");
return mCursor;
}
}
I think you're not opening the database before trying to delete.
public void DeleteData(){
del_btn.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
//Try adding these lines
try {
db = new DBclass(this);
db.open();
db.deleteData();
}catch(Exception e){
e.print
}finally{
db.close();
}
}
});
}
Add this in DBclass will delete all data from the particular table
public void deleteAll(){
SQLiteDatabase db = this.getWritableDatabase();
String deleteStmt="DELETE FROM "+TABLE_NAME;
db.execSQL(deleteStmt);
db.close();
}
Deleting a single row or single item (where item is the model class or you can pass the keyId/primarykey )
// Deleting single Item
public void deleteItem(Item item) {
SQLiteDatabase db = this.getWritableDatabase();
db.delete(TABLE_NAME, KEY_ID + " = ?",
new String[] { String.valueOf(item.getKeyId()) });
db.close();
}
Also please refer the below link :
https://www.androidhive.info/2013/09/android-sqlite-database-with-multiple-tables/

SQLite Foreign Key Constraints cannot be enabled or disabled while there are transactions in progress

I want to have a Sqlite database that somewhat resembles my MySql database I use to store information. In Sqlite foreign keys are disabled by default.
When I try to use the "setForeignKeyConstraintsEnabled()" command I get the following error.
java.lang.IllegalStateException: Foreign Key Constraints cannot be enabled or disabled while there are transactions in progress. Finish all transactions and release all active database connections first.
How do I fix this?
RegisterActivity
package e.adin_pc.spark;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;
import com.android.volley.AuthFailureError;
import com.android.volley.Request;
import com.android.volley.RequestQueue;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.StringRequest;
import com.android.volley.toolbox.Volley;
import java.util.HashMap;
import java.util.Map;
public class Register extends AppCompatActivity {
EditText Username,Password,Email,Birthday;
Button Register;
String insertURL = "http://10.0.2.2/skripte/insert_user.php";
RequestQueue requestQueue;
private DatabaseHandler db;
private static final String TAG = "RegisterActivity";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_register);
Username=findViewById(R.id.UserNameReg_EditText);
Password=findViewById(R.id.PasswordReg_EditText);
Email=findViewById(R.id.EmailReg_EditText);
Birthday=findViewById(R.id.BirthdayReg_EditText);
Register=findViewById(R.id.register_Button);
db=new DatabaseHandler(this);
requestQueue = Volley.newRequestQueue(getApplicationContext());
Register.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
StringRequest stringRequest = new StringRequest(Request.Method.POST,
insertURL, new Response.Listener<String>() {
#Override
public void onResponse(String response) {
Toast.makeText(Register.this,response,Toast.LENGTH_LONG).show();
//Make object
Users user=new Users();
user.setId(Integer.parseInt(
user.setUserName(Username.toString());
user.setPassword(Password.toString());
user.setEmail(Email.toString());
user.setBirthday(Birthday.toString());
user.setIs_Admin(false);
//INSERT IS CALLED HERE
boolean insert = db.InsertUser(user);
Log.i(TAG,"Uspjelo je valjda ",null);
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Toast.makeText(Register.this,error.toString(),Toast.LENGTH_LONG).show();
}
}) {
#Override
protected Map<String, String> getParams() throws AuthFailureError {
Map<String, String> parameters = new HashMap<String, String>();
parameters.put("USERNAME", Username.getText().toString());
parameters.put("PASSWORD", Password.getText().toString());
parameters.put("EMAIL", Email.getText().toString());
parameters.put("BIRTHDAY", Birthday.getText().toString());
return parameters;
}
};
requestQueue.add(stringRequest);
}
});
}
}
DB Handler code
package e.adin_pc.spark;
import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.DatabaseErrorHandler;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
import android.util.Log;
import java.util.ArrayList;
import java.util.List;
/**
* Created by Adin-PC on 3/30/2018.
*/
public class DatabaseHandler extends SQLiteOpenHelper {
private static final String DATABASE_NAME = "Spark.db";
private static final int VERSION = 1;
//Tabela1
private static final String table1_name="Users";
private static final String Users_id = "Users_id";
private static final String user_name = "user_name";
private static final String password = "password";
private static final String email = "email";
private static final String birthday = "birthday";
private static final String is_admin = "is_admin";
//Table 2
private static final String table2_name="Flights";
private static final String Flights_id = "Flights_id";
private static final String start_destination = "start_destination";
private static final String end_destination = "end_destination";
private static final String flight_start_time = "flight_start_time";
private static final String Flight_end_time = "Flight_end_time";
private static final String Price = "Price";
//Table 3
private static final String table3_name="User_flights";
private static final String User_flights_id = "User_flights_id";
private static final String User_fk = "User_fk";
private static final String Flight_fk = "Flight_fk";
public DatabaseHandler(Context context) {
super(context, DATABASE_NAME, null, VERSION);
}
#Override
public void onCreate(SQLiteDatabase db) {
String Tb1Sql="CREATE TABLE "+table1_name+" ("+
Users_id+" integer primary key , "+
user_name+" text not null,"+
password+" text not null,"+
email+" text not null,"+
birthday+" text not null,"+
is_admin+" text not null"+" )";
String Tb2Sql="CREATE TABLE "+table2_name+" ("+
Flights_id+" integer primary key , "+
start_destination+" text not null,"+
end_destination+" text not null,"+
flight_start_time+" text not null,"+
Flight_end_time+" text not null,"+
Price+" text not null"+" )";
String Tb3Sql="CREATE TABLE "+table3_name+" ("+
User_flights_id+" integer primary key , "+
User_fk+" integer not null, "+
"FOREIGN KEY ("+User_fk+") REFERENCES "+table1_name+"("+Users_id+"), "+
Flight_fk+" integer not null, "+
"FOREIGN KEY ("+Flight_fk+") REFERENCES "+table2_name+"("+Flights_id+")"+
" )";
db.setForeignKeyConstraintsEnabled(true); //ERROR IS HERE
//db.execSQL("PRAGMA foreign_keys=ON"); //THIS ALSO DOESNT WORK
db.execSQL(Tb1Sql);
db.execSQL(Tb2Sql);
db.execSQL(Tb3Sql);
}
#Override
public void onOpen(SQLiteDatabase db) {
super.onOpen(db);
}
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
db.execSQL("DROP TABLE IF EXISTS " + table3_name);
db.execSQL("DROP TABLE IF EXISTS " + table1_name);
db.execSQL("DROP TABLE IF EXISTS " + table2_name);
onCreate(db);
}
//*---------------------------USER COMMANDS-------------------------------------------------------
public boolean InsertUser(Users New_User){
SQLiteDatabase db=this.getWritableDatabase();
ContentValues values=new ContentValues();
values.put(Users_id,New_User.getId());
values.put(user_name,New_User.getUserName());
values.put(password,New_User.getPassword());
values.put(email,New_User.getEmail());
values.put(birthday,New_User.getBirthday());
values.put(is_admin,New_User.getIs_Admin());
long result=db.insert(table1_name,null,values);
db.close();
if (result == -1) {
return false;
} else {
return true;
}
}
public Users GetUser(String UserName, String Password){
SQLiteDatabase db=this.getReadableDatabase();
String Query="SELECT * FROM "+ table1_name+" WHERE "+user_name+" = "+UserName+" AND "+
password+" = "+Password;
Cursor c = db.rawQuery(Query, null);
if (c != null)
c.moveToFirst();
Users user= new Users();
user.setId(c.getInt(c.getColumnIndex(Users_id)));
user.setUserName(c.getString(c.getColumnIndex(user_name)));
user.setPassword(c.getString(c.getColumnIndex(password)));
user.setEmail(c.getString(c.getColumnIndex(email)));
user.setBirthday(c.getString(c.getColumnIndex(birthday)));
String IsAdmin=c.getString(c.getColumnIndex(is_admin));
String validation;
if (IsAdmin=="true")
user.setIs_Admin(true);
else
user.setIs_Admin(false);
db.close();
return user;
}
//*---------------------------FLIGTS COMMANDS-------------------------------------------------------
public boolean InsertFlights(Flights New_flight){
SQLiteDatabase db=this.getWritableDatabase();
ContentValues values=new ContentValues();
values.put(start_destination,New_flight.getStart_destination());
values.put(end_destination,New_flight.getEnd_destination());
values.put(flight_start_time,New_flight.getFlight_start_time());
values.put(Flight_end_time,New_flight.getFlight_end_time());
values.put(Price,New_flight.getPrice());
long result=db.insert(table2_name,null,values);
db.close();
if (result == -1) {
return false;
} else {
return true;
}
}
/*
* getting all flights under single user
* */
public List<Flights> getAllUSersFlights(long user_id) {
List<Flights> flights = new ArrayList<Flights>();
String selectQuery = "SELECT * FROM " + table2_name +" INNER JOIN "+ table3_name+" ON "
+ table2_name+"."+Flights_id+" = "+table3_name+"."+Flight_fk+" WHERE "+table3_name+"."+User_fk+"="+user_id;
SQLiteDatabase db = this.getReadableDatabase();
Cursor c = db.rawQuery(selectQuery, null);
// looping through all rows and adding to list
if (c.moveToFirst()) {
do {
Flights td = new Flights();
td.setId(c.getInt((c.getColumnIndex(Flights_id))));
td.setStart_destination(c.getString(c.getColumnIndex(start_destination)));
td.setEnd_destination(c.getString(c.getColumnIndex(end_destination)));
td.setFlight_start_time(c.getString(c.getColumnIndex(flight_start_time)));
td.setFlight_end_time(c.getString(c.getColumnIndex(Flight_end_time)));
td.setPrice(c.getFloat(c.getColumnIndex(Price)));
flights.add(td);
} while (c.moveToNext());
}
db.close();
return flights;
}
//*---------------------------USerFlights COMMANDS-------------------------------------------------------
public boolean InsertUSerFlights(long user_id,long flight_id ){
SQLiteDatabase db=this.getWritableDatabase();
ContentValues values=new ContentValues();
values.put(User_fk, user_id);
values.put(Flight_fk, flight_id);
long result=db.insert(table3_name,null,values);
if (result == -1) {
return false;
} else {
return true;
}
}
}
Use the onConfigure() callback for calling setForeignKeyConstraintsEnabled().
onCreate() runs is executed in a transaction. It is also run only once and not for any later invocation of your app, so it's unsuitable for setting foreign keys pragma.

Cant validate Login on Android app using a SQLite db

I am having a problem validating my login for my android app. I have 2 fields that require user to enter email and password, if both exist in db then they will be taken to mainscreen (log in successful) if incorrect error will appear. I have tried everything but still doesnt work! Please help I have posted my code below.
package com.example.finalproject;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;
public class LoginActivity extends Activity implements OnClickListener{
EditText mEmailAdd;
EditText mPassword;
private SQLiteAdapter mydb = null;
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.login_activity);
//addListenerOnButton();
}
public void onCreateMainscreen(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.screenmain_activity);
Button mNewUser = (Button)findViewById(R.id.btnLogMain);
mNewUser.setOnClickListener(this);
}
public void onClick(View v) {
switch(v.getId()){
case R.id.btnLogMain:
mEmailAdd = (EditText)findViewById(R.id.email);
mPassword = (EditText)findViewById(R.id.password);
String uname = mEmailAdd.getText().toString();
String pass = mPassword.getText().toString();
if(uname.equals("") || uname == null){
Toast.makeText(getApplicationContext(), "email Empty", Toast.LENGTH_SHORT).show();
}else if(pass.equals("") || pass == null){
Toast.makeText(getApplicationContext(), "Password Empty", Toast.LENGTH_SHORT).show();
}else{
boolean validLogin = validateLogin(uname, pass, LoginActivity.this);
if(validLogin){
System.out.println("In Valid");
Intent i = new Intent(LoginActivity.this, MainMenuActivity.class);
startActivity(i);
finish();
}
}
break;
}
}
// #SuppressWarnings("deprecation")
public boolean validateLogin(String uemail, String pass, Context context) {
mydb = new SQLiteAdapter(this);
SQLiteAdapter db = mydb.openToWrite();
//SELECT
String[] columns = {"_id"};
//WHERE clause
String selection = "email=? AND password=?";
//WHERE clause arguments
String[] selectionArgs = {uemail,pass};
Cursor cursor = null;
try{
//SELECT _id FROM login WHERE email=uemail AND password=pass
cursor = db.query(SQLiteAdapter.MYDATABASE_TABLE, columns, selection, selectionArgs, null, null, null);
// startManagingCursor(cursor);
}catch(Exception e){
e.printStackTrace();
}
int numberOfRows = cursor.getCount();
if(numberOfRows <= 0){
Toast.makeText(getApplicationContext(), "Failed..\nTry Again", Toast.LENGTH_SHORT).show();
return false;
}
return true;
}
public void onDestroy(){
super.onDestroy();
mydb.close();
}
}
DATABASE CLASS
package com.example.finalproject;
import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
import android.database.sqlite.SQLiteDatabase.CursorFactory;
public class SQLiteAdapter {
public static final String MYDATABASE_NAME = "MY_PROJECT_DATABASE";
public static final String MYDATABASE_TABLE = "MY_USERS_TABLE";
public static final int MYDATABASE_VERSION = 1;
public static final String KEY_ID = "_id";
public static final String KEY_NAME = "name";
public static final String KEY_EMAIL = "email";
public static final String KEY_PASSWORD = "password";
//create table MY_DATABASE (ID integer primary key, Content text not null);
private static final String SCRIPT_CREATE_DATABASE =
"create table " + MYDATABASE_TABLE + " ("
+ KEY_ID + " integer primary key autoincrement, "
+ KEY_NAME + " text not null, "
+ KEY_EMAIL + " text not null, "
+ KEY_PASSWORD + " text not null);";
private SQLiteHelper sqLiteHelper;
private SQLiteDatabase sqLiteDatabase;
private Context context;
public SQLiteAdapter(Context c){
context = c;
}
public SQLiteAdapter openToRead() throws android.database.SQLException {
sqLiteHelper = new SQLiteHelper(context, MYDATABASE_NAME, null, MYDATABASE_VERSION);
sqLiteDatabase = sqLiteHelper.getReadableDatabase();
return this;
}
public SQLiteAdapter openToWrite() throws android.database.SQLException {
sqLiteHelper = new SQLiteHelper(context, MYDATABASE_NAME, null, MYDATABASE_VERSION);
sqLiteDatabase = sqLiteHelper.getWritableDatabase();
return this;
}
public void close(){
sqLiteHelper.close();
}
public long insert(String name, String email, String password){
ContentValues contentValues = new ContentValues();
contentValues.put(KEY_NAME, name);
contentValues.put(KEY_EMAIL, email);
contentValues.put(KEY_PASSWORD, password);
return sqLiteDatabase.insert(MYDATABASE_TABLE, null, contentValues);
}
public int deleteAll(){
return sqLiteDatabase.delete(MYDATABASE_TABLE, null, null);
}
public Cursor queueAll(){
String[] columns = new String[]{KEY_ID, KEY_NAME, KEY_EMAIL,KEY_PASSWORD};
Cursor cursor = sqLiteDatabase.query(MYDATABASE_TABLE, columns,
null, null, null, null, null);
return cursor;
}
public class SQLiteHelper extends SQLiteOpenHelper {
public SQLiteHelper(Context context, String name,
CursorFactory factory, int version) {
super(context, name, factory, version);
}
#Override
public void onCreate(SQLiteDatabase db) {
// TODO Auto-generated method stub
db.execSQL(SCRIPT_CREATE_DATABASE);
}
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
// TODO Auto-generated method stub
}
}
}
not your error, but change
if(uname.equals("") || uname == null){ // throws nullpointerexception if uname == null
to
if(uname == null || uname.length() == 0 ){ // throws no exception and also checks the " "
Not sure if this was just a copy-paste error but the code as provided not only doesn't compile, but never sets up the click listener for the login button either. Here's what I modified to make it both compile and query the database.
In SQLiteAdapter:
public SQLiteDatabase openToWrite() throws android.database.SQLException {
sqLiteHelper = new SQLiteHelper(context, MYDATABASE_NAME, null,
MYDATABASE_VERSION);
sqLiteDatabase = sqLiteHelper.getWritableDatabase();
return sqLiteDatabase;
}
In LoginActivity:
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.login_activity);
//addListenerOnButton();
Button mNewUser = (Button)findViewById(R.id.btnLogMain);
mNewUser.setOnClickListener(this);
}
public void onCreateMainscreen(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.screenmain_activity);
Button mNewUser = (Button)findViewById(R.id.btnLogMain);
mNewUser.setOnClickListener(this);
}
public boolean validateLogin(String uemail, String pass, Context context) {
mydb = new SQLiteAdapter(this);
SQLiteDatabase db = mydb.openToWrite();
//SELECT
String[] columns = {"_id"};
//WHERE clause
String selection = "email=? AND password=?";
//WHERE clause arguments
String[] selectionArgs = {uemail,pass};
Cursor cursor = null;
try{
//SELECT _id FROM login WHERE email=uemail AND password=pass
cursor = db.query(SQLiteAdapter.MYDATABASE_TABLE, columns, selection, selectionArgs, null, null, null);
// startManagingCursor(cursor);
}catch(Exception e){
e.printStackTrace();
}
int numberOfRows = cursor.getCount();
if(numberOfRows <= 0){
Toast.makeText(getApplicationContext(), "Failed..\nTry Again", Toast.LENGTH_SHORT).show();
return false;
}
return true;
}
Note also that this code will never insert anything into the database, either. I assume this will be done elsewhere. Further there are many naming convention and general good practices being broken here.
A few issues:
Never do database work on the main thread.
Variables prefixed with 'm' indicate they are member variables of the class.
Be sure to use the #Override notation when appropriate.

Categories