I have a program to sum two numbers and save result in SQL then show results in a TextView but I don't know how to make that; help me please.
But this number comes from the user (EditText) or from button ...
must I make a new table for the sum number for example or what .
I watch videos on you tube but I can do it that program.
this my code...
in DataBase activity :
public class DB_sql extends SQLiteOpenHelper {
public static final String name = "data.db";
public static final String TABLE_NAME="mydata";
public static final String KEY_First="first";
public static final String KEY_second="second";
public DB_sql(#Nullable Context context) {
super(context, name, null, 1);
}
#Override
public void onCreate(SQLiteDatabase db) {
db.execSQL("create table TABLE_NAME ( id INTEGER PRIMARY KEY AUTOINCREMENT, KEY_First INTEGER, KEY_second INTEGER)");
}
#Override
public void onUpgrade(SQLiteDatabase db, int i, int i1) {
db.execSQL("DROP TABLE IF EXISTS TABLE_NAME");
onCreate(db);
}
public boolean insertdata (int first,int second){
SQLiteDatabase db = this.getWritableDatabase();
ContentValues numbers = new ContentValues();
numbers.put("first",first);
numbers.put("second",second);
long result = db.insert(TABLE_NAME,null,numbers);
if (result == -1)
return false;
else
return true;
}
in result activity:
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_result);
result = (TextView)findViewById(R.id.result);
int first = getIntent().getIntExtra("number1",0);
int second = getIntent().getIntExtra("number2",0);
Boolean dataSQL = db_sql.insertdata(first,second);
if (dataSQL == true){
Toast.makeText(this,"data inserted",Toast.LENGTH_SHORT).show();
}else {
Toast.makeText(this,"data not inserted",Toast.LENGTH_SHORT).show();
}
in MainActivity:
public class MainActivity extends AppCompatActivity {
// DB_sql db_sql = new DB_sql(this);
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
public void second(View view) {
Intent sec = new Intent(this,result.class);
sec.putExtra("number2",40);
startActivity(sec);
}
public void first(View view) {
Intent fir=new Intent(this,result.class);
fir.putExtra("number1",85);
startActivity(fir);
}
}
Related
I tried to create a database and create one table in it. The database is being created but not the table.it doesn't show any error and also am not able to insert the value into it.I want to create a table and insert the data recieved from the user but the data is not able to add to database, neither it shows any errors.The code is as follows:
public DataBaseHelper(Context context) {
super(context, DATABASE_NAME, null, version);
}
#Override
public void onCreate(SQLiteDatabase db) {
String q = "CREATE TABLE IF NOT EXISTS " + TABLE_NAMETRY + "(" +
COL_ID + " INTEGER PRIMARY KEY, " + COL_NAME + " TEXT, " + COL_PHONE + " TEXT " + ")";`enter code here`
db.execSQL(q);
}
#Override
public void onUpgrade(SQLiteDatabase db, int i, int i1) {
db.execSQL("DROP table if exist "+TABLE_NAMETRY);
onCreate(db);
}
public boolean insertData(String name,String no)
{
SQLiteDatabase db = this.getWritableDatabase();
ContentValues contentvalue = new ContentValues();
contentvalue.put(COL_NAME,name);
contentvalue.put(COL_PHONE,no);
long result = db.insert(TABLE_NAMETRY,null,contentvalue);
if(result==-1)
return false;
else
return true;
}
public class MainActivity extends AppCompatActivity {
DataBaseHelper mydb;
EditText name,no;
Button b1;
TextView t1;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mydb=new DataBaseHelper(this);
name=(EditText)findViewById(R.id.name);
no=(EditText)findViewById(R.id.no);
t1=(TextView)findViewById(R.id.t1);
b1=(Button)findViewById(R.id.b1);
b1.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Toast.makeText(MainActivity.this, "Adding Data", Toast.LENGTH_SHORT).show();
AddData();
}
});
}
public void AddData()
{
boolean check= mydb.insertData(name.getText().toString(),no.getText().toString());
if(check==true)
t1.setText("data submitted");
else
t1.setText("data not submitted");
}
}
Most probably the helper is creating the table (onCreate) and then delete it (onUpgrade).
Here how I create my helper, take notice of the databaseVersion, as it is important when the (onUpgrade) is executed
public class DatabaseOpenHelper extends SQLiteOpenHelper {
private final static String databaseName = "Your_DB_Name";
private final static int databaseVersion = 13;
DatabaseOpenHelper(Context context) {
super(context, databaseName, null, databaseVersion);
}
#Override
public void onCreate(SQLiteDatabase db) { // Do Create Your Table Here }
#Override
public void onUpgrade(SQLiteDatabase db, int Old_Version, int New_Version) { //Delete Your tables here if they exists}
My table is not getting created in Sqlite (Toast for dataNotInserted).Code snippet below...
EXCEPTION
android.database.sqlite.SQLiteException: no such table: PETROL.DB (code 1): , while compiling: INSERT INTO PETROL.DB(AMOUNT) VALUES (?)
Activity2.java
public class Activity2 extends AppCompatActivity {
EditText ET1;
Button B1;
Button Bview;
DatabaseHelper myDb;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_2);
myDb = new DatabaseHelper(this);
ET1 = findViewById(R.id.editText_amount);
B1 = findViewById(R.id.button_add);
Bview = findViewById(R.id.button_view);
AddData();
}
public void AddData() {
B1.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
boolean isInserted = myDb.insertData(Integer.parseInt(ET1.getText().toString()));
if (isInserted == true) {
Toast.makeText(Activity2.this, "DataInserted", Toast.LENGTH_LONG).show();
} else
Toast.makeText(Activity2.this, "DataNotInserted", Toast.LENGTH_LONG).show();
}
}
);
}
}
DatabaseHelper.java
public class DatabaseHelper extends SQLiteOpenHelper {
public static final String DATABASE_NAME="PETROL.DB";
public static final String TABLE_NAME="PETROL_TABLE";
public static final String COL_1="ID";
public static final String COL_2="AMOUNT";
public DatabaseHelper(Context context)
{
super(context,DATABASE_NAME,null,1);
}
#Override
public void onCreate(SQLiteDatabase sqLiteDatabase) {
sqLiteDatabase.execSQL( "CREATE TABLE " + TABLE_NAME + "(" + COL_1 + " INTEGER PRIMARY KEY AUTOINCREMENT," + COL_2 + " INTEGER );");
Log.d("data","ghgc");
}
public boolean insertData(int data)
{
SQLiteDatabase sqLiteDatabase=this.getWritableDatabase();
ContentValues contextValues=new ContentValues();
contextValues.put("AMOUNT",data);
Log.d("insertData",Integer.toString(data));
long result= sqLiteDatabase.insert(DATABASE_NAME,null,contextValues);
if(result==-1)
return false;//to check if data is inserted
else
return true;
//sqLiteDatabase.close();
}
}
onUpgrade not mentioned since i'm still working on version 1
Your issue is as per the message and is caused as your are passing the Database name PETROL.DB to the insert method instead of passing the table name. As per the method's signature :-
long insert(String table, String nullColumnHack, ContentValues values)
Convenience method for inserting a row into the database. SQLiteDatabase - insert
As such change :-
long result= sqLiteDatabase.insert(DATABASE_NAME,null,contextValues);
to :-
long result= sqLiteDatabase.insert(TABLE_NAME,null,contextValues);
This question already has answers here:
Unfortunately MyApp has stopped. How can I solve this?
(23 answers)
Closed 5 years ago.
I am new to Android SQLite database & while executing this.getWritableDatabase() my app stops. Is there any solution to this problem? My database is about getting students' information and saving their marks in the database.
public class DatabaseHelper extends SQLiteOpenHelper {
public static final String DATABASE_NAME="Dictionary.db";
public static final String TABLE_NAME="Dictionary_data";
public static final String COL_1="ID";
public static final String COL_2="Name";
public static final String COL_3="SURNAME";
public static final String COL_4="MARKS";
public DatabaseHelper(Context context) {
super(context,DATABASE_NAME,null,1);
}
#Override
public void onCreate(SQLiteDatabase db) {
db.execSQL("CREATE TABLE"+ TABLE_NAME+ "(ID INTEGER PRIMARY KEY AUTO INCREMENT,NAME TEXT,SURENAME TEXT,MARKS INTEGER)");
}
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
db.execSQL("DROP TABLE IF EXISTS"+TABLE_NAME);
onCreate(db);
}
public boolean insert_data(String name,String surname,String marks) {
SQLiteDatabase db = this.getWritableDatabase();
ContentValues contentValues= new ContentValues();
contentValues.put(COL_2,name);
contentValues.put(COL_3,surname);
contentValues.put(COL_4,marks);
long result = db.insert(TABLE_NAME,null,contentValues);
if(result==-1)
return false;
else
return true;
}
}
And my mainActivity class:
public class MainActivity extends AppCompatActivity {
DatabaseHelper myDB;
EditText editName,editSurname,editMark;
Button btn_add_data;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
myDB = new DatabaseHelper(this.getApplicationContext());
editName = (EditText)findViewById(R.id.namespace);
editSurname = (EditText)findViewById(R.id.surnamespace);
editMark = (EditText)findViewById(R.id.markspace);
btn_add_data = (Button)findViewById(R.id.add_button);
addData();
}
public void addData(){
btn_add_data.setOnClickListener(
new View.OnClickListener() {
#Override
public void onClick(View v) {
boolean id_inserted = myDB.insert_data(editName.getText().toString(),editSurname.getText().toString(),editMark.getText().toString());
if(id_inserted)
Toast.makeText(MainActivity.this,"Data inserted",Toast.LENGTH_LONG).show();
else
Toast.makeText(MainActivity.this,"Data not inserted",Toast.LENGTH_LONG).show();
}
}
);
}
}
there is error in create table
db.execSQL("CREATE TABLE"+ TABLE_NAME+ "(ID INTEGER PRIMARY KEY AUTO INCREMENT,NAME TEXT,SURENAME TEXT,MARKS INTEGER)");
please add space after TABLE
db.execSQL("CREATE TABLE "+ TABLE_NAME+ " (ID INTEGER PRIMARY KEY AUTO INCREMENT,NAME TEXT,SURENAME TEXT,MARKS INTEGER)");
also add log cat for more details,i am not able to comment as it's my new account.
I'm very new at android programming and this is my first question on stack overflow ever. I am having trouble understanding where i have gone wrong in my code implementation. I'm trying to store data in a database and then extract it into an arraylist.
This is the class where i add data into the database in the button onclicklistener:
public class KarmaDescription extends AppCompatActivity {
Button button;
TasksDBHandler dbHandler;
int tId = 1;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_karma_desc2min);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
getSupportActionBar().setHomeButtonEnabled(true);
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
getSupportActionBar().setTitle("Overview");
button = (Button) findViewById(R.id.button);
button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
MyTasksGS myTask = new MyTasksGS(tId, "New Task Title", 2);
dbHandler.addTask(myTask);
Toast.makeText(KarmaDescription.this, "Task Added", Toast.LENGTH_SHORT).show();
}
});
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
int id = item.getItemId();
if (id == android.R.id.home) {
onBackPressed();
}
return super.onOptionsItemSelected(item);
}
}
This is the class which manages the database:
public class TasksDBHandler extends SQLiteOpenHelper {
private static final int DATABASE_VERSION = 1;
private static final String DATABASE_NAME = "tasks.db";
public static final String TABLE_TASKS = "tasks";
public static final String COLUMN_ID = "id";
public static final String COLUMN_TASKNAME = "taskname";
public static final String COLUMN_DAYSLEFT = "daysleft";
public TasksDBHandler(Context context, String name, SQLiteDatabase.CursorFactory factory, int version) {
super(context, DATABASE_NAME, factory, DATABASE_VERSION);
}
#Override
public void onCreate(SQLiteDatabase db) {
String query = "CREATE TABLE " + TABLE_TASKS + "(" +
COLUMN_ID + " INTEGER PRIMARY KEY," +
COLUMN_TASKNAME + " TEXT," +
COLUMN_DAYSLEFT + " INTEGER" +
")";
db.execSQL(query);
}
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
db.execSQL("DROP TABLE IF EXISTS " + TABLE_TASKS);
onCreate(db);
}
//Add a new row to the database
public void addTask(MyTasksGS myTask) {
ContentValues values = new ContentValues();
values.put(COLUMN_ID, myTask.getId());
values.put(COLUMN_TASKNAME, myTask.getTitle());
values.put(COLUMN_DAYSLEFT, myTask.getDaysRemaining());
SQLiteDatabase db = getWritableDatabase();
db.insert(TABLE_TASKS, null, values);
db.close();
}
//Delete row from the database
public void deleteTask(String taskID) {
SQLiteDatabase db = getWritableDatabase();
db.execSQL("DELETE FROM " + TABLE_TASKS + " WHERE " + COLUMN_ID + "=\"" + taskID + "\";");
}
//To put data into an arraylist
public List<MyTasksGS> getDataFromDB()
{
int id, daysRemaining;
String title;
List<MyTasksGS> tasksList = new ArrayList<MyTasksGS>();
String query = "SELECT * FROM " + TABLE_TASKS;
SQLiteDatabase db = getReadableDatabase();
Cursor cursor = db.rawQuery(query, null);
cursor.moveToFirst();
while (cursor.moveToNext())
{
id = cursor.getInt(cursor.getColumnIndexOrThrow(COLUMN_ID));
title = cursor.getString(cursor.getColumnIndexOrThrow(COLUMN_TASKNAME));
daysRemaining = cursor.getInt(cursor.getColumnIndexOrThrow(COLUMN_DAYSLEFT));
MyTasksGS myTask = new MyTasksGS(id, title, daysRemaining);
tasksList.add(myTask);
}
return tasksList;
}
}
I'm trying to copy the arraylist data which is returned from the above class(using getDataFromDB function) into myTaskList here and im getting this error:
java.lang.NullPointerException: Attempt to invoke virtual method 'java.util.List com.example.prateek.karma.TasksDBHandler.getDataFromDB()' on a null object reference
public class MyTasksFragment extends Fragment {
Button taskComplete;
RecyclerView RVMyTasks;
static MyTasksAdapter mtAdapter;
List<MyTasksGS> myTaskList = new ArrayList<>();
TasksDBHandler dbHandler;
public MyTasksFragment() {
// Required empty public constructor
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
// Inflate the layout for this fragment
View view = inflater.inflate(R.layout.fragment_my_tasks, container, false);
taskComplete = (Button) view.findViewById(R.id.taskComplete);
RVMyTasks = (RecyclerView) view.findViewById(R.id.RVMyTasks);
mtAdapter = new MyTasksAdapter(myTaskList);
RecyclerView.LayoutManager mLayoutManager = new LinearLayoutManager(getContext());
RVMyTasks.setLayoutManager(mLayoutManager);
RVMyTasks.setItemAnimator(new DefaultItemAnimator());
RVMyTasks.setAdapter(mtAdapter);
myTaskList = dbHandler.getDataFromDB();
mtAdapter.notifyDataSetChanged();
return view;
}
}
And this is the MyTasksGS class:
public class MyTasksGS {
String title;
int daysRemaining;
int id;
public MyTasksGS() {
}
public MyTasksGS(int id, String title, int daysRemaining) {
this.title = title;
this.daysRemaining = daysRemaining;
this.id = id;
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getTitle() {
return title;
}
public void setTitle(String title) {
this.title = title;
}
public int getDaysRemaining() {
return daysRemaining;
}
public void setDaysRemaining(int daysRemaining) {
this.daysRemaining = daysRemaining;
}
}
I may have made a very silly mistake somewhere but im not able to find it. Any help is appreciated
You need to instantiate the dbHandler, you are trying to use it without a valid instance. It causes the NullPointerException.
In your on onCreateView
before myTaskList = dbHandler.getDataFromDB();
add : dbHandler = new TasksDBHandler(getActivity());
use your class property DATABASE_NAME and DATABASE_VERSION instead of pass in constructor.
Change your TaskDBHandler constructor like this
public TasksDBHandler(Context context) {
super(context, DATABASE_NAME, null, DATABASE_VERSION);
}
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);
}