can i use database demo - android

Hello people i have been making my app now for 6 month. iv been working on my layout all this time and coding etc.
Now for the Last month iv been trying to make a database. But i just can't get my head round this problem. I have finished the android notepad tutorial and i have downloaded SQLite database browser. and even tho i have a working database from the notepad v3( add & delete data) i just don't know if i can use this database demo in my project.
also i was on some stack overflow page (cant find it now) and someone put a link to a database demo zip file in which i downloaded and when i run it. its just what am after.
hope you guys can help me out and let me know if i can just use this database demo as my own..
Don't get me wrong am not looking for a easy way out of making my own database or learning about it.
There is a lot to learn in the android world. and if i have a working DB which i can use on other project i will learn along the way about coding..
here is the java code of the database demo its a bit heavy pasteing all this so sorry
if you would like to see my XML please just say..
package mina.android.DatabaseDemo;
import android.app.Activity;
import android.app.Dialog;
import android.database.Cursor;
import android.os.Bundle;
import android.text.Spannable;
import android.view.View;
import android.widget.AdapterView;
import android.widget.EditText;
import android.widget.SimpleCursorAdapter;
import android.widget.Spinner;
import android.widget.TextView;
import android.widget.AdapterView.OnItemSelectedListener;
public class AddEmployee extends Activity {
EditText txtName;
EditText txtAge;
TextView txtEmps;
DatabaseHelper dbHelper;
Spinner spinDept;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.addemployee);
txtName=(EditText)findViewById(R.id.txtName);
txtAge=(EditText)findViewById(R.id.txtAge);
txtEmps=(TextView)findViewById(R.id.txtEmps);
spinDept=(Spinner)findViewById(R.id.spinDept);
}
#Override
public void onStart()
{
try
{
super.onStart();
dbHelper=new DatabaseHelper(this);
txtEmps.setText(txtEmps.getText()+String.valueOf(dbHelper.getEmployeeCount()));
Cursor c=dbHelper.getAllDepts();
startManagingCursor(c);
//SimpleCursorAdapter ca=new
SimpleCursorAdapter(this,android.R.layout.simple_spinner_item, c, new String []
{DatabaseHelper.colDeptName}, new int []{android.R.id.text1});
SimpleCursorAdapter ca=new
SimpleCursorAdapter(this,R.layout.deptspinnerrow, c, new String []
{DatabaseHelper.colDeptName,"_id"}, new int []{R.id.txtDeptName});
//ca.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
spinDept.setAdapter(ca);
spinDept.setOnItemSelectedListener(new OnItemSelectedListener() {
public void onItemSelected(AdapterView<?> parent, View
selectedView,
int position, long id) {
// TODO Auto-generated method stub
}
public void onNothingSelected(AdapterView<?> arg0) {
// TODO Auto-generated method stub
}
});
//never close cursor
}
catch(Exception ex)
{
CatchError(ex.toString());
}
}
public void btnAddEmp_Click(View view)
{
boolean ok=true;
try
{
Spannable spn=txtAge.getText();
String name=txtName.getText().toString();
int age=Integer.valueOf(spn.toString());
int deptID=Integer.valueOf((int)spinDept.getSelectedItemId());
Employee emp=new Employee(name,age,deptID);
dbHelper.AddEmployee(emp);
}
catch(Exception ex)
{
ok=false;
CatchError(ex.toString());
}
finally
{
if(ok)
{
//NotifyEmpAdded();
Alerts.ShowEmpAddedAlert(this);
txtEmps.setText("Number of employees
"+String.valueOf(dbHelper.getEmployeeCount()));
}
}
}
void CatchError(String Exception)
{
Dialog diag=new Dialog(this);
diag.setTitle("Add new Employee");
TextView txt=new TextView(this);
txt.setText(Exception);
diag.setContentView(txt);
diag.show();
}
void NotifyEmpAdded()
{
Dialog diag=new Dialog(this);
diag.setTitle("Add new Employee");
TextView txt=new TextView(this);
txt.setText("Employee Added Successfully");
diag.setContentView(txt);
diag.show();
try {
diag.wait(1000);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
CatchError(e.toString());
}
diag.notify();
diag.dismiss();
}
}
package mina.android.DatabaseDemo;
import android.app.AlertDialog;
import android.app.Dialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.DialogInterface.OnClickListener;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.Spinner;
import android.widget.TextView;
public class Alerts {
public static void ShowEmpAddedAlert(Context con)
{
AlertDialog.Builder builder=new AlertDialog.Builder(con);
builder.setTitle("Add new Employee");
builder.setIcon(android.R.drawable.ic_dialog_info);
DialogListner listner=new DialogListner();
builder.setMessage("Employee Added successfully");
builder.setPositiveButton("ok", listner);
AlertDialog diag=builder.create();
diag.show();
}
public static AlertDialog ShowEditDialog(final Context con,final Employee emp)
{
AlertDialog.Builder b=new AlertDialog.Builder(con);
b.setTitle("Employee Details");
LayoutInflater li=LayoutInflater.from(con);
View v=li.inflate(R.layout.editdialog, null);
b.setIcon(android.R.drawable.ic_input_get);
b.setView(v);
final TextView txtName=(TextView)v.findViewById(R.id.txtDelName);
final TextView txtAge=(TextView)v.findViewById(R.id.txtDelAge);
final Spinner spin=(Spinner)v.findViewById(R.id.spinDiagDept);
Utilities.ManageDeptSpinner(con, spin);
for(int i=0;i<spin.getCount();i++)
{
long id=spin.getItemIdAtPosition(i);
if(id==emp.getDept())
{
spin.setSelection(i, true);
break;
}
}
txtName.setText(emp.getName());
txtAge.setText(String.valueOf(emp.getAge()));
b.setPositiveButton("Modify", new OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
// TODO Auto-generated method stub
emp.setName(txtName.getText().toString());
emp.setAge(Integer.valueOf(txtAge.getText().toString()));
emp.setDept((int)spin.getItemIdAtPosition(spin.getSelectedItemPosition()));
try
{
DatabaseHelper db=new DatabaseHelper(con);
db.UpdateEmp(emp);
}
catch(Exception ex)
{
CatchError(con, ex.toString());
}
}
});
b.setNeutralButton("Delete", new OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
// TODO Auto-generated method stub
DatabaseHelper db=new DatabaseHelper(con);
db.DeleteEmp(emp);
}
});
b.setNegativeButton("Cancel", null);
return b.create();
//diag.show();
}
static public void CatchError(Context con, String Exception)
{
Dialog diag=new Dialog(con);
diag.setTitle("Error");
TextView txt=new TextView(con);
txt.setText(Exception);
diag.setContentView(txt);
diag.show();
}
}
package mina.android.DatabaseDemo
import android.app.TabActivity;
import android.content.Intent;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import android.widget.GridView;
import android.widget.TabHost;
import android.widget.TextView;
public class DatabaseDemo extends TabActivity {
DatabaseHelper dbHelper;
GridView grid;
TextView txtTest;
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
SetupTabs();
}
#Override
public boolean onCreateOptionsMenu(Menu menu)
{
menu.add(1, 1, 1, "Add Employee");
return true;
}
public boolean onOptionsItemSelected(MenuItem item)
{
switch (item.getItemId())
{
//Add employee
case 1:
Intent addIntent=new Intent(this,AddEmployee.class);
startActivity(addIntent);
break;
}
super.onOptionsItemSelected(item);
return false;
}
void SetupTabs()
{
TabHost host=getTabHost();
TabHost.TabSpec spec=host.newTabSpec("tag1");
Intent in1=new Intent(this, AddEmployee.class);
spec.setIndicator("Add Employee");
spec.setContent(in1);
TabHost.TabSpec spec2=host.newTabSpec("tag2");
Intent in2=new Intent(this, GridList.class);
spec2.setIndicator("Employees");
spec2.setContent(in2);
host.addTab(spec);
host.addTab(spec2);
}
}
package mina.android.DatabaseDemo;
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 {
static final String dbName="demoDB";
static final String employeeTable="Employees";
static final String colID="EmployeeID";
static final String colName="EmployeeName";
static final String colAge="Age";
static final String colDept="Dept";
static final String deptTable="Dept";
static final String colDeptID="DeptID";
static final String colDeptName="DeptName";
static final String viewEmps="ViewEmps";
public DatabaseHelper(Context context) {
super(context, dbName, null,33);
// TODO Auto-generated constructor stub
}
#Override
public void onCreate(SQLiteDatabase db) {
// TODO Auto-generated method stub
db.execSQL("CREATE TABLE "+deptTable+" ("+colDeptID+ " INTEGER PRIMARY KEY
, "+
colDeptName+ " TEXT)");
db.execSQL("CREATE TABLE "+employeeTable+" ("+colID+" INTEGER PRIMARY KEY
AUTOINCREMENT, "+
colName+" TEXT, "+colAge+" Integer, "+colDept+" INTEGER
NOT NULL ,FOREIGN KEY ("+colDept+") REFERENCES "+deptTable+"
("+colDeptID+"));");
db.execSQL("CREATE TRIGGER fk_empdept_deptid " +
" BEFORE INSERT "+
" ON "+employeeTable+
" FOR EACH ROW BEGIN"+
" SELECT CASE WHEN ((SELECT "+colDeptID+" FROM
"+deptTable+" WHERE "+colDeptID+"=new."+colDept+" ) IS NULL)"+
" THEN RAISE (ABORT,'Foreign Key Violation') END;"+
" END;");
db.execSQL("CREATE VIEW "+viewEmps+
" AS SELECT "+employeeTable+"."+colID+" AS _id,"+
" "+employeeTable+"."+colName+","+
" "+employeeTable+"."+colAge+","+
" "+deptTable+"."+colDeptName+""+
" FROM "+employeeTable+" JOIN "+deptTable+
" ON "+employeeTable+"."+colDept+"
="+deptTable+"."+colDeptID
);
//Inserts pre-defined departments
InsertDepts(db);
}
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
// TODO Auto-generated method stub
db.execSQL("DROP TABLE IF EXISTS "+employeeTable);
db.execSQL("DROP TABLE IF EXISTS "+deptTable);
db.execSQL("DROP TRIGGER IF EXISTS dept_id_trigger");
db.execSQL("DROP TRIGGER IF EXISTS dept_id_trigger22");
db.execSQL("DROP TRIGGER IF EXISTS fk_empdept_deptid");
db.execSQL("DROP VIEW IF EXISTS "+viewEmps);
onCreate(db);
}
void AddEmployee(Employee emp)
{
SQLiteDatabase db= this.getWritableDatabase();
ContentValues cv=new ContentValues();
cv.put(colName, emp.getName());
cv.put(colAge, emp.getAge());
cv.put(colDept, emp.getDept());
//cv.put(colDept,2);
db.insert(employeeTable, colName, cv);
db.close();
}
int getEmployeeCount()
{
SQLiteDatabase db=this.getWritableDatabase();
Cursor cur= db.rawQuery("Select * from "+employeeTable, null);
int x= cur.getCount();
cur.close();
return x;
}
Cursor getAllEmployees()
{
SQLiteDatabase db=this.getWritableDatabase();
//Cursor cur= db.rawQuery("Select "+colID+" as _id , "+colName+",
"+colAge+" from "+employeeTable, new String [] {});
Cursor cur= db.rawQuery("SELECT * FROM "+viewEmps,null);
return cur;
}
Cursor getAllDepts()
{
SQLiteDatabase db=this.getReadableDatabase();
Cursor cur=db.rawQuery("SELECT "+colDeptID+" as _id, "+colDeptName+" from
"+deptTable,new String [] {});
return cur;
}
void InsertDepts(SQLiteDatabase db)
{
ContentValues cv=new ContentValues();
cv.put(colDeptID, 1);
cv.put(colDeptName, "Sales");
db.insert(deptTable, colDeptID, cv);
cv.put(colDeptID, 2);
cv.put(colDeptName, "IT");
db.insert(deptTable, colDeptID, cv);
cv.put(colDeptID, 3);
cv.put(colDeptName, "HR");
db.insert(deptTable, colDeptID, cv);
db.insert(deptTable, colDeptID, cv);
}
public String GetDept(int ID)
{
SQLiteDatabase db=this.getReadableDatabase();
String[] params=new String[]{String.valueOf(ID)};
Cursor c=db.rawQuery("SELECT "+colDeptName+" FROM"+ deptTable+" WHERE
"+colDeptID+"=?",params);
c.moveToFirst();
int index= c.getColumnIndex(colDeptName);
return c.getString(index);
}
public Cursor getEmpByDept(String Dept)
{
SQLiteDatabase db=this.getReadableDatabase();
String [] columns=new String[]{"_id",colName,colAge,colDeptName};
Cursor c=db.query(viewEmps, columns, colDeptName+"=?", new String[]
{Dept}, null, null, null);
return c;
}
public int GetDeptID(String Dept)
{
SQLiteDatabase db=this.getReadableDatabase();
Cursor c=db.query(deptTable, new String[]{colDeptID+" as
_id",colDeptName},colDeptName+"=?", new String[]{Dept}, null, null, null);
//Cursor c=db.rawQuery("SELECT "+colDeptID+" as _id FROM "+deptTable+"
WHERE "+colDeptName+"=?", new String []{Dept});
c.moveToFirst();
return c.getInt(c.getColumnIndex("_id"));
}
public int UpdateEmp(Employee emp)
{
SQLiteDatabase db=this.getWritableDatabase();
ContentValues cv=new ContentValues();
cv.put(colName, emp.getName());
cv.put(colAge, emp.getAge());
cv.put(colDept, emp.getDept());
return db.update(employeeTable, cv, colID+"=?", new String
[]{String.valueOf(emp.getID())});
}
public void DeleteEmp(Employee emp)
{
SQLiteDatabase db=this.getWritableDatabase();
db.delete(employeeTable,colID+"=?", new String []
{String.valueOf(emp.getID())});
db.close();
}
}
package mina.android.DatabaseDemo;
import android.content.DialogInterface;
public class DialogListner implements
android.content.DialogInterface.OnClickListener {
public DialogListner()
{
}
public void onClick(DialogInterface dialog, int which) {
// TODO Auto-generated method stub
}
}
package mina.android.DatabaseDemo;
import android.content.Context;
public class Employee {
int _id;
String _name;
int _age;
int _dept;
public Employee(String Name,int Age,int Dept)
{
this._name=Name;
this._age=Age;
this._dept=Dept;
}
public Employee(String Name,int Age)
{
this._name=Name;
this._age=Age;
}
public int getID()
{
return this._id;
}
public void SetID(int ID)
{
this._id=ID;
}
public String getName()
{
return this._name;
}
public int getAge()
{
return this._age;
}
public void setName(String Name)
{
this._name=Name;
}
public void setAge(int Age)
{
this._age=Age;
}
public void setDept(int Dept)
{
this._dept=Dept;
}
public String getDeptName(Context con, int Dept)
{
return new DatabaseHelper(con).GetDept(Dept);
}
public int getDept()
{
return this._dept;
}
}
package mina.android.DatabaseDemo;
import android.app.Activity;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.DialogInterface.OnDismissListener;
import android.database.Cursor;
import android.database.sqlite.SQLiteCursor;
import android.os.Bundle;
import android.view.View;
import android.widget.AdapterView;
import android.widget.GridView;
import android.widget.SimpleCursorAdapter;
import android.widget.Spinner;
import android.widget.TextView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.AdapterView.OnItemSelectedListener;
public class GridList extends Activity {
DatabaseHelper dbHelper;
static public GridView grid;
TextView txtTest;
Spinner spinDept1;
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.gridview);
grid=(GridView)findViewById(R.id.grid);
txtTest=(TextView)findViewById(R.id.txtTest);
spinDept1=(Spinner)findViewById(R.id.spinDept1);
Utilities.ManageDeptSpinner(this.getParent(),spinDept1);
final DatabaseHelper db=new DatabaseHelper(this);
try
{
http://img856.imageshack.us/img856/446/hoop.png
spinDept1.setOnItemSelectedListener(new OnItemSelectedListener() {
public void onItemSelected(AdapterView<?> arg0, View arg1,
int arg2, long arg3) {
// TODO Auto-generated method stub
LoadGrid();
//sca.notifyDataSetChanged();
}
public void onNothingSelected(AdapterView<?> arg0) {
// TODO Auto-generated method stub
}
});
}
catch(Exception ex)
{
txtTest.setText(ex.toString());
}
try
{
grid.setOnItemClickListener(new OnItemClickListener()
{
public void onItemClick(AdapterView<?> parent, View v, int position,
long id) {
// TODO Auto-generated method stub
try
{
SQLiteCursor
cr=(SQLiteCursor)parent.getItemAtPosition(position);
String
name=cr.getString(cr.getColumnIndex(DatabaseHelper.colName));
int
age=cr.getInt(cr.getColumnIndex(DatabaseHelper.colAge));
String
Dept=cr.getString(cr.getColumnIndex(DatabaseHelper.colDeptName));
Employee emp=new Employee(name, age,db.GetDeptID(Dept));
emp.SetID((int)id);
AlertDialog diag= Alerts.ShowEditDialog(GridList.this,emp);
diag.setOnDismissListener(new OnDismissListener() {
public void onDismiss(DialogInterface dialog) {
// TODO Auto-generated method stub
txtTest.setText("dismissed");
//((SimpleCursorAdapter)grid.getAdapter()).notifyDataSetChanged();
LoadGrid();
}
});
diag.show();
}
catch(Exception ex)
{
Alerts.CatchError(GridList.this, ex.toString());
}
}
}
);
}
catch(Exception ex)
{
}
}
#Override
public void onStart()
{
super.onStart();
//LoadGrid();
}
public void LoadGrid()
{
dbHelper=new DatabaseHelper(this);
try
{
//Cursor c=dbHelper.getAllEmployees();
View v=spinDept1.getSelectedView();
TextView txt=(TextView)v.findViewById(R.id.txtDeptName);
String Dept=String.valueOf(txt.getText());
Cursor c=dbHelper.getEmpByDept(Dept);
startManagingCursor(c);
String [] from=new String
[]{DatabaseHelper.colName,DatabaseHelper.colAge,DatabaseHelper.colDeptName};
int [] to=new int [] {R.id.colName,R.id.colAge,R.id.colDept};
SimpleCursorAdapter sca=new
SimpleCursorAdapter(this,R.layout.gridrow,c,from,to);
grid.setAdapter(sca);
}
catch(Exception ex)
{
AlertDialog.Builder b=new AlertDialog.Builder(this);
b.setMessage(ex.toString());
b.show();
}
}
}
package mina.android.DatabaseDemo;
import android.content.Context;
import android.database.Cursor;
import android.widget.SimpleCursorAdapter;
import android.widget.Spinner;
public class Utilities {
static public void ManageDeptSpinner(Context context,Spinner view)
{
DatabaseHelper dbHelper=new DatabaseHelper(context);
Cursor c=dbHelper.getAllDepts();
//context.startManagingCursor(c);
//SimpleCursorAdapter ca=new
SimpleCursorAdapter(this,android.R.layout.simple_spinner_item, c, new String []
{DatabaseHelper.colDeptName}, new int []{android.R.id.text1});
SimpleCursorAdapter ca=new
SimpleCursorAdapter(context,R.layout.deptspinnerrow,c,
new String [] {DatabaseHelper.colDeptName,"_id"}, new int []{R.id.txtDeptName});
view.setAdapter(ca);
}
}

Most Android demos, including the current version of Notepad, use the Apache License v2.0. This license says you can freely use and redistribute the code, but you must preserve all existing notices and attributions, and clearly acknowledge that you have modified the code. (See paragraph 4 for the exact wording.)

Related

Why my database deletion code did not works

My Database program works so far with submit and show data function. But deletion and modify database function is not working. I have attached the code for EventsDB.java and EventDetail.java and their resource layout file. Basically there is no problem with submit and show data part. i haven done the modify part and deletion part just din work.Please help.
package com.cinrafood.teopeishen.databasedemo;
import android.content.Intent;
import android.database.SQLException;
import android.os.Bundle;
import android.view.View;
import android.widget.EditText;
import android.widget.Toast;
import androidx.appcompat.app.AppCompatActivity;
public class MainActivity extends AppCompatActivity {
EditText etEvent,etEventDetail,etDate;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main_activity);
etEvent=(EditText)findViewById(R.id.etEvent);
etEventDetail= (EditText)findViewById(R.id.etEventDetail);
etDate=(EditText)findViewById(R.id.etDate);
}
public void btnSubmit (View view)
{
try{
String event = etEvent.getText().toString();
String eventDetail = etEventDetail.getText().toString();
String date= etDate.getText().toString();
EventsDB db = new EventsDB(this);
db.open();
db.createEntry(event,eventDetail,date);
db.close();
Toast.makeText(MainActivity.this,"Successfully saved!!",Toast.LENGTH_LONG).show();
etDate.setText("");
etEventDetail.setText("");
etEvent.setText("");
}catch (SQLException e)
{
Toast.makeText(this, e.getMessage(), Toast.LENGTH_SHORT).show();
}catch (Exception e)
{
Toast.makeText(this,"Please fill up all field",Toast.LENGTH_LONG).show();
}
}
public void btnShowEvents (View view)
{
startActivity(new Intent(this,EventData.class));
}
}
package com.cinrafood.teopeishen.databasedemo;
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 java.util.ArrayList;
public class EventsDB
{
public static final String KEY_ROWID ="_id";
public static final String KEY_EVENT="event_name";
public static final String KEY_EVENT_DESCRIPTIOM="event_description";
public static final String KEY_DATE="event_date";
private final String DATABASE_NAME="EventsDB";
private final String DATABASE_TABLE="EventsTable";
private final int DATABASE_VERSION=1;
private DBHelper ourHelper;
private final Context ourContext;
private SQLiteDatabase ourDatabase;
private ArrayList<Event> events;
public EventsDB(Context context)
{
ourContext= context;
}
private class DBHelper extends SQLiteOpenHelper
{
public DBHelper (Context context)
{
super(context,DATABASE_NAME,null,DATABASE_VERSION);
}
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
db.execSQL("DROP TABLE IF EXISTS "+DATABASE_TABLE);
onCreate(db);
}
#Override
public void onCreate(SQLiteDatabase db) {
/*
CREATE TABLE EventsTable (_id INTEGER PRIMARY KEY AUTOINCREMENT,
event_name TEXT NOT NULL,event_description TEXT NOT NULL,
event_date DATE NOT NULL);
*/
String sqlCode="CREATE TABLE "+DATABASE_TABLE+" ("+
KEY_ROWID+" INTEGER PRIMARY KEY AUTOINCREMENT, "+
KEY_EVENT+" TEXT NOT NULL, "+
KEY_EVENT_DESCRIPTIOM+" TEXT NOT NULL, "+
KEY_DATE+" TEXT NOT NULL);";
db.execSQL(sqlCode);
}
}
public EventsDB open() throws SQLException
{
ourHelper = new DBHelper(ourContext);
ourDatabase=ourHelper.getWritableDatabase();
events= new ArrayList<Event>();
return this;
}
public void close()
{
ourHelper.close();
}
public long createEntry(String event_name, String event_description, String event_date)
{
ContentValues cv = new ContentValues();
cv.put(KEY_EVENT,event_name);
cv.put(KEY_EVENT_DESCRIPTIOM,event_description);
cv.put(KEY_DATE,event_date);
return ourDatabase.insert(DATABASE_TABLE,null,cv);
}
public ArrayList<Event> getData()
{
String [] columns = new String[]{KEY_ROWID,KEY_EVENT,KEY_EVENT_DESCRIPTIOM,KEY_DATE};
Cursor c = ourDatabase.query(DATABASE_TABLE,columns,null,null,null,null,null);
int iRowID = c.getColumnIndex(KEY_ROWID);
int iEvent = c.getColumnIndex(KEY_EVENT);
int iEventDescription = c.getColumnIndex(KEY_EVENT_DESCRIPTIOM);
int iDate = c.getColumnIndex(KEY_DATE);
for(c.moveToFirst();!c.isAfterLast();c.moveToNext())
{
Event event = new Event(c.getInt(iRowID),c.getString(iEvent),c.getString(iEventDescription),c.getString(iDate));
events.add(event);
}
return events;
}
public long deleteEntry (String rowID){
return ourDatabase.delete(DATABASE_TABLE,KEY_ROWID+"=?",new String[]{rowID});
}
public long updateEntry(String rowID, String event_name, String event_description, String event_date)
{
ContentValues cv = new ContentValues();
cv.put(KEY_EVENT,event_name);
cv.put(KEY_EVENT_DESCRIPTIOM,event_description);
cv.put(KEY_DATE,event_date);
return ourDatabase.update(DATABASE_TABLE,cv,KEY_ROWID+"=?",new String[]{rowID});
}
}
package com.cinrafood.teopeishen.databasedemo;
import android.content.Intent;
import android.database.SQLException;
import android.os.Bundle;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ListView;
import android.widget.Toast;
import androidx.appcompat.app.AppCompatActivity;
import androidx.appcompat.widget.Toolbar;
public class EventData extends AppCompatActivity {
ListView lvEvents;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_event_data);
Toolbar toolbar = findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
try{
EventsDB db = new EventsDB(this);
db.open();
lvEvents= (ListView)findViewById(R.id.lvEvents);
lvEvents.setAdapter(new CustomAdapter(db.getData(),getApplicationContext()));
db.close();
}catch (SQLException e)
{
Toast.makeText(this, e.getMessage(), Toast.LENGTH_SHORT).show();
}catch(Exception e){
Toast.makeText(this, e.getMessage(),Toast.LENGTH_LONG).show();
}
AdapterView.OnItemLongClickListener click = new AdapterView.OnItemLongClickListener() {
#Override
public boolean onItemLongClick(AdapterView<?> parent, View view, int position, long id) {
Intent intent = new Intent(EventData.this,EventDetail.class);
intent.putExtra("Location",position);
startActivity(intent);
return true;
}
};
lvEvents.setOnItemLongClickListener(click);
}
}
package com.cinrafood.teopeishen.databasedemo;
import android.database.SQLException;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;
import androidx.appcompat.app.AppCompatActivity;
import androidx.appcompat.widget.Toolbar;
import java.util.ArrayList;
public class EventDetail extends AppCompatActivity {
EditText etTitlePage,etEventDetailPage,etDatePage;
Button btnDeleteEvent;
int location;
ArrayList<Event> events;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_event_detail);
Toolbar toolbar = findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
etTitlePage=(EditText) findViewById(R.id.etTitlePage);
etEventDetailPage=(EditText) findViewById(R.id.etEventDetailPage);
etDatePage=(EditText) findViewById(R.id.etDatePage);
btnDeleteEvent=(Button)findViewById(R.id.btnDeleteEvent);
try{
EventsDB db = new EventsDB(this);
db.open();
events=db.getData();
location = getIntent().getIntExtra("Location",0);
etTitlePage.setText(events.get(location).getEvent_name());
etEventDetailPage.setText(events.get(location).getEvent_description());
etDatePage.setText(events.get(location).getEvent_date());
db.close();
}catch (SQLException e)
{
Toast.makeText(this, e.getMessage(), Toast.LENGTH_SHORT).show();
}catch(Exception e){
Toast.makeText(this, e.getMessage(),Toast.LENGTH_LONG).show();
}
btnDeleteEvent.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
try{
EventsDB db = new EventsDB(getApplicationContext());
db.open();
db.deleteEntry((location+1)+"");
db.close();
Toast.makeText(getApplicationContext(),"Successfully deleted!!",Toast.LENGTH_LONG).show();
}catch (SQLException e)
{
Toast.makeText(getApplicationContext(), e.getMessage(), Toast.LENGTH_SHORT).show();
}catch(Exception e){
Toast.makeText(getApplicationContext(), e.getMessage(),Toast.LENGTH_LONG).show();
}
}
});
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
}
}
public Integer deleteContacts (Integer id) {
SQLiteDatabase db = this.getWritableDatabase();
return db.delete("contacts",
"id = ? ",
new String[] { Integer.toString(id) });
}
Actually you have passed position of the item in ListView to delete that item from database which is not correct. You have to pass the rowId of database primary key to complete the delete operation.
AdapterView.OnItemLongClickListener click = new AdapterView.OnItemLongClickListener() {
#Override
public boolean onItemLongClick(AdapterView<?> parent, View view, int position, long id) {
//Retrieve Event from adapter
Event event = lvEvents.getAdapter().getItem(position);
Intent intent = new Intent(EventData.this,EventDetail.class);
intent.putExtra("Location", event.getRowId()); // get rowId from event.
startActivity(intent);
return true;
}
};
And execute delete operation using that rowId
db.deleteEntry(location + "");

Can't delete Database item SQLite Android

I've been going round in circles with this for days and I can't get my head around what's wrong.
With the following code, when you press the "yes" button to delete the item you touched, it shows everything and appears to do everything but the item is not removed from the list.
Activity class:
package com1032.em00224.knit;
import java.util.ArrayList;
import android.os.Bundle;
import android.app.Activity;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.database.Cursor;
import android.view.KeyEvent;
import android.view.View;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ArrayAdapter;
import android.widget.ListView;
import android.widget.Toast;
public class NoteActivity extends Activity {
private ListView list;
DatabaseHandler db;
int id_To_Update = 0;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_note);
db = new DatabaseHandler(this);
ArrayList array_list = db.getAllNotes();
ArrayAdapter arrayAdapter =
new ArrayAdapter(this,android.R.layout.simple_list_item_1, array_list);
//adding it to the list view.
list = (ListView)findViewById(R.id.listView1);
list.setAdapter(arrayAdapter);
list.setOnItemClickListener(new OnItemClickListener(){
#Override
public void onItemClick(AdapterView<?> parent, View arg1, final int position,
long arg3) {
// TODO Auto-generated method stub
AlertDialog.Builder adb = new AlertDialog.Builder(NoteActivity.this);
adb.setTitle("Delete Note?");
adb.setMessage(R.string.deleteNote);
adb.setPositiveButton(R.string.yes, new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
db.deleteNote(position + 1);
arrayAdapter.notifyDataSetChanged();
Toast.makeText(getApplicationContext(), "Note Deleted", Toast.LENGTH_SHORT).show();
Intent intent = new Intent(getApplicationContext(), com1032.em00224.knit.NoteActivity.class);
startActivity(intent);
}
});
adb.setNegativeButton(R.string.no, new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
}
});
adb.show();
}
});
}
And the Database helper:
package com1032.em00224.knit;
import java.util.ArrayList;
import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.DatabaseUtils;
import android.database.sqlite.SQLiteOpenHelper;
import android.database.sqlite.SQLiteDatabase;
public class DatabaseHandler extends SQLiteOpenHelper {
public static final String DATABASE_NAME = "NoteDatabase.db";
public static final String NOTES_TABLE_NAME = "notes";
public static final String NOTES_COLUMN_ID = "id";
public static final String NOTES_COLUMN_NOTE = "note";
public DatabaseHandler(Context context)
{
super(context, DATABASE_NAME , null, 1);
}
#Override
public void onCreate(SQLiteDatabase db) {
// TODO Auto-generated method stub
db.execSQL(
"create table notes " +
"(id integer primary key, note text)"
);
}
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
// TODO Auto-generated method stub
db.execSQL("DROP TABLE IF EXISTS notes");
onCreate(db);
}
public boolean insertNote (String note)
{
SQLiteDatabase db = this.getWritableDatabase();
ContentValues contentValues = new ContentValues();
contentValues.put("note", note);
db.insert("notes", null, contentValues);
return true;
}
public Cursor getData(int id){
SQLiteDatabase db = this.getReadableDatabase();
Cursor res = db.rawQuery( "select * from contacts where id="+id+"", null );
return res;
}
public int numberOfRows(){
SQLiteDatabase db = this.getReadableDatabase();
int numRows = (int) DatabaseUtils.queryNumEntries(db, NOTES_TABLE_NAME);
return numRows;
}
public boolean updateNote (Integer id, String note)
{
SQLiteDatabase db = this.getWritableDatabase();
ContentValues contentValues = new ContentValues();
contentValues.put("note", note);
db.update("notes", contentValues, "id = ? ", new String[] { Integer.toString(id) } );
return true;
}
public Integer deleteNote (Integer id)
{
SQLiteDatabase db = this.getWritableDatabase();
return db.delete("notes",
"id = ? ",
new String[] { Integer.toString(id) });
}
public ArrayList getAllNotes()
{
ArrayList array_list = new ArrayList();
SQLiteDatabase db = this.getReadableDatabase();
Cursor res = db.rawQuery( "select * from notes", null );
res.moveToFirst();
while(res.isAfterLast() == false){
array_list.add(res.getString(res.getColumnIndex(NOTES_COLUMN_NOTE)));
res.moveToNext();
}
return array_list;
}
}
Everything else, such as adding a new item, works as it should.
Edit - It now deletes the one that is selected, but it doesn't always actually delete and there seems to be no pattern - I've added some system.out.printlns to get a clearer picture but it says that it is deleting the right one when it isn't.
In some Projects I faced the same Problem. So there are two possible Solutions. First, after removing Your data from database, also remove item from listview/Adapter and call notifyDataSetChanged:
db.deleteNote(position);
arrayAdapter.remove(arrayAdapter.getItem(itemToRemove));
arrayAdapter.notifyDataSetChanged();
So, my Problem was, that this sometimes doesn´t work, until now, I don´t know what I was doing wrong. Anyway, if this doesn´t work, refresh the whole data after deleting:
private void refreshData(){
ArrayList array_list = db.getAllNotes();
ArrayAdapter arrayAdapter =
new ArrayAdapter(this,android.R.layout.simple_list_item_1, array_list);
list.setAdapter(arrayAdapter);
list.invalidateViews();
}
So this should look somehting like this in Your onClick:
adb.setPositiveButton(R.string.yes, new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
db.deleteNote(position);
refreshData();
Toast.makeText(getApplicationContext(), "Note Deleted", Toast.LENGTH_SHORT).show();
Intent intent = new Intent(getApplicationContext(), com1032.em00224.knit.NoteActivity.class);
startActivity(intent);
}
});
This is just from scratch, I can´t test the code for now because I have no IDE here. So don´t forget to do some Workaround (like opening and closing database etc.).

SQLiteAssetHelper and getWritableDatabase

I'm having have some trouble with my Database activity. I am unable to write to the database and view the database using the following code.
my Database activity:
package com.jacob.eindproject;
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.database.sqlite.SQLiteDatabase.CursorFactory;
import java.sql.*;
import com.readystatesoftware.sqliteasset.SQLiteAssetHelper;
public class Database extends SQLiteAssetHelper {
public static final String KEY_PRODUCT = "Product";
public static final String KEY_EENHEID = "Eenheid";
public static final String KEY_KCAL = "Kcal";
private static final String DATABASE_NAME = "Voedsel";
private static final String DATABASE_TABLE = "Voeding";
private static final int DATABASE_VERSION = 1;
private DbHelper ourHelper;
private final Context ourContext;
private SQLiteDatabase ourDatabase;
private static class DbHelper extends SQLiteAssetHelper{
public DbHelper(Context context) {
super(context, DATABASE_NAME, context.getExternalFilesDir(null).getAbsolutePath(), null, DATABASE_VERSION);
// TODO Auto-generated constructor stub
}
}
#Override
public void onUpgrade(SQLiteDatabase Voedsel, int oldVersion, int newVersion) {
Voedsel.execSQL("DROP TABLE IF EXISTS " + DATABASE_TABLE);
onCreate(Voedsel);
}
public void close(Database database) {
// TODO Auto-generated method stub
}
public Database(Context c){
ourContext = c;
}
public Database open() throws SQLException{
ourHelper = new DbHelper(ourContext);
ourDatabase = ourHelper.getWritableDatabase();
return this;
}
public void close() {
ourHelper.close();
}
public long createEntry(String product, String kcal, String eenheid) {
ContentValues cv = new ContentValues();
cv.put(KEY_PRODUCT, product);
cv.put(KEY_EENHEID, eenheid);
cv.put(KEY_KCAL, kcal);
return ourDatabase.insert(DATABASE_TABLE, null, cv);
}
public String getData() {
// TODO Auto-generated method stub
String[] columns = new String[]{ KEY_PRODUCT, KEY_EENHEID, KEY_KCAL};
Cursor c = ourDatabase.query(DATABASE_TABLE, columns, null, null, null, null, null);
String result = "";
int iRow = c.getColumnIndex(KEY_PRODUCT);
int iName = c.getColumnIndex(KEY_EENHEID);
int iHotness = c.getColumnIndex(KEY_KCAL);
for (c.moveToFirst(); !c.isAfterLast(); c.moveToNext()){
result = result + c.getString(iRow) + " " + c.getString(iName) + " " + c.getString(iHotness) + "\n";
}
return result;
}
}
My SQLView activity:
package com.jacob.eindproject;
import android.app.Activity;
import android.os.Bundle;
import android.widget.TextView;
public class SQLView extends Activity{
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.sqlview);
TextView tv = (TextView) findViewById(R.id.tvSQLinfo);
Database info = new Database(this);
info.open();
String data = info.getData();
info.close();
tv.setText(data);
}
}
SQLite activity:
package com.jacob.eindproject;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.app.Activity;
import android.app.Dialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.view.View.OnClickListener;
public class SQLite extends Activity implements View.OnClickListener {
Button sqlUpdate, sqlView;
EditText sqlVoeding, sqlKcal, sqlEenheid;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.sqllite);
sqlUpdate = (Button) findViewById(R.id.bSQLUpdate);
sqlVoeding = (EditText) findViewById(R.id.etSQLVoeding);
sqlEenheid = (EditText) findViewById(R.id.etSQLEenheid);
sqlKcal = (EditText) findViewById(R.id.etSQLKcal);
sqlView = (Button) findViewById(R.id.bSQLopenView);
sqlView.setOnClickListener((android.view.View.OnClickListener) this);
sqlUpdate.setOnClickListener((android.view.View.OnClickListener) this);
}
public void onClick(View arg0) {
switch (arg0.getId()) {
case R.id.bSQLUpdate:
boolean didItWork = true;
try{
String voeding = sqlVoeding.getText().toString();
String Kcal = sqlKcal.getText().toString();
String eenheid = sqlEenheid.getText().toString();
Database entry = new Database(SQLite.this);
entry.open();
entry.createEntry(voeding, Kcal, eenheid);
entry.close();
}catch (Exception e ){
didItWork = false;
}finally{
if (didItWork){
Dialog d = new Dialog(this);
d.setTitle("Heak Yeay");
TextView tv = new TextView(this);
tv.setText("Succes");
d.setContentView(tv);
d.show();
}
}
break;
case R.id.bSQLopenView:
Intent i = new Intent(this, SQLView.class);
startActivity(i);
}
}
public void onClick(DialogInterface arg0, int arg1) {
// TODO Auto-generated method stub
}
}
I am having my database file(Voedsel.rar), in assets/databases/Voedsel.rar.
To write to your database, try a method like this:
public void insertVoeding(String product, String eenheid, String kcal) {
ourDatabase.execSQL("INSERT INTO Voeding (Product, Eenheid, Kcal) VALUES (?, ?, ?)",
new String[] {product, eenheid, kcal});
}
The question marks are replaced by the values in the string array. Your column names cannot be inserted using the string array, because the execSQL method puts quotation marks around these values. The query will fail if you try.
There are two ways to read from a database (may even be two ways to write to it, too). I personally prefer using raw queries, like this one to get the entire database:
public Cursor getEntireDB() {
return ourDatabase.rawQuery("SELECT * FROM Voeding");
}
You can then use the cursor in a CursorAdapter to create a list.

Eclipse android database : How do i insert a date after inserting a "note"

I am trying to write a Race database where you would enter a race name and a race date, then click on that race name, and edit/delete it or the date. I am having trouble input the date. below is my LogCat error.
What am I doing wrong ?
//LOGCAT
12-08 20:15:35.710: I/Database(1648): sqlite returned: error code = 1, msg = near "FROM": syntax error
12-08 20:15:35.710: E/ERROR(1648): ERROR IN CODE: android.database.sqlite.SQLiteException: near "FROM": syntax error: , while compiling: SELECT _id, note FROM Races, date FROM Races
12-08 20:15:35.721: W/System.err(1648): android.database.sqlite.SQLiteException: near "FROM": syntax error: , while compiling: SELECT _id, note FROM Races, date FROM Races
12-08 20:15:35.730: W/System.err(1648): at android.database.sqlite.SQLiteCompiledSql.native_compile(Native Method)
//View races java code
package com.CIS2818.tritracker;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.database.Cursor;
import android.os.Bundle;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.Button;
import android.widget.CursorAdapter;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.TextView;
public class View_races extends Activity {
NoteAdapter adapter=null;
RaceHelper helper2=null;
Cursor dataset_cursor=null;
EditText editNote2=null;
EditText editNote3=null;
String noteId2=null;
String TAG = "INFORMATION";
#SuppressWarnings("deprecation")
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
try
{
setContentView(R.layout.activity_view_races);
ListView list2=(ListView)findViewById(R.id.list2);
editNote2 = (EditText)findViewById(R.id.myEditText2);
editNote3 = (EditText)findViewById(R.id.myEditText3);
helper2=new RaceHelper(this);
dataset_cursor=helper2.getAll();
startManagingCursor(dataset_cursor);
adapter=new NoteAdapter(dataset_cursor);
list2.setAdapter(adapter);
Button btnSimple2 = (Button) findViewById(R.id.btnSimple2);
btnSimple2.setOnClickListener(onSave);
Button btnDelete2 = (Button) findViewById(R.id.btnDelete2);
btnDelete2.setOnClickListener(onDelete);
list2.setOnItemClickListener(onListClick);
}
catch (Exception e)
{
Log.e("ERROR", "ERROR IN CODE: " + e.toString());
e.printStackTrace();
}
}
#Override
public void onDestroy() {
super.onDestroy();
helper2.close();
}
private View.OnClickListener onSave=new View.OnClickListener() {
#SuppressWarnings("deprecation")
public void onClick(View v) {
Log.i(TAG,"You passed through the save method");
if (noteId2==null) {
helper2.insert(editNote2.getText().toString(),editNote3.getText().toString());
}
else{
helper2.update(noteId2, editNote2.getText().toString(),editNote3.getText().toString());
noteId2=null;
}
dataset_cursor.requery();
editNote2.setText("");
}
};
private View.OnClickListener onDelete=new View.OnClickListener() {
#SuppressWarnings("deprecation")
public void onClick(View v) {
if (noteId2==null) {
return;
}
else{
helper2.delete(noteId2);
noteId2=null;
}
dataset_cursor.requery();
editNote2.setText("");
}
};
private AdapterView.OnItemClickListener onListClick=new AdapterView.OnItemClickListener() {
public void onItemClick(AdapterView<?> parent,
View view, int position,
long id2)
{
noteId2 =String.valueOf(id2);
Cursor c=helper2.getById(noteId2);
c.moveToFirst();
editNote2.setText(helper2.getNote(c));
}
};
class NoteAdapter extends CursorAdapter {
#SuppressWarnings("deprecation")
NoteAdapter(Cursor c) {
super(View_races.this, c);
}
#Override
public void bindView(View row, Context ctxt,Cursor c) {
NoteHolder2 holder=(NoteHolder2)row.getTag();
holder.populateFrom(c, helper2);
}
#Override
public View newView(Context ctxt, Cursor c,ViewGroup parent) {
LayoutInflater inflater=getLayoutInflater();
View row=inflater.inflate(R.layout.row2, parent, false);
NoteHolder2 holder=new NoteHolder2(row);
row.setTag(holder);
return(row);
}
}
static class NoteHolder2 {
private TextView noteText2=null;
NoteHolder2(View row) {
noteText2=(TextView)row.findViewById(R.id.note2);
}
void populateFrom(Cursor c, RaceHelper helper) {
noteText2.setText(helper.getNote(c));
}
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.activity_view_races, menu);
return true;}
//Button Method to return to the main Menu
public void Menu(View v){
Intent intent = new Intent(this, MainMenuActivity.class);
startActivity(intent);
}
//Button Method to go to the Race Activity
public void Races(View v){
Intent intent = new Intent(this, UpComingRaceActivity.class);
startActivity(intent);
}
}
// RaceHelper java code
package com.CIS2818.tritracker;
import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
import android.util.Log;
class RaceHelper extends SQLiteOpenHelper {
private static final String DATABASE_NAME="Races.db";
private static final int SCHEMA_VERSION=2;
String TAG = "INFORMATION";
public RaceHelper(Context context) {
super(context, DATABASE_NAME, null, SCHEMA_VERSION);
}
#Override
public void onCreate(SQLiteDatabase db) {
db.execSQL("CREATE TABLE Races (_id INTEGER PRIMARY KEY AUTOINCREMENT, note TEXT, date TEXT);");
Log.i(TAG, "You are in the creation of db");
}
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
}
public void insert(String note, String date) {
ContentValues cv=new ContentValues();
cv.put("note", note);
getWritableDatabase().insert("Races", "note", cv);
Log.i(TAG, "You have succesfully inserted into the db");
}
public void update(String id, String note, String date) {
ContentValues cv=new ContentValues();
String[] args={id};
cv.put("note", note);
getWritableDatabase().update("Races", cv, "_id=?", args);
}
public void delete(String id) {
getWritableDatabase().delete("Races", "_id=?", new String[] {id});
}
public Cursor getAll() {
return(getReadableDatabase()
.rawQuery("SELECT _id, note FROM Races, date FROM Races",
null));
}
public String getNote(Cursor c) {
return(c.getString(1));
}
public Cursor getById(String id) {
String[] args={id};
return(getReadableDatabase()
.rawQuery("SELECT _id, note FROM Races WHERE _id=?",
args));
}
Change below line
getReadableDatabase().rawQuery("SELECT _id, note FROM Races, date FROM Races",
null)
to
getReadableDatabase().rawQuery("SELECT _id, note, data FROM Races",
null)

Eclipse LogCat Error about "no such table" SQLite

I am trying to write a Race database where you would enter a race name, then click on that race name, and edit/delete it.
So I am getting an error in my logcat (error code=1). It tells me there is no table created so I think I am not calling my variables correctly.
//LogCat
12-08 12:46:21.019: I/INFORMATION(650): You entered the insert method
12-08 12:46:21.019: I/Database(650): sqlite returned: error code = 1, msg = no such table: Note
12-08 12:46:21.062: E/Database(650): Error inserting note=ft
12-08 12:46:21.062: E/Database(650): android.database.sqlite.SQLiteException: no such table: Note: , while compiling: INSERT INTO Note(note) VALUES(?);
12-08 12:46:21.062: E/Database(650): at android.database.sqlite.SQLiteCompiledSql.native_compile(Native Method)
12-08 12:46:21.062: E/Database(650): at android.database.sqlite.SQLiteCompiledSql.compile(SQLiteCompiledSql.java:92)
12-08 12:46:21.062: E/Database(650): at android.database.sqlite.SQLiteCompiledSql.<init>(SQLiteCompiledSql.java:65)
//View races java code
package com.CIS2818.tritracker;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.database.Cursor;
import android.os.Bundle;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.Button;
import android.widget.CursorAdapter;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.TextView;
public class View_races extends Activity {
NoteAdapter adapter=null;
RaceHelper helper2=null;
Cursor dataset_cursor=null;
EditText editNote2=null;
String noteId2=null;
String TAG = "INFORMATION";
#SuppressWarnings("deprecation")
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
try
{
setContentView(R.layout.activity_view_races);
ListView list2=(ListView)findViewById(R.id.list2);
editNote2 = (EditText)findViewById(R.id.myEditText2);
helper2=new RaceHelper(this);
dataset_cursor=helper2.getAll();
startManagingCursor(dataset_cursor);
adapter=new NoteAdapter(dataset_cursor);
list2.setAdapter(adapter);
Button btnSimple2 = (Button) findViewById(R.id.btnSimple2);
btnSimple2.setOnClickListener(onSave);
Button btnDelete2 = (Button) findViewById(R.id.btnDelete2);
btnDelete2.setOnClickListener(onDelete);
list2.setOnItemClickListener(onListClick);
}
catch (Exception e)
{
Log.e("ERROR", "ERROR IN CODE: " + e.toString());
e.printStackTrace();
}
}
#Override
public void onDestroy() {
super.onDestroy();
helper2.close();
}
private View.OnClickListener onSave=new View.OnClickListener() {
#SuppressWarnings("deprecation")
public void onClick(View v) {
Log.i(TAG,"You passed through the save method");
if (noteId2==null) {
helper2.insert(editNote2.getText().toString());
}
else{
helper2.update(noteId2, editNote2.getText().toString());
noteId2=null;
}
dataset_cursor.requery();
editNote2.setText("");
}
};
private View.OnClickListener onDelete=new View.OnClickListener() {
#SuppressWarnings("deprecation")
public void onClick(View v) {
if (noteId2==null) {
return;
}
else{
helper2.delete(noteId2);
noteId2=null;
}
dataset_cursor.requery();
editNote2.setText("");
}
};
private AdapterView.OnItemClickListener onListClick=new AdapterView.OnItemClickListener() {
public void onItemClick(AdapterView<?> parent,
View view, int position,
long id2)
{
noteId2 =String.valueOf(id2);
Cursor c=helper2.getById(noteId2);
c.moveToFirst();
editNote2.setText(helper2.getNote(c));
}
};
class NoteAdapter extends CursorAdapter {
#SuppressWarnings("deprecation")
NoteAdapter(Cursor c) {
super(View_races.this, c);
}
#Override
public void bindView(View row, Context ctxt,Cursor c) {
NoteHolder2 holder=(NoteHolder2)row.getTag();
holder.populateFrom(c, helper2);
}
#Override
public View newView(Context ctxt, Cursor c,ViewGroup parent) {
LayoutInflater inflater=getLayoutInflater();
View row=inflater.inflate(R.layout.row2, parent, false);
NoteHolder2 holder=new NoteHolder2(row);
row.setTag(holder);
return(row);
}
}
static class NoteHolder2 {
private TextView noteText2=null;
NoteHolder2(View row) {
noteText2=(TextView)row.findViewById(R.id.note2);
}
void populateFrom(Cursor c, RaceHelper helper) {
noteText2.setText(helper.getNote(c));
}
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.activity_view_races, menu);
return true;
}
//Button Method to return to the main Menu
public void Menu(View v){
Intent intent = new Intent(this, MainMenuActivity.class);
startActivity(intent);
}
//Button Method to go to the Race Activity
public void Races(View v){
Intent intent = new Intent(this, UpComingRaceActivity.class);
startActivity(intent);
}}
//RaceHelper java code
package com.CIS2818.tritracker;
import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
import android.util.Log;
class RaceHelper extends SQLiteOpenHelper {
private static final String DATABASE_NAME="note2.db";
private static final int SCHEMA_VERSION=1;
String TAG ="INFORMATION";
public RaceHelper(Context context) {
super(context, DATABASE_NAME, null, SCHEMA_VERSION);
}
#Override
public void onCreate(SQLiteDatabase db) {
db.execSQL("CREATE TABLE Note (_id INTEGER PRIMARY KEY AUTOINCREMENT, note TEXT);");
}
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
}
public void insert(String note2) {
Log.i(TAG,"You entered the insert method");
ContentValues cv2=new ContentValues();
cv2.put("note", note2);
getWritableDatabase().insert("Note", "note", cv2);
}
public void update(String id, String note2) {
ContentValues cv2=new ContentValues();
String[] args={id};
cv2.put("note", note2);
getWritableDatabase().update("Note", cv2, "_id=?", args);
}
public void delete(String id2) {
getWritableDatabase().delete("Note", "_id=?", new String[] {id2});
}
public Cursor getAll() {
return(getReadableDatabase()
.rawQuery("SELECT _id, note FROM Notes",
null));
}
public String getNote(Cursor c2) {
return(c2.getString(1));
}
public Cursor getById(String id2) {
String[] args={id2};
return(getReadableDatabase()
.rawQuery("SELECT _id, note FROM Note WHERE _id=?",
args));
}
}
It appears you have changed your SQL schema in your Java code but haven't informed SQLite. In order for your SQLiteOpenHelper class to use the new schema you provided in onCreate(), you need to upgrade your database. This is the most basic approach.
First add some functionality to onUpgrade():
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
db.execSQL("DROP TABLE IF EXISTS Note");
onCreate(db);
}
Now increment SCHEMA_VERSION to trigger an upgrade:
private static final int SCHEMA_VERSION=2;
Understand that SQLiteOpenHelper does not check the code inside onCreate() for you, you must tell SQLite there is a change by incrementing SCHEMA_VERSION.
In your insert method make the second value null. For example getWritableDatabase().insert("Note",null,cv2);
I have the same question as yours.I solved it.At first I rename the table that I create but do nothing with the CREATE_DATABASE order.Then I notice it. Although I corrected the order it does not works.So I add the onUpgrade method, and increment DATABASE_VERSION to a higher number,it works!!!Hope it works also for you.

Categories

Resources