Unable to delete data from SQLite - java

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/

Related

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.

Android Studio project

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/

Adding tables in SQLite android

I was researching on how to add tables in an sqlite database for more information but I can't have a grip on how it was truly done.
I have this code:
package com.example.database;
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 = "SCORING";
public static final String MYDATABASE_TABLE = "SCORING_TABLE";
public static final String MYDATABASE_TABLE1 = "Assessment";
public static final int MYDATABASE_VERSION = 3;
public static final String KEY_ID = "_id";
public static final String KEY_CONTENT1 = "Content1";
public static final String KEY_CONTENT2 = "Content2";
public static final String KEY_CONTENT3 = "Content3";
//create table SCORING (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_CONTENT1 + " text not null, "
+ KEY_CONTENT2 + " text not null, "
+ KEY_CONTENT3 + "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 content1, String content2, String content3){
ContentValues contentValues = new ContentValues();
contentValues.put(KEY_CONTENT1, content1);
contentValues.put(KEY_CONTENT2, content2);
contentValues.put(KEY_CONTENT3, content3);
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_CONTENT1, KEY_CONTENT2, KEY_CONTENT3};
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
// If you need to add a column
if (newVersion > oldVersion) {
db.execSQL("ALTER TABLE SCORING_TABLE ADD COLUMN Content4 TEXT");
}
}
}
}
and for the second one I'm having a hard time inputting data to the second table
package com.example.database;
import com.example.database.R;
import android.app.Activity;
import android.content.Intent;
import android.database.Cursor;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.SimpleCursorAdapter;
import android.widget.TextView;
import android.widget.Toast;
public class AndroidSQLite extends Activity {
EditText inputContent2;
TextView textView1, textView2;
Button buttonAdd, buttonDeleteAll;
private SQLiteAdapter mySQLiteAdapter;
ListView listContent;
SimpleCursorAdapter cursorAdapter;
Cursor cursor;
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
textView1 = (TextView)findViewById(R.id.textView1);
textView2 = (TextView)findViewById(R.id.textView2);
inputContent2 = (EditText)findViewById(R.id.content2);
buttonAdd = (Button)findViewById(R.id.add);
buttonDeleteAll = (Button)findViewById(R.id.deleteall);
listContent = (ListView)findViewById(R.id.contentlist);
mySQLiteAdapter = new SQLiteAdapter(this);
mySQLiteAdapter.openToWrite();
cursor = mySQLiteAdapter.queueAll();
String[] from = new String[]{SQLiteAdapter.KEY_ID, SQLiteAdapter.KEY_CONTENT1, SQLiteAdapter.KEY_CONTENT2, SQLiteAdapter.KEY_CONTENT3};
int[] to = new int[]{R.id.id, R.id.text1, R.id.text2, R.id.text3};
cursorAdapter =
new SimpleCursorAdapter(this, R.layout.row, cursor, from, to);
listContent.setAdapter(cursorAdapter);
buttonAdd.setOnClickListener(buttonAddOnClickListener);
buttonDeleteAll.setOnClickListener(buttonDeleteAllOnClickListener);
}
Button.OnClickListener buttonAddOnClickListener
= new Button.OnClickListener(){
#Override
public void onClick(View arg0) {
// TODO Auto-generated method stub
int a=Integer.parseInt(textView1.getText().toString());
int b=a+2;
String s1 = String.valueOf(b);
textView1.setText(s1);
Toast.makeText(getApplicationContext(), "Wrong",
Toast.LENGTH_SHORT).show();
String data1 = textView1.getText().toString();
String data2 = inputContent2.getText().toString();
String data3 = textView2.getText().toString();
mySQLiteAdapter.insert(data1, data2, data3);
updateList();
}
};
Button.OnClickListener buttonDeleteAllOnClickListener
= new Button.OnClickListener(){
#Override
public void onClick(View arg0) {
// TODO Auto-generated method stub
mySQLiteAdapter.deleteAll();
updateList();
}
};
#Override
protected void onDestroy() {
// TODO Auto-generated method stub
super.onDestroy();
mySQLiteAdapter.close();
}
private void updateList(){
cursor.requery();
}
}
I personally found using ContentProviders to be a clearer and easier to maintain way to manage multiple tables.
There is a nice article here that explains ContentProviders and other ways of dealing with android database/
http://www.vogella.com/articles/AndroidSQLite/article.html#tutorialusecp

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.

My program To_do List doesn't work, because of the SQLite

Can somebody help me I wrote this app, but it doesn't work and I don't find the solution.
1st error:
java.lang.illegalstateexception could not read row 0 col 1 from cursor window. Make sure the cursor is initialized correctly before accessing data from it
2nd error:
android.database.sqlite.SQLite Exception: near "=": syntax error (code 1): while compiling: SELECT ZAHL1 FROM Verlauf WHERE ID =
package com.example.to_doliste2;
import java.util.ArrayList;
import java.util.List;
import android.os.Bundle;
import android.app.Activity;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;
import android.widget.ArrayAdapter;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.Toast;
public class MainActivityT extends Activity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_t);
datasource = new VerlaufDataSource(this);
}
private VerlaufDataSource datasource;
List<Entry> AufgabenListe = new ArrayList<Entry>();
public void VerlaufKlick(View view)
{
try
{
String zahl1;
EditText Feld1 = (EditText)findViewById(R.id.editText1);
if (Feld1.getText().toString().length() == 0)
{
return;
}
zahl1 = (Feld1.getText().toString());
Feld1.setText(String.valueOf(zahl1));
try
{
datasource.open();
datasource.createEntry(zahl1);
datasource.close();
}
catch (Exception ex)
{
Toast.makeText(this,ex.toString(),Toast.LENGTH_LONG).show();
}
AufgabenListe.clear();
try
{
datasource.open();
AufgabenListe = datasource.getAllEntries();
datasource.close();
}
catch (Exception ex)
{
Toast.makeText(this,ex.toString(),Toast.LENGTH_LONG).show();
}
ArrayAdapter<Entry> adapterVerlauf = new ArrayAdapter<Entry>(MainActivityT.this, android.R.layout.simple_list_item_1, AufgabenListe);
ListView lVerlauf = (ListView)findViewById(R.id.listView1);
lVerlauf.setAdapter(adapterVerlauf);
}
catch (Exception ex)
{
Toast.makeText(this,ex.toString(),Toast.LENGTH_LONG).show();
}
}
}
package com.example.to_doliste2;
import android.database.sqlite.SQLiteOpenHelper;
import android.content.Context;
import android.database.sqlite.SQLiteDatabase;
import android.util.Log;
public class MySQLHelper extends SQLiteOpenHelper {
public static final String DATABASE_NAME = "verlaufAufgaben.db";
public static final int DATABASE_VERSION = 1;
private static final String TABLE_CREATE_VERLAUF = ""
+"create table VERLAUF ("
+" ID integer primary key, "
+" Zahl1 int) ";
public MySQLHelper(Context context)
{
super (context, DATABASE_NAME, null, DATABASE_VERSION);
}
#Override
public void onCreate(SQLiteDatabase database)
{
database.execSQL(TABLE_CREATE_VERLAUF);
}
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion)
{
Log.w(MySQLHelper.class.getName(),
"Upgrading database from version " + oldVersion + "to "
+ newVersion + ", which all destroy all old data");
db.execSQL("DROP TABLE IF EXISTS SCANITEM");
onCreate(db);
}
}
package com.example.to_doliste2;
public class Entry {
private int zahl1;
public int getZahl1()
{
return zahl1;
}
public void setZahl1(int zahl1)
{
this.zahl1 = zahl1;
}
#Override
public String toString()
{
return String.format("%d", zahl1);
}
}
package com.example.to_doliste2;
import java.util.ArrayList;
import java.util.List;
import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.SQLException;
import android.database.sqlite.SQLiteDatabase;
public class VerlaufDataSource {
private SQLiteDatabase database;
private MySQLHelper dbHelper;
private String[] allColumns = {"ZAHL1"};
public VerlaufDataSource(Context context)
{
dbHelper = new MySQLHelper(context);
}
public void open() throws SQLException
{
database = dbHelper.getWritableDatabase();
}
public void close()
{
dbHelper.close();
}
public Entry createEntry(String zahl1)
{
ContentValues values = new ContentValues();
values.put("ZAHL1", zahl1);
long insertId = database.insert("Verlauf", null, values);
Cursor cursor = database.query("Verlauf", allColumns, "ID = " + insertId, null, null, null, null);
cursor.moveToFirst();
return cursorToEntry(cursor);
}
protected List<Entry> getAllEntries()
{
List<Entry> EntriesList = new ArrayList<Entry>();
EntriesList = new ArrayList<Entry>();
Cursor cursor = database.query("Verlauf", allColumns, "ID =" , null, null, null, null, null);
cursor.moveToFirst();
if(cursor.getCount() == 0) return EntriesList;
while (cursor.isAfterLast()==false)
{
Entry entry = cursorToEntry(cursor);
EntriesList.add(entry);
cursor.moveToNext();
}
cursor.close();
return EntriesList;
}
private Entry cursorToEntry(Cursor cursor)
{
Entry entry = new Entry();
entry.setZahl1(cursor.getInt(1));
return entry;
}
}
if you are retrieving all columns from database then change your query as:
Cursor cursor = database.query("Verlauf",
allColumns, null, null, null, null, null);
First, change the cursor.getInt(1) inside VerlaufDataSource.cursorToEntry(Cursor) to cursor.getInt(0), because the count starts from 0, and you have queried for only one column (allColumns == { "ZAHL1" }).
Secondly, as ρяσѕρєя K mentioned above, "ID =" is not a correct WHERE-clause in VerlaufDataSource.getAllEntries(). Change it to null if you want all the columns.

Categories