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.
Related
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 + "");
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 have created a simple app to learn sqlite in android.
But when i click on the showdata button i get null values
MainDB.java
package com.example.logintp;
import java.util.List;
import android.R.layout;
import android.app.Activity;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import com.example.logintp.R.id;
public class MainDB extends Activity {
TextView name, password,show1;
EditText etname, etpassword;
Button save,show;
String s1, s2;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
final DbClass db = new DbClass(this);
name = (TextView) findViewById(R.id.name);
password = (TextView) findViewById(R.id.password);
show1=(TextView) findViewById(R.id.show);
etname = (EditText) findViewById(R.id.etName);
etpassword = (EditText) findViewById(id.etPassword);
save = (Button) findViewById(R.id.save);
show=(Button) findViewById(R.id.Display);
show.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
String data=db.showAll();
show1.setText(data);
}
});
save.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View arg0) {
// TODO Auto-generated method stub
s1 = etname.getText().toString();
s2 = etpassword.getText().toString();
long id = db.insertData(new Login(s1, s2));
if (id < 0) {
CommonFunctions.display(MainDB.this, "unsucessful");
}else{
CommonFunctions.display(MainDB.this, "sucessful");
}
}
});
}
}
DataBaseHandler Class
package com.example.logintp;
import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
public class DbClass extends SQLiteOpenHelper {
private static final String db_name="LoginDetails";
private static final String table_name="Login";
private static final String name="name";
private static final String password="password";
private static final int db_version=1;
private static final String Create_Table=" CREATE TABLE " + table_name + "(" +name + " VARCHAR(200)," +password+ " VARCHAR(200)" + " ) ";
public DbClass(Context context){
super(context, db_name, null, db_version);
}
public void onCreate(SQLiteDatabase db) {
// TODO Auto-generated method stub
db.execSQL(Create_Table);
}
#Override
public void onUpgrade(SQLiteDatabase arg0, int arg1, int arg2) {
// TODO Auto-generated method stub
}
public long insertData(Login l){
SQLiteDatabase db=getWritableDatabase();
ContentValues cv=new ContentValues();
cv.put(name, l.getName());
cv.put(password, l.getPassword());
long id=db.insert(table_name, null, cv);
db.close();
return id;
}
public String showAll(){
String[] coloums= {name , password};
StringBuffer b=new StringBuffer();
SQLiteDatabase db=getWritableDatabase();
Cursor cursor=db.query(table_name, coloums, null, null, null, null, null);
while(cursor.moveToNext()){
//Login login=new Login();
String name1=cursor.getString(0);
String password1=cursor.getString(1);
b.append(name1+" "+password1+ "/n");
}
return b.toString();
}
}
i have created a simple app to learn sqlite in android.
But when i click on the showdata button i get null values
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.