I am building a training log that uses an sqlite database to save what the user inputs. Currently, I only have an add method that appends to the database, but am unsure as to how to create a delete method that removes the row created. The user data is initially created and added in TrainingLogCreate (class), which accesses DBAdapter's (Class) add method. What can I add to my remove method in DBAdapter to be able to remove a user entry?
TrainingLogCreate:
public class TrainingLogCreate extends AppCompatActivity {
EditText nameTxt;
EditText posTxt;
Button savebtn;
Context context = this;
public TrainingLogCreate() {
// Required empty public constructor
}
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.training_log_create);
savebtn = (Button) findViewById(R.id.saveButton);
nameTxt = (EditText) findViewById(R.id.exercizeActivity);
posTxt = (EditText) findViewById(R.id.exercizeDetails);
final DBAdapter db = new DBAdapter(this);
SimpleDateFormat dateFormat = new SimpleDateFormat("MM/dd/yyyy");
String datetime;
try {
Date date = new Date();
datetime = dateFormat.format(date);
} finally {
}
final String dateTxt = datetime;
savebtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
//OPEN
db.openDB();
//INSERT
long result = db.add(nameTxt.getText().toString(), posTxt.getText().toString(), dateTxt.toString());
if (result > 0) {
nameTxt.setText("");
posTxt.setText("");
} else {
Toast.makeText(getApplicationContext(), "Failure", Toast.LENGTH_SHORT).show();
}
//CLOSE DB
db.close();
//Open Fragment
finish();
}
});
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
MenuInflater mif = getMenuInflater();
mif.inflate(R.menu.training_create_menu, menu);
getActionBar().show();
return super.onCreateOptionsMenu(menu);
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// handle item selection
switch (item.getItemId()) {
case R.id.action_save:
//add save functionality
return true;
default:
return super.onOptionsItemSelected(item);
}
}
}
DBAdapter:
public class DBAdapter {
//COLUMNS
static final String ROWID="id";
static final String NAME = "name";
static final String POSITION = "position";
static final String DATE = "date";
//DB PROPERTIES
static final String DBNAME="m_DB";
static final String TBNAME="m_TB";
static final int DBVERSION='1';
static final String CREATE_TB="CREATE TABLE m_TB(id INTEGER PRIMARY KEY AUTOINCREMENT,"
+ "name TEXT NOT NULL,position TEXT NOT NULL,date TEXT NOT NULL);";
final Context c;
SQLiteDatabase db;
DBHelper helper;
public DBAdapter(FragmentActivity ctx) {
// TODO Auto-generated constructor stub
this.c=ctx;
helper=new DBHelper(c);
}
// INNER HELPER DB CLASS
private static class DBHelper extends SQLiteOpenHelper
{
public DBHelper(Context context ) {
super(context, DBNAME, null, DBVERSION);
// TODO Auto-generated constructor stub
}
#Override
public void onCreate(SQLiteDatabase db) {
try
{
db.execSQL(CREATE_TB);
} catch (SQLException e) {
e.printStackTrace();
}
}
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
// TODO Auto-generated method stub
Log.w("DBAdapetr","Upgrading DB");
db.execSQL("DROP TABLE IF EXISTS m_TB");
onCreate(db);
}
}
// OPEN THE DB
public DBAdapter openDB()
{
try
{
db=helper.getWritableDatabase();
}catch(SQLException e)
{
Toast.makeText(c, e.getMessage(), Toast.LENGTH_LONG).show();
}
return this;
}
//CLOSE THE DB
public void close()
{
helper.close();
}
//INSERT INTO TABLE
public long add(String name,String pos, String date)
{
try
{
ContentValues cv=new ContentValues();
cv.put(NAME, name);
cv.put(POSITION, pos);
cv.put(DATE, date);
return db.insert(TBNAME, ROWID, cv);
}catch(SQLException e)
{
e.printStackTrace();
}
return 0;
}
//REMOVE FROM TABLE
public long remove(String name)
{
}
//GET ALL VALUES
public Cursor getAllNames()
{
String[] columns={ROWID,NAME,POSITION,DATE};
return db.query(TBNAME, columns, null, null, null, null, null);
}
}
You can have a delete method like this
public void deleteInterestId(int id) {
SQLiteDatabase db = this.getWritableDatabase();
db.delete(TABLE_TIMEKEEPER, KEY_ID + "=?", new String[]{String.valueOf(id)});
db.close();
}
You have to pass the id which you want to delete. You have to customize this method a bit but it will give you an idea
And the most important thing for delete is that you have to also create a column named id and increase it's value as record are inserted. Because you can't delete on base of id that is created automatically by database
Related
I did have a column named source.I had no ideas where i was wrong.
I constructed table time at onCreate method.
public class DbHelper1 extends SQLiteOpenHelper {
static final String TAG = "DbHelper1";
static final String DB_NAME = "timeline.db";
static final int DB_VERSION = 1;
static final String TABLE = "timeline";
static final String C_ID = BaseColumns._ID;
static final String C_CREATED_AT = "created_at";
static final String C_SOURCE = "source";//C_SOURCE represents source
static final String C_TEXT = "txt";
static final String C_USER = "user";
Context context;
public DbHelper1(Context context) {
super(context, DB_NAME, null, DB_VERSION);
this.context = context;
}
#Override
public void onCreate(SQLiteDatabase db) {
// TODO Auto-generated method stub
StringBuffer buffer = new StringBuffer();
buffer.append("create table " + TABLE + " (");
buffer.append(C_ID + " int primary key ,");
buffer.append(C_CREATED_AT + " int ,");
buffer.append(C_USER + " text ,");
buffer.append(C_TEXT + " text ,");
buffer.append(C_SOURCE+" text ");//here is my column source
buffer.append(")");
String sql=buffer.toString();
db.execSQL(sql);
Log.d(TAG, "onCreate sql :"+sql);
}
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
// TODO Auto-generated method stub
db.execSQL("drop table if exists "+TABLE);
Log.d(TAG, "onUpgrade");
onCreate(db);
}
}
here is my test service:
public class UpdaterService3 extends Service {
private static final String TAG = "UpdaterService3";
static final int DELAY = 3000;
private boolean runFlag = false;
private Updater updater;
private YambaApplication1 yamba;
DbHelper1 dbHelper;
SQLiteDatabase db;
#Override
public IBinder onBind(Intent arg0) {
// TODO Auto-generated method stub
return null;
}
#Override
public void onCreate() {
// TODO Auto-generated method stub
super.onCreate();
yamba = (YambaApplication1) getApplication();
this.updater = new Updater();
dbHelper = new DbHelper1(this);
Log.d(TAG, "onCreate");
}
#Override
public int onStartCommand(Intent intent, int flags, int startId) {
// TODO Auto-generated method stub
super.onStartCommand(intent, flags, startId);
this.runFlag = true;
this.updater.start();
this.yamba.setServiceRunning(true);
Log.d(TAG, "onStarted");
return START_STICKY;
}
#Override
public void onDestroy() {
// TODO Auto-generated method stub
super.onDestroy();
this.runFlag = false;
this.updater.interrupt();
this.updater = null;
this.yamba.setServiceRunning(false);
Log.d(TAG, "onDestroy");
}
private class Updater extends Thread {
public Updater() {
super("UpdaterService-Updater");
}
#Override
public void run() {
// TODO Auto-generated method stub
UpdaterService3 updaterService = UpdaterService3.this;
while (updaterService.runFlag) {
Status status;
Log.d(TAG, "Updater running");
try {
db=dbHelper.getWritableDatabase();
Log.d(TAG, "Updater ran");
status = new Status();
status.createdAt = String.valueOf(System
.currentTimeMillis());
status.id = UUID.randomUUID().toString();
status.source = "hello i'm " + status.id
+ ",nice to see you";
status.text = "wow baby :" + status.id;
status.user = "user:" + status.id;
ContentValues values = new ContentValues();
values.clear();
values.put(DbHelper1.C_ID, status.id);
values.put(DbHelper1.C_CREATED_AT, status.createdAt);
values.put(DbHelper1.C_SOURCE, status.source);
values.put(DbHelper1.C_TEXT, status.text);
values.put(DbHelper1.C_USER, status.user);
db.insertOrThrow(DbHelper1.TABLE, null, values);
Log.d(TAG, String.format("%s:%s", status.user,status.text));
db.close();
Log.d(TAG, "Updater run");
Thread.sleep(DELAY);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
updaterService.runFlag = false;
}
}
}
}
}
here is class status
public class Status {//entity bean
String id;
String createdAt;
String source;
String text;
String user;
}
I was really confused.I was a new coder for android.please help!~
1 DB_VERSION must be named DATABASE_VERSION. It's not an optional constant. If you modify the database structure in time, Android relies on this constant to perform the upgrades.
2 If you changed the database structure (i.e.: added or renamed a column), you must increase the DATABASE_VERSION constant value, in order for the onUpgrade() method to fire.
i wanted to append edit text value to in sqlitedb to the new text on top(index 0) and move the previously inserted data down(start from index 1) while inserting rows...Insert the new row on top and display them in a ListView. my code works for appending rows in the bottom .
help me out..
dbhelper.java
public class DBhelper extends SQLiteOpenHelper {
public static final String DATABASE_NAME = "REGISTRATION_DB";
public static final String TABLE_NAME = "REGISTRATION_TABLE";
public static final int VERSION = 1;
public static final String KEY_ID = "_id";
public static final String NAME = "NAME";
public static final String DB = "create table " + TABLE_NAME + " ("
+ KEY_ID + " integer primary key autoincrement, " + NAME
+ " text not null );";
public DBhelper(Context context, String name,
CursorFactory factory, int version) {
super(context, name, factory, version);
// TODO Auto-generated constructor stub
}
#Override
public void onCreate(SQLiteDatabase db) {
// TODO Auto-generated method stub
db.execSQL(DB);
}
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
// TODO Auto-generated method stub
db.execSQL("DROP TABLE IF EXISTS " + TABLE_NAME);
}
}
dataoperation.java
SQLiteDatabase database_ob;
DBhelper openHelper_ob;
Context context;
public Dataoper(Context c) {
// TODO Auto-generated constructor stub
context=c;
}
public Dataoper opnToRead() {
openHelper_ob = new DBhelper(context,
openHelper_ob.DATABASE_NAME, null, openHelper_ob.VERSION);
database_ob = openHelper_ob.getReadableDatabase();
return this;
}
public Dataoper opnToWrite() {
openHelper_ob = new DBhelper(context,
openHelper_ob.DATABASE_NAME, null, openHelper_ob.VERSION);
database_ob = openHelper_ob.getWritableDatabase();
return this;
}
public void Close() {
database_ob.close();
}
public long insertData(String fname) {
ContentValues contentValues = new ContentValues();
contentValues.put(openHelper_ob.NAME, fname);
opnToWrite();
long val = database_ob.insert(openHelper_ob.TABLE_NAME, null,
contentValues);
Close();
return val;
}
public Cursor readdata() {
String[] cols = { openHelper_ob.KEY_ID, openHelper_ob.NAME };
opnToWrite();
#SuppressWarnings("static-access")
Cursor c = database_ob.query(openHelper_ob.TABLE_NAME, cols, null,
null, null, null, null);
return c;
}
public Cursor queryAll(int nameId) {
String[] cols = { openHelper_ob.KEY_ID, openHelper_ob.NAME};
opnToWrite();
Cursor c = database_ob.query(openHelper_ob.TABLE_NAME, cols,
openHelper_ob.KEY_ID + "=" + nameId, null, null, null, null);
return c;
}
Mainactivity.java
public class MainActivity extends Activity {
ListView lv;
Dataoper adapter_ob;
DBhelper helper_ob;
SQLiteDatabase db_ob;
Button bt;
Cursor cursor;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
lv=(ListView)findViewById(R.id.list);
bt=(Button)findViewById(R.id.bt);
adapter_ob = new Dataoper(this);
String[] from = { DBhelper.NAME };
int[] to = { R.id.name };
cursor = adapter_ob.readdata();
SimpleCursorAdapter cursorAdapter = new SimpleCursorAdapter(this,
R.layout.listitem_row, cursor, from, to);
lv.setAdapter(cursorAdapter);
bt.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
Intent i= new Intent(MainActivity.this, Second.class);
startActivity(i);
}
});
}
}
You can display the values first which is inserted in last by query
select NAME from REGISTRATION_TABLE orderby _id ASEC
while executing this query,you get cursor values.from cursor value,you need to make arraylist and pass that arraylist to Arrayadapter.
Arraylist<String> al=new ArrayList<String>();
cursor cursor=db.rawquery("select NAME from REGISTRATION_TABLE orderby _id ASEC",null);
if(cursor.getcount()!=0)
{
cursor.movetofirst();
do{
al.add(cursor.getstring(0));
}
while(cursor.movetonext());
}
cursor.close();
Arrayadapter adapter=new Arrayadapter(this,R.layout.simple_list_item_1,al);
lv.setadapter(adapter);
I'm Developing an android app in which there are Login activity and a Questionnaire activity contains Questions which as radio Buttons and also a Button(Next).So now I wanted to create a database to store the values of the respective fields. I've typed the code for dataHandler and Login.java now the problem is i wanted to know whether the table has been created and also how to view my table please help me and also please check whether my code is correct.
Thanks in Advance.
Here is code for the DatabaseAdapter.java
public class DatabaseAdapter {
DatabaseHandler dbhandler;
public DatabaseAdapter(Context context){
dbhandler =new DatabaseHandler(context);
}
public long insertData(String name,String desig,String years,String dept)
{
SQLiteDatabase db=dbhandler.getWritableDatabase();
ContentValues content=new ContentValues();
content.put(DatabaseHandler.NAME, name);
content.put(DatabaseHandler.DESIGNATION,desig);
content.put(DatabaseHandler.YEARS, years);
content.put(DatabaseHandler.DEPARTMENT, dept);
long id=db.insertOrThrow(DatabaseHandler.TABLE_NAME, null, content);
return id;
}
static class DatabaseHandler extends SQLiteOpenHelper {
private static final String NAME="name";
private static final String DESIGNATION="desig";
private static final String YEARS="years";
private static final String DEPARTMENT="dept";
private static final String TABLE_NAME="visteon";
private static final String DATA_BASE_NAME="VisteonSurvey";
private static final int DATABASE_VERSION=2;
private static final String CREATE_TABLE="CREATE TABLE "+TABLE_NAME+"("+NAME+" VARCHAR(255),"+DESIGNATION+"text not null,"+YEARS+" text not null,"+DEPARTMENT+" text not null);";
public DatabaseHandler(Context context)
{
super(context,DATA_BASE_NAME,null,DATABASE_VERSION);
}
#Override
public void onCreate(SQLiteDatabase db) {
try{
db.execSQL(CREATE_TABLE);
}
catch(SQLException e)
{
e.printStackTrace();
}
}
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
try {
db.execSQL("DROP TABLE IF EXISTS visteon");
onCreate(db);
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
Here is code for Login.java
public void OnClickListener(View v)
{
name=(EditText)findViewById(R.id.editText1);
years1=(RadioButton)findViewById(R.id.radioButton3);
years2=(RadioButton)findViewById(R.id.radioButton4);
years3=(RadioButton)findViewById(R.id.radioButton5);
manager=(RadioButton)findViewById(R.id.radioButton1);
teamleader=(RadioButton)findViewById(R.id.radioButton2);
rg1=(RadioGroup)findViewById(R.id.Designation);
rg2=(RadioGroup)findViewById(R.id.Years);
dept=(Spinner)findViewById(R.id.spinner1);
proceed = (Button)findViewById(R.id.button1);
proceed.setOnClickListener(new View.OnClickListener()
{
#Override
public void onClick(View v)
{
if (validationSuccess())
{
if(manager.isChecked())
{
Intent managerIntent = new Intent(getApplicationContext(), ManagerQuestionnaire1.class); // <----- START "SEARCH" ACTIVITY
startActivityForResult(managerIntent, 0);
}
else
{
Intent teamleaderIntent = new Intent(getApplicationContext(), TeamleaderQuestionnaire1.class); // <----- START "TYPE ENTRIES OUT" ACTIVITY
startActivityForResult(teamleaderIntent, 0);
}
}
else {
AlertDialog();
}
String user=name.getText().toString();
String designation=rg1.getContext().toString();
String experience=rg2.getContext().toString();
String department=dept.getContext().toString();
long id= DatabaseHandler.insertData (user, designation, experience, department);
Toast.makeText(getBaseContext(),"Form Updated",Toast.LENGTH_LONG).show();
}
});
I am new to Android development. I have a problem in my application. My SQLite database table
is recreating on each system reboot, and all saved contents are wiped out from table. Can anyone please help me to solve this problem?
here is my Database class....
package Nsh.android.sms;
import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteDatabase.CursorFactory;
import android.database.sqlite.SQLiteOpenHelper;
import android.provider.SyncStateContract.Helpers;
public class Database {
public static final String MYDATABASENAME="Mylanguagedbnew.db";
public static final String MYDATABASETABLE="Mylanguagedb_table1";
public static final int MYDATABASEVERSION=1;
public static final String KEY_id="_id";
public static final String KEY_language="languages";
public static final String KEY_description="languagedescription";
private static final String SCRIPT_CREATE_DATABASE="create table if not exists
"+MYDATABASETABLE+" ("+KEY_id+" integer primary key autoincrement, "+KEY_language+"
text not null, "+KEY_description+ " text not null);";
private datahelper sqliteopenhelper;
public static String userselectedlang;
private SQLiteDatabase sqlitedatabase;
private Context context;
public Database(Context c){
System.out.println("DBcontext!!!1111");
context=c;
}
public Database openToread()throws android.database.SQLException{
System.out.println("DBINSERTTTTTTTTT!!!OPENREAD22222");
sqliteopenhelper=new datahelper(context,MYDATABASENAME,null,MYDATABASEVERSION);
System.out.println("DBINSERTTTTTTTTT!!!OPENREAD22222");
sqlitedatabase=sqliteopenhelper.getReadableDatabase();
System.out.println("DBINSERTTTTTTTTT!!!OPENREAD22222");
return this;
}
public Database openTowrite()throws android.database.SQLException{
System.out.println("DBINSERTTTTTTTTT!!!OPENWRITE22222");
sqliteopenhelper=new datahelper(context,MYDATABASENAME,null,MYDATABASEVERSION);
sqlitedatabase=sqliteopenhelper.getWritableDatabase();
return this;
}
public void close(){
sqliteopenhelper.close();
}
public Cursor retriveall(){
System.out.println("RETRIEVE ALL OK!!!!!!!!!");
String[] columns={KEY_id,KEY_language,KEY_description};
Cursor cursor=sqlitedatabase.query(MYDATABASETABLE, columns,null,null,null,null,null);
return cursor;
}
public Cursor retrivelanguages(){
String[] columns={KEY_language};
Cursor c=sqlitedatabase.query(MYDATABASETABLE, columns,null,null,null,null,null);
return c;
}
public Cursor retrieveselectedlanguagedecription(){
userselectedlang=listlang.selectedlanguage;
String query="select languagedescription from Mylanguagedb_table1 where languages
='"+userselectedlang+"';";
Cursor c1=sqlitedatabase.rawQuery(query,null);
return c1;
}
public long insert(String language,String languagedescription){
System.out.println("DBINSERTTTTTTTTT!!!INSERT !!!!!!!!!1111");
ContentValues contentvalues=new ContentValues();
contentvalues.put(KEY_language,language);
contentvalues.put(KEY_description,languagedescription);
return sqlitedatabase.insert(MYDATABASETABLE, null,contentvalues);
}
public int deleteall(){
return sqlitedatabase.delete(MYDATABASETABLE,null,null);
}
/*public int deleterow(){
String selectedrow=listlang.selectedlanguage;
return sqlitedatabase.delete(MYDATABASETABLE,selectedrow, null);
}*/
private static class datahelper extends SQLiteOpenHelper{
public datahelper(Context context, String name, CursorFactory factory,
int version) {
super(context, name, factory, version);
// TODO Auto-generated constructor stub
}
#Override
public void onCreate(SQLiteDatabase db) {
// TODO Auto-generated method stub
db.execSQL(SCRIPT_CREATE_DATABASE);
}
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
// TODO Auto-generated method stub
//db.update(table, values, whereClause, whereArgs)
}
}
}
when app start it will create new db and table if not exist else it will continue with exit db.
put this code in your app's Start-up Activity's onCreate() method to check whether Database is already exist or not.
//this is the name of my database
public static final String DATABASE_NAME = "mydatabase.db";
//this is the complete path of my database stored. you can check in DDMS
public static final String DATABASE_PATH = "/data/data/com.rdc.mydatabase/databases/";
Context context = getBaseContext();
boolean databaseStatus = checkDataBase( DATABASE_PATH,DATABASE_NAME);
//this will check when app start
if (databaseStatus == false) {
DBAdapter database = new DBAdapter(context);
//here you can call your create table method
//database.createLoginTable();
Log.v("Debug", "Login table created.");
}
else{
Log.v("Debug", "Database already exist");
}
//method to check whether db is already exist or not and returns boolean
private boolean checkDataBase(String databasePath, String databaseName) {
SQLiteDatabase checkDB = null;
try {
checkDB = SQLiteDatabase.openDatabase(databasePath + databaseName,
null, SQLiteDatabase.OPEN_READONLY);
checkDB.close();
Log.v("Debug", "Database exist");
return true;
} catch (SQLiteException e) {
Log.v("Debug", "Database not exist");
}
return false;
}
i hope it will help you!!
You can solve this problem by using SharedPreferences in onCreate() method ,you can limit the insertion of the data (if it is fixed data) only when the app first time executed.This will solve the duplication.
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.splash);
SharedPreferences pref = getSharedPreferences(PREFS_NAME1,MODE_PRIVATE);
boolean first1 = pref.getBoolean(PREF_FIRST1, false);
if(first1!=true)
{
getSharedPreferences(PREFS_NAME1,MODE_PRIVATE)
.edit()
.putBoolean(PREF_FIRST1, true)
.commit();
// insert data here or use Background Task to do that
}
}
I am facing some difficulties in inserting the data in sqlite. The application is quiz application, where user need to have a username first (w/out password) then the score can be viewed later on. Before do the quiz user has to create username first (if new user) then choose the username (all the usernames will be listed), so user needs to click the related username. The username (almag table) can be inserted successfully, but not for score table. Two tables are linked with foreign key which are userId. when user finished the quiz and press certain button (menu button), I want the score will be saved automatically, but I am still facing difficulties to do so.. I hope someone can help.
These are some codes of the application.
Database java file
public class DatabaseUsername extends SQLiteOpenHelper {
private static final String DATABASE_NAME="use.db";
private static final int SCHEMA_VERSION=1;
private View _id;
public DatabaseUsername(Context context) {
super(context, DATABASE_NAME, null, SCHEMA_VERSION);
}
#Override
public void onCreate(SQLiteDatabase db) {
db.execSQL("CREATE TABLE almag (_id INTEGER PRIMARY KEY AUTOINCREMENT, nama TEXT, jekel TEXT);");
db.execSQL("CREATE TABLE score (_id INTEGER PRIMARY KEY AUTOINCREMENT, score INTEGER, userId INTEGER NOT NULL, FOREIGN KEY (userId) REFERENCES almag(_id) ON DELETE CASCADE);"); //create table score
db.execSQL("PRAGMA foreign_keys = ON;");
}
#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, nama, jekel FROM almag ORDER BY nama",null));
}
public Cursor getById(String id) {
String[] args={id};
return(getReadableDatabase().rawQuery("SELECT _id, nama, jekel FROM almag WHERE _ID=?",args));
}
public void insert(String nama, String jekel) {
ContentValues cv=new ContentValues();
cv.put("nama", nama);
cv.put("jekel", jekel);
getWritableDatabase().insert("almag", "nama", cv);
}
public void insertScore (int _id, int score) {
ContentValues cv=new ContentValues();
cv.put("_id", _id);
cv.put("score", score);
getWritableDatabase().insert("score", "score", cv);
}
public void setUsername(View _id) {
this._id = _id;
}
public String getNama(Cursor c) {
return(c.getString(1));
}
public String getJekel(Cursor c) {
return(c.getString(2));
}
}
TheEndActivity
public class TheEndActivity extends Activity implements OnClickListener {
DatabaseUsername helper=null;
private int _id;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.theendactivitylayout);
helper=new DatabaseUsername(this);
final SetGame currentGame = ((TheApplication)getApplication()).getCurrentGame();
String result = "Your Score is " + currentGame.getRight() + "/" + currentGame.getNumRounds() + ".. ";
String comment = Mark.getResultComment(currentGame.getRight(), currentGame.getNumRounds(), getDifficultySettings());
TextView results = (TextView)findViewById(R.id.endgameResult);
results.setText(result + comment);
int image = Mark.getResultImage(currentGame.getRight(), currentGame.getNumRounds(), getDifficultySettings());
ImageView resultImage = (ImageView)findViewById(R.id.resultPage);
resultImage.setImageResource(image);
Button finishBtn = (Button) findViewById(R.id.finishBtn);
Button answerBtn = (Button) findViewById(R.id.answerBtn);
finishBtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent i = new Intent(TheEndActivity.this, QuizAppActivity.class);
startActivity(i);
helper.insertScore(_id, currentGame.getRight());
}
});
answerBtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent i = new Intent(TheEndActivity.this, AnsActivity.class);
startActivityForResult(i, AppRule.PLAYBUTTON);
}
});
}
private int getDifficultySettings() {
SharedPreferences settings = getSharedPreferences(AppRule.SETTINGS, 0);
int diff = settings.getInt(AppRule.DIFFICULTY, 2);
return diff;
}
public boolean onKeyDown(int keyCode, KeyEvent event)
{
switch (keyCode)
{
case KeyEvent.KEYCODE_BACK :
return true;
}
return super.onKeyDown(keyCode, event);
}
#Override
public void onClick(View arg0) {
// TODO Auto-generated method stub
}}
UsernameList
public class UsernameList extends ListActivity {
public final static String ID_EXTRA="com.rika.fyp.player";
Cursor model=null;
AlmagAdapter adapter=null;
EditText nama=null;
RadioGroup jekel=null;
DatabaseUsername helper=null;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.usernamelist);
helper=new DatabaseUsername(this);
nama=(EditText)findViewById(R.id.nama);
jekel=(RadioGroup)findViewById(R.id.jekel);
model=helper.getAll();
startManagingCursor(model);
adapter=new AlmagAdapter(model);
setListAdapter(adapter);
}
#Override
public void onDestroy() {
super.onDestroy();
helper.close();
}
#Override
public void onListItemClick(ListView list, View view,int position, long id) {
helper.setUsername(nama);
Intent i=new Intent(UsernameList.this, QuizAppActivity.class);
i.putExtra(ID_EXTRA, String.valueOf(id));
startActivity(i);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
new MenuInflater(this).inflate(R.menu.option, menu);
return(super.onCreateOptionsMenu(menu));
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
if (item.getItemId()==R.id.add) {
startActivity(new Intent(UsernameList.this, UsernameRegister.class));
return(true);
}
return(super.onOptionsItemSelected(item));
}
private View.OnClickListener onSave=new View.OnClickListener() {
public void onClick(View v) {
String type=null;
switch (jekel.getCheckedRadioButtonId()) {
case R.id.pria:
type="Pria";
break;
case R.id.perempuan:
type="Perempuan";
break;
}
helper.insert(nama.getText().toString(), type);
model.requery();
}
};
class AlmagAdapter extends CursorAdapter {
AlmagAdapter(Cursor c) {
super(UsernameList.this, c);
}
#Override
public void bindView(View row, Context ctxt,Cursor c) {
AlmagHolder holder=(AlmagHolder)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.usernamerow, parent, false);
AlmagHolder holder=new AlmagHolder(row);
row.setTag(holder);
return(row);
}
}
static class AlmagHolder {
private TextView nama=null;
private TextView alamat=null;
private ImageView icon=null;
private View row=null;
AlmagHolder(View row) {
this.row=row;
nama=(TextView)row.findViewById(R.id.title);
icon=(ImageView)row.findViewById(R.id.icon);
}
void populateFrom(Cursor c, DatabaseUsername helper) {
nama.setText(helper.getNama(c));
if (helper.getJekel(c).equals("Pria")) {
icon.setImageResource(R.drawable.pria);
}
else if (helper.getJekel(c).equals("Perempuan")) {
icon.setImageResource(R.drawable.perempuan);
}
}
}}
I got these in the logcat
ERROR/Database(319): Error inserting score=20 _id=0
ERROR/Database(319): android.database.sqlite.SQLiteConstraintException: error code 19: constraint failed
Your onCreate() method looks overly complicated. Try this instead:
public void onCreate(SQLiteDatabase db) {
db.execSQL("CREATE TABLE almag (_id INTEGER PRIMARY KEY AUTOINCREMENT, nama TEXT, jekel TEXT);");
db.execSQL("CREATE TABLE score (_id INTEGER PRIMARY KEY AUTOINCREMENT, score INTEGER, userId FOREIGN KEY REFERENCES almag(_id) ON DELETE CASCADE);"); //create table score
}
I can't guarantee it will fix your problem, but simplicity has a way of clearing up things.
Also try changing your insert methods to this:
public void insert(String nama, String jekel) {
ContentValues cv=new ContentValues();
cv.put("nama", nama);
cv.put("jekel", jekel);
getWritableDatabase().insert("almag", null, cv);
}
public void insertScore (int _id, int score) {
ContentValues cv=new ContentValues();
cv.put("_id", _id);
cv.put("score", score);
getWritableDatabase().insert("score", null, cv);
}