Eclipse LogCat Error about "no such table" SQLite - android

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.

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

error while retriving data from the database SQLite in android

my database helper class is
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;
public class DataHandlerDairy {
public static final String DATE = "date";
public static final String DAIRY = "dairy";
private static final String DATA_BASE_NAME = "mydairy";
private static final String TABLE_NAME = "table_dairy";
private static final int DATABASE_VERSION = 1;
private static final String TABLE_CREATE="create table table_dairy (date text primary key," + "dairy text not null);";
DataBaseHelper1 dbhelper1;
Context ct;
SQLiteDatabase db;
public DataHandlerDairy(Context ct)
{
this.ct=ct;
dbhelper1 = new DataBaseHelper1(ct);
}
private static class DataBaseHelper1 extends SQLiteOpenHelper
{
public DataBaseHelper1(Context ct)
{
super(ct,DATA_BASE_NAME,null, DATABASE_VERSION);
}
#Override
public void onCreate(SQLiteDatabase db) {
// TODO Auto-generated method stub
try
{
db.execSQL(TABLE_CREATE);
}
catch(SQLException e)
{
e.printStackTrace();
}
}
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
db.execSQL("DROP TABLE IF EXISTS table_dairy ");
onCreate(db);
}
}
public DataHandlerDairy open()
{
db = dbhelper1.getWritableDatabase();
return this;
}
public void close()
{
dbhelper1.close();
}
public long insertData(String date,String dairy)
{
ContentValues content = new ContentValues();
content.put(DATE, date);
content.put(DAIRY, dairy);
return db.insertOrThrow(TABLE_NAME, null, content);
}
public Cursor returnData(String date1) throws SQLException
{
Cursor c = db.query(true, TABLE_NAME, new String[] { DATE, DAIRY}, DATE + "=" + date1, null, null, null, null, null);
if(c!=null)
{
c.moveToFirst();
}
return c;
}
}
when i try to retrive the data from the database I am getting an error.
I have used the database helper class in the following code.
import android.os.Bundle;
import android.app.Activity;
import android.content.Intent;
import android.database.Cursor;
import android.graphics.Typeface;
import android.view.Menu;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.ImageButton;
import android.widget.TextView;
public class Read_Dairy extends Activity {
String date1;
TextView tv1,tv2;
ImageButton imgb1;
Button bt1;
DataHandlerDairy handler3;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_read__dairy);
tv1=(TextView) findViewById(R.id.readme);
imgb1=(ImageButton) findViewById(R.id.tick);
bt1=(Button) findViewById(R.id.ready);
tv2=(TextView) findViewById(R.id.love);
Bundle bundle = getIntent().getExtras();
date1 = bundle.getString("kanna");
bt1.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
String getdata=" ";
tv2.setText(date1);
String abcd=tv2.getText().toString();
handler3 = new DataHandlerDairy(getBaseContext());
handler3.open();
Cursor c = handler3.returnData(abcd);
if(c.moveToFirst())
{
do
{
getdata=c.getString(1);
}while(c.moveToNext());
}
handler3.close();
if(getdata==null)
{
tv1.setText("no data exists for this date");
}
else
{
tv1.setText(getdata);
}
}
});
imgb1.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
Intent ks = new Intent(Read_Dairy.this,PickYourDate.class);
startActivity(ks);
}
});
Typeface font = Typeface.createFromAsset(getAssets(), "Strato-linked.ttf");
tv1.setTypeface(font);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.activity_read__dairy, menu);
return true;
}
}
I am getting an error while using this and my StackTrace is
FATAL EXCEPTION: main
Process: simple.smile.my_dairy, PID: 4423
android.database.CursorIndexOutOfBoundsException: Index 0 requested, with a size of 0
at android.database.AbstractCursor.checkPosition(AbstractCursor.java:426)
at android.database.AbstractWindowedCursor.checkPosition(AbstractWindowedCursor.java:136)
at android.database.AbstractWindowedCursor.getString(AbstractWindowedCursor.java:50)
at simple.smile.my_dairy.Read_Dairy$1.onClick(Read_Dairy.java:71)
at android.view.View.performClick(View.java:4832)
at android.view.View$PerformClick.run(View.java:19839)
at android.os.Handler.handleCallback(Handler.java:739)
at android.os.Handler.dispatchMessage(Handler.java:95)
at android.os.Looper.loop(Looper.java:211)
at android.app.ActivityThread.main(ActivityThread.java:5315)
at java.lang.reflect.Method.invoke(Native Method)
at java.lang.reflect.Method.invoke(Method.java:372)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:941)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:736)
Please tell me where the error is and how to rectify it.
getdata=c.getString(1) is not a good way. Instead use getdata=c.getString(c.getColumnIndex(DataHandlerDairy.DAIRY))

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)

can i use database demo

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.)

Android Database Help ( How do I add a delete button )

I have been following a datababse tutorial of commonsware which is the LunchList example, however i would love to know how i can add a delete button, so that i could delete a lunch item once its been created.
I have searched around and found this answer but i'm just not sure how to implement it, please could someone show me how
Add a delete() method to the RestaurantHelper class and call it from
an options menu item on the DetailForm activity.
Thanks
Lucy
ResaurantHelper.java
import android.content.Context;
import android.content.ContentValues;
import android.database.Cursor;
import android.database.SQLException;
import android.database.sqlite.SQLiteOpenHelper;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteQueryBuilder;
class RestaurantHelper extends SQLiteOpenHelper {
private static final String DATABASE_NAME="Lunchlist.db";
private static final int SCHEMA_VERSION=1;
public RestaurantHelper(Context context) {
super(context, DATABASE_NAME, null, SCHEMA_VERSION);
}
#Override
public void onCreate(SQLiteDatabase db) {
db.execSQL("CREATE TABLE restaurants (_id INTEGER PRIMARY KEY AUTOINCREMENT, name TEXT, address TEXT, type TEXT, notes TEXT);");
}
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
// no-op, since will not be called until 2nd schema
// version exists
}
public Cursor getAll() {
return(getReadableDatabase()
.rawQuery("SELECT _id, name, address, type, notes FROM restaurants ORDER BY name",
null));
}
public void insert(String name, String address,
String type, String notes) {
ContentValues cv=new ContentValues();
cv.put("name", name);
cv.put("address", address);
cv.put("type", type);
cv.put("notes", notes);
getWritableDatabase().insert("restaurants", "name", cv);
}
public String getName(Cursor c) {
return(c.getString(1));
}
public String getAddress(Cursor c) {
return(c.getString(2));
}
public String getType(Cursor c) {
return(c.getString(3));
}
public String getNotes(Cursor c) {
return(c.getString(4));
}
}
LunchList.java
package apt.tutorial;
import android.app.TabActivity;
import android.content.Context;
import android.database.Cursor;
import android.os.Bundle;
import android.view.View;
import android.view.ViewGroup;
import android.view.LayoutInflater;
import android.widget.AdapterView;
import android.widget.CursorAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.RadioGroup;
import android.widget.TabHost;
import android.widget.TextView;
public class LunchList extends TabActivity {
Cursor model=null;
RestaurantAdapter adapter=null;
EditText name=null;
EditText address=null;
EditText notes=null;
RadioGroup types=null;
RestaurantHelper helper=null;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
helper=new RestaurantHelper(this);
name=(EditText)findViewById(R.id.name);
address=(EditText)findViewById(R.id.addr);
notes=(EditText)findViewById(R.id.notes);
types=(RadioGroup)findViewById(R.id.types);
address.setVisibility(View.GONE);
notes.setVisibility(View.GONE);
Button save=(Button)findViewById(R.id.save);
save.setOnClickListener(onSave);
ListView list=(ListView)findViewById(R.id.restaurants);
model=helper.getAll();
startManagingCursor(model);
adapter=new RestaurantAdapter(model);
list.setAdapter(adapter);
TabHost.TabSpec spec=getTabHost().newTabSpec("tag1");
spec.setContent(R.id.restaurants);
spec.setIndicator("My Reasons", getResources()
.getDrawable(R.drawable.list));
getTabHost().addTab(spec);
spec=getTabHost().newTabSpec("tag2");
spec.setContent(R.id.details);
spec.setIndicator("Add Reason", getResources()
.getDrawable(R.drawable.restaurant));
getTabHost().addTab(spec);
getTabHost().setCurrentTab(0);
list.setOnItemClickListener(onListClick);
}
#Override
public void onDestroy() {
super.onDestroy();
helper.close();
}
private View.OnClickListener onSave=new View.OnClickListener() {
public void onClick(View v) {
String type=null;
switch (types.getCheckedRadioButtonId()) {
case R.id.sit_down:
type="sit_down";
break;
case R.id.take_out:
type="take_out";
break;
case R.id.delivery:
type="delivery";
break;
}
helper.insert(name.getText().toString(),
address.getText().toString(), type,
notes.getText().toString());
model.requery();
}
};
private AdapterView.OnItemClickListener onListClick=new AdapterView.OnItemClickListener() {
public void onItemClick(AdapterView<?> parent,
View view, int position,
long id) {
model.moveToPosition(position);
name.setText(helper.getName(model));
address.setText(helper.getAddress(model));
notes.setText(helper.getNotes(model));
if (helper.getType(model).equals("sit_down")) {
types.check(R.id.sit_down);
}
else if (helper.getType(model).equals("take_out")) {
types.check(R.id.take_out);
}
else {
types.check(R.id.delivery);
}
getTabHost().setCurrentTab(1);
}
};
class RestaurantAdapter extends CursorAdapter {
RestaurantAdapter(Cursor c) {
super(LunchList.this, c);
}
#Override
public void bindView(View row, Context ctxt,
Cursor c) {
RestaurantHolder holder=(RestaurantHolder)row.getTag();
holder.populateFrom(c, helper);
}
#Override
public View newView(Context ctxt, Cursor c,
ViewGroup parent) {
LayoutInflater inflater=getLayoutInflater();
View row=inflater.inflate(R.layout.row, parent, false);
RestaurantHolder holder=new RestaurantHolder(row);
row.setTag(holder);
return(row);
}
}
static class RestaurantHolder {
private TextView name=null;
private TextView address=null;
private ImageView icon=null;
RestaurantHolder(View row) {
name=(TextView)row.findViewById(R.id.title);
address=(TextView)row.findViewById(R.id.address);
icon=(ImageView)row.findViewById(R.id.icon);
}
void populateFrom(Cursor c, RestaurantHelper helper) {
name.setText(helper.getName(c));
address.setText(helper.getAddress(c));
if (helper.getType(c).equals("sit_down")) {
icon.setImageResource(R.drawable.ball_red);
}
else if (helper.getType(c).equals("take_out")) {
icon.setImageResource(R.drawable.ball_yellow);
}
else {
icon.setImageResource(R.drawable.ball_green);
}
}
}
}
Add a new Button (btnDelete) to your layout-xml
mount it in your code using Button btnDel =(Button)findViewById(R.id.btnDelete);
Add a clickListener on it using:
btnDel.setOnClickListener)new OnClickListener()
{
#Override
public void onClick(View v)
{
//add SQL deletion code here
}
});
And final execute the SQL deletion statement in the onClickListener ;)
If you can check a matching ID, this could work
db.execSQL("DELETE FROM restaurants WHERE id = '+" idToDelete "+' ;");
I am fairly certain that you need to carry on with the tutorials. Having watched Commons_Ware (the book's author and extremely active member here) on the site I doubt he will leave you hanging. I am quite certain he teaches the complete CRUD model one step at a time.
As a side note, if you haven't purchased a subscription to his books, I highly recomend it. They are updated frequently to include the latest info.
Rather than using execSQL() for deletion, use following :
To delete entire table:
db.delete(DATABASE_TABLE, null, null);
To delete particular records in a table:
db.delete(DATABASE_TABLE, whereCondition, null);
for eg:
db.delete(restaurants, "id = '"+ IdToBeDeleted +"'", null);

Categories

Resources