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 + "");
Related
This question already has answers here:
Unfortunately MyApp has stopped. How can I solve this?
(23 answers)
Closed 7 years ago.
I have this problem: I wrote an app, but the SQLiteDatabase isn't working.
My database class code:
package com.example.frauprinzssapp;
import android.content.ContentValues;
import android.content.Context;
import android.database.DatabaseErrorHandler;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteDatabase.CursorFactory;
import android.database.sqlite.SQLiteOpenHelper;
public class database extends SQLiteOpenHelper{
public static final String DB_NAME = "users.db";
public static final String DB_TABLENAME = "users_table";
public static final String COL_1 = "id";
public static final String COL_2 = "name";
public static final String COl_3 = "class";
public static final String COL_4 = "right";
public database(Context context) {
super(context, DB_NAME, null, 1);
}
#Override
public void onCreate(SQLiteDatabase db) {
db.execSQL("create table "+DB_TABLENAME+"(id INTEGER PRIMARY KEY AUTOINCREMENT, name TEXT, class TEXT, right INTEGER)");
}
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
db.execSQL("DROP TABLE IF EXIST "+DB_TABLENAME);
onCreate(db);
}
public boolean insertdata(String name, String clas){
SQLiteDatabase db = this.getWritableDatabase();
ContentValues cv = new ContentValues();
cv.put(COL_2, name);
cv.put(COl_3, clas);
cv.put(COL_4, 0);
long result = db.insert(DB_TABLENAME, null, cv);
if (result == -1){
return false;
}else{
return true;
}
}
}
The main code is:
package com.example.frauprinzssapp;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import android.app.Activity;
import android.content.Context;
import android.os.Bundle;
import android.view.View;
import android.widget.EditText;
import android.widget.Toast;
public class Main extends Activity {
List<String> addusers = new ArrayList<String>();
database myDb;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
myDb = new database(this);
}
//-----change view voids-----
public void main(View view){
setContentView(R.layout.main);
}
public void adduser(View view){
setContentView(R.layout.adduser);
}
public void removeuser(View view){
setContentView(R.layout.removeuser);
}
//------actions------
public void add(){
EditText name = (EditText) findViewById(R.id.aun);
EditText clas = (EditText) findViewById(R.id.auc);
if (name.toString() == null || clas.toString() == null){
Toast.makeText(Main.this, "please fill in all textfields!", Toast.LENGTH_LONG);
return;
}
try{
myDb.insertdata(name.toString(), clas.toString());
Toast.makeText(Main.this, "added user "+name.toString()+"!", Toast.LENGTH_LONG);
}catch(Exception e){
Toast.makeText(Main.this, "[ERROR] Could not create user maybe its already created!", Toast.LENGTH_LONG);
}
}
public void remove(){
}
public void show(){
}
}
I used the
android:onClick="add"
to make so that the add() void runs
please now it just puts random stuff into the sqlite pleaseeeee help
try it....
//------actions------
public void add(){
EditText name = (EditText) findViewById(R.id.aun);
EditText clas = (EditText) findViewById(R.id.auc);
String name1 = name.getText().toString();
String clas1 = clas.getText().toString();
if (name1.equals("") || clas1.equals("")){
Toast.makeText(Main.this, "please fill in all textfields!", Toast.LENGTH_LONG);
return;
}
try{
myDb.insertdata(name1, clas1);
Toast.makeText(Main.this, "added user "+name1+"!", Toast.LENGTH_LONG);
}catch(Exception e){
Toast.makeText(Main.this, "[ERROR] Could not create user maybe its already created!", Toast.LENGTH_LONG);
}
}
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))
I'm having have some trouble with my Database activity. I am unable to write to the database and view the database using the following code.
my Database activity:
package com.jacob.eindproject;
import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.SQLException;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
import android.database.sqlite.SQLiteDatabase.CursorFactory;
import java.sql.*;
import com.readystatesoftware.sqliteasset.SQLiteAssetHelper;
public class Database extends SQLiteAssetHelper {
public static final String KEY_PRODUCT = "Product";
public static final String KEY_EENHEID = "Eenheid";
public static final String KEY_KCAL = "Kcal";
private static final String DATABASE_NAME = "Voedsel";
private static final String DATABASE_TABLE = "Voeding";
private static final int DATABASE_VERSION = 1;
private DbHelper ourHelper;
private final Context ourContext;
private SQLiteDatabase ourDatabase;
private static class DbHelper extends SQLiteAssetHelper{
public DbHelper(Context context) {
super(context, DATABASE_NAME, context.getExternalFilesDir(null).getAbsolutePath(), null, DATABASE_VERSION);
// TODO Auto-generated constructor stub
}
}
#Override
public void onUpgrade(SQLiteDatabase Voedsel, int oldVersion, int newVersion) {
Voedsel.execSQL("DROP TABLE IF EXISTS " + DATABASE_TABLE);
onCreate(Voedsel);
}
public void close(Database database) {
// TODO Auto-generated method stub
}
public Database(Context c){
ourContext = c;
}
public Database open() throws SQLException{
ourHelper = new DbHelper(ourContext);
ourDatabase = ourHelper.getWritableDatabase();
return this;
}
public void close() {
ourHelper.close();
}
public long createEntry(String product, String kcal, String eenheid) {
ContentValues cv = new ContentValues();
cv.put(KEY_PRODUCT, product);
cv.put(KEY_EENHEID, eenheid);
cv.put(KEY_KCAL, kcal);
return ourDatabase.insert(DATABASE_TABLE, null, cv);
}
public String getData() {
// TODO Auto-generated method stub
String[] columns = new String[]{ KEY_PRODUCT, KEY_EENHEID, KEY_KCAL};
Cursor c = ourDatabase.query(DATABASE_TABLE, columns, null, null, null, null, null);
String result = "";
int iRow = c.getColumnIndex(KEY_PRODUCT);
int iName = c.getColumnIndex(KEY_EENHEID);
int iHotness = c.getColumnIndex(KEY_KCAL);
for (c.moveToFirst(); !c.isAfterLast(); c.moveToNext()){
result = result + c.getString(iRow) + " " + c.getString(iName) + " " + c.getString(iHotness) + "\n";
}
return result;
}
}
My SQLView activity:
package com.jacob.eindproject;
import android.app.Activity;
import android.os.Bundle;
import android.widget.TextView;
public class SQLView extends Activity{
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.sqlview);
TextView tv = (TextView) findViewById(R.id.tvSQLinfo);
Database info = new Database(this);
info.open();
String data = info.getData();
info.close();
tv.setText(data);
}
}
SQLite activity:
package com.jacob.eindproject;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.app.Activity;
import android.app.Dialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.view.View.OnClickListener;
public class SQLite extends Activity implements View.OnClickListener {
Button sqlUpdate, sqlView;
EditText sqlVoeding, sqlKcal, sqlEenheid;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.sqllite);
sqlUpdate = (Button) findViewById(R.id.bSQLUpdate);
sqlVoeding = (EditText) findViewById(R.id.etSQLVoeding);
sqlEenheid = (EditText) findViewById(R.id.etSQLEenheid);
sqlKcal = (EditText) findViewById(R.id.etSQLKcal);
sqlView = (Button) findViewById(R.id.bSQLopenView);
sqlView.setOnClickListener((android.view.View.OnClickListener) this);
sqlUpdate.setOnClickListener((android.view.View.OnClickListener) this);
}
public void onClick(View arg0) {
switch (arg0.getId()) {
case R.id.bSQLUpdate:
boolean didItWork = true;
try{
String voeding = sqlVoeding.getText().toString();
String Kcal = sqlKcal.getText().toString();
String eenheid = sqlEenheid.getText().toString();
Database entry = new Database(SQLite.this);
entry.open();
entry.createEntry(voeding, Kcal, eenheid);
entry.close();
}catch (Exception e ){
didItWork = false;
}finally{
if (didItWork){
Dialog d = new Dialog(this);
d.setTitle("Heak Yeay");
TextView tv = new TextView(this);
tv.setText("Succes");
d.setContentView(tv);
d.show();
}
}
break;
case R.id.bSQLopenView:
Intent i = new Intent(this, SQLView.class);
startActivity(i);
}
}
public void onClick(DialogInterface arg0, int arg1) {
// TODO Auto-generated method stub
}
}
I am having my database file(Voedsel.rar), in assets/databases/Voedsel.rar.
To write to your database, try a method like this:
public void insertVoeding(String product, String eenheid, String kcal) {
ourDatabase.execSQL("INSERT INTO Voeding (Product, Eenheid, Kcal) VALUES (?, ?, ?)",
new String[] {product, eenheid, kcal});
}
The question marks are replaced by the values in the string array. Your column names cannot be inserted using the string array, because the execSQL method puts quotation marks around these values. The query will fail if you try.
There are two ways to read from a database (may even be two ways to write to it, too). I personally prefer using raw queries, like this one to get the entire database:
public Cursor getEntireDB() {
return ourDatabase.rawQuery("SELECT * FROM Voeding");
}
You can then use the cursor in a CursorAdapter to create a list.
I am getting Nullpointerexception error when checked rdio4
Codes:
Answerpage.java
package com.example.psikotestproject;
import android.app.Activity;
import android.content.ContentValues;
import android.content.Context;
import android.content.Intent;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteDatabase.CursorFactory;
import android.database.sqlite.SQLiteOpenHelper;
import android.os.Bundle;
import android.os.Message;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.widget.Button;
import android.widget.RadioButton;
import android.widget.RadioGroup;
import android.widget.TextView;
import android.widget.Toast;
public class AnswerPage extends Activity{
#Override
protected void onDestroy() {
super.onDestroy();
}
DbHelper dbhelper;
SQLiteDatabase db;
Context contextim;
int i=1;
int obko=0;
int soma=0;
int kadu=0;
int depr=0;
int foan=0;
static float somahesap=0.0f;
static float obkohesap=0.0f;
static float kaduhesap=0.0f;
static float deprhesap=0.0f;
static float foanhesap=0.0f;
//dizim
final String questions[]={
"Baş ağrısı" ,
"Sinirlilik ya da içinin titremesi",
"Zihinden atamadığınız tekrarlayan, hoşa gitmeyen düşünceler",
"Baygınlık ya da baş dönmesi",
"Cinsel arzu ve ilginin kaybı",
"Başkaları tarafından eleştirilme duygusu",
"Herhangi bir kimsenin düşüncelerinizi kontrol edebileceği
};
#Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.answerpage);
//component tanımları
final TextView txtquestion=(TextView)findViewById(R.id.txtquestion);
final RadioGroup rdiogroup=(RadioGroup)findViewById(R.id.rdiogroup);
final RadioButton rdio0=(RadioButton)findViewById(R.id.rdio0);
final RadioButton rdio1=(RadioButton)findViewById(R.id.rdio1);
final RadioButton rdio2=(RadioButton)findViewById(R.id.rdio2);
final RadioButton rdio3=(RadioButton)findViewById(R.id.rdio3);
final RadioButton rdio4=(RadioButton)findViewById(R.id.rdio4);
final Button btndigersoru=(Button)findViewById(R.id.btndigersoru);
final Button btnoncekisoru=(Button)findViewById(R.id.btnoncekisoru);
txtquestion.setText(questions[i-1]);
//diğersorubutonclick
btndigersoru.setOnClickListener(new View.OnClickListener(){
public void onClick(View v){
if(rdio0.isChecked()||rdio1.isChecked()||rdio2.isChecked()||rdio3.isChecked()||rdio4.isChecked())
{
txtquestion.setText(questions[i]);
if(rdio0.isChecked()==true)
{
dbhelper.addKayitlar(rdiogroup.getCheckedRadioButtonId());
//secili[i]=rdiogroup.getCheckedRadioButtonId();
rdiogroup.clearCheck();
}
if(rdio1.isChecked()==true)
{
if(i==1||i==4||i==12||i==27||i==40||i==42||i==48||i==52||i==53||i==56||i==58)
soma++;
if(i==3||i==9||i==10||i==28||i==38||i==45||i==46||i==51||i==55||i==65)
obko++;
if(i==6||i==21||i==34||i==36||i==37||i==41||i==61||i==69||i==73)
kadu++;
if(i==4||i==5||i==15||i==20||i==22||i==26||i==29||i==30||i==31||i==32||i==54||i==71||i==79)
depr++;
if(i==13||i==25||i==47||i==50||i==70||i==75||i==82)
foan++;
dbhelper.addKayitlar(rdiogroup.getCheckedRadioButtonId());
//secili[i]=rdiogroup.getCheckedRadioButtonId();
rdiogroup.clearCheck();
}
if(rdio2.isChecked()==true)
{
if(i==1||i==4||i==12||i==27||i==40||i==42||i==48||i==52||i==53||i==56||i==58)
soma=soma+2;
if(i==3||i==9||i==10||i==28||i==38||i==45||i==46||i==51||i==55||i==65)
obko=obko+2;
if(i==6||i==21||i==34||i==36||i==37||i==41||i==61||i==69||i==73)
kadu=kadu+2;
if(i==4||i==5||i==15||i==20||i==22||i==26||i==29||i==30||i==31||i==32||i==54||i==71||i==79)
depr=depr+2;
if(i==13||i==25||i==47||i==50||i==70||i==75||i==82)
foan=foan+2;
dbhelper.addKayitlar(rdiogroup.getCheckedRadioButtonId());
//secili[i]=rdiogroup.getCheckedRadioButtonId();
rdiogroup.clearCheck();
}
if(rdio3.isChecked()==true)
{
if(i==1||i==4||i==12||i==27||i==40||i==42||i==48||i==52||i==53||i==56||i==58)
soma=soma+3;
if(i==3||i==9||i==10||i==28||i==38||i==45||i==46||i==51||i==55||i==65)
obko=obko+2;
if(i==6||i==21||i==34||i==36||i==37||i==41||i==61||i==69||i==73)
kadu=kadu+2;
if(i==4||i==5||i==15||i==20||i==22||i==26||i==29||i==30||i==31||i==32||i==54||i==71||i==79)
depr=depr+2;
if(i==13||i==25||i==47||i==50||i==70||i==75||i==82)
foan=foan+3;
dbhelper.addKayitlar(rdiogroup.getCheckedRadioButtonId());
//secili[i]=rdiogroup.getCheckedRadioButtonId();
rdiogroup.clearCheck();
}
if(rdio4.isChecked()==true)
{
if(i==1||i==4||i==12||i==27||i==40||i==42||i==48||i==52||i==53||i==56||i==58)
soma=soma+4;
if(i==3||i==9||i==10||i==28||i==38||i==45||i==46||i==51||i==55||i==65)
obko=obko+4;
if(i==6||i==21||i==34||i==36||i==37||i==41||i==61||i==69||i==73)
kadu=kadu+4;
if(i==4||i==5||i==15||i==20||i==22||i==26||i==29||i==30||i==31||i==32||i==54||i==71||i==79)
depr=depr+4;
if(i==13||i==25||i==47||i==50||i==70||i==75||i==82)
foan=foan+4;
dbhelper.addKayitlar(rdiogroup.getCheckedRadioButtonId());
//secili[i]=rdiogroup.getCheckedRadioButtonId();
rdiogroup.clearCheck();
}
}
if(i<16)
i++;
else{}
if(i>1)
{
btnoncekisoru.setVisibility(View.VISIBLE);
}
if(i>=9)
//if(i>=90)
{
//En son hesaplar
somahesap=(float) (soma/11.0);
obkohesap=(float) (obko/10.0);
kaduhesap=(float) (kadu/9.0);
deprhesap=(float) (depr/13.0);
foanhesap=(float) (foan/7.0);
Intent finishingActivity=new Intent("com.example.psikotestproject.RESULTPAGE");
startActivity(finishingActivity);
}
}
});
//btnoncekibutonclick
btnoncekisoru.setOnClickListener(new View.OnClickListener(){
public void onClick(View v){
rdiogroup.clearCheck();
dbhelper.getKayitlar(i-1);
txtquestion.setText(questions[i-1]);
i--;
//rdiogroup.check(secili[i]);
if(i<=0)
{
btnoncekisoru.setVisibility(View.INVISIBLE);
}
}
});
}
Dbhelper.java
public class DbHelper extends SQLiteOpenHelper {
// Tüm Static değişkenler
// Database Versiyonu
private static final int DATABASE_VERSION = 1;
// Database Adı
private static final String DATABASE_NAME = "dbSecimler";
// Kayitlar Tablosunun Adı
private static final String TABLE_NAME = "Secimler";
// Kayitlar Tablosunun Kolon Adları
private static final String KEY_CEVAP = "Cevaplar";
// Yapılandırıcı metod
public DbHelper(Context context) {
super(context, DATABASE_NAME, null, DATABASE_VERSION);
}
// Database Oluşturma işlemi.
#Override
public void onCreate(SQLiteDatabase db) {
String create_table = "CREATE TABLE " + TABLE_NAME + "(id INTEGER PRİMARY KEY AUTOINCREMENT"
+ KEY_CEVAP + " INTEGER," + ")";
db.execSQL(create_table);
}
// Database Yükseltme işlemi.
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
// Varsa şayet eski tabloyu sil.
db.execSQL("DROP TABLE IF EXISTS " + TABLE_NAME);
// Tekrar tablo oluştur.
onCreate(db);
}
// Yeni Kayıt Eklemek.
void addKayitlar(int i) {
SQLiteDatabase db= this.getWritableDatabase();
ContentValues values = new ContentValues();
values.put(KEY_CEVAP, i);
// Ekleme işlemi...
db.insert(TABLE_NAME, null , values);
db.close(); // Açık olan database i kapat.
}
//İstenilen Kaydı Getirmek.
Kayitlar getKayitlar(int i) {
SQLiteDatabase db = this.getReadableDatabase();
Cursor cursor = db.query(TABLE_NAME, new String[] {KEY_CEVAP},null, null, null, null, null);
if (cursor != null)
cursor.moveToFirst();
Kayitlar kayit = new Kayitlar(Integer.parseInt(cursor.getString(1)));
// return Kayitlar
return kayit;
}
}
Errors on LogCat
threadid=1: thread exiting with uncaught exception (group=0x4001d800)
FATAL EXCEPTION: main
java.lang.NullPointerExceptionat com.example.psikotestproject.AnswerPage$1.onClick(AnswerPage.java:282)
-
-
-
and 282 is: dbhelper.addKayitlar(rdiogroup.getCheckedRadioButtonId());
rdiogroup.getCheckedRadioButtonId() not null I'm sure.I think I have an error about saving database.What can I solve?
It seems that you are missing findViewById() for the view for which you have implemented onClickListener.
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)