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
Related
I'm working on a code snippet for performing CRUD operations in Sqlite DB in Android Studio. I created a listView to hold two attributes, i.e., name and job but the application is getting crashed at runtime. It says:
Sqlite Exception: no such column( code 1) "name" Found.
I've searched for the solution but every solution I've checked is a failed one. My DB browser shows the table contains the column. Do I need to add SELECT FROM ...query to my code? If it is, then where should I put the code?
my code as below:
DatabaseHelper.class
import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
public class DatabaseHelper extends SQLiteOpenHelper {
private static final int DATABASE_VERSION = 1;
public static final String DATABASE_NAME = "SQLiteDatabase.db";
public static final String TABLE_NAME = "USERS";
public static final String _ID = "_id";
public static final String DESC = "occupation";
public static final String SUBJECT = "name";
SQLiteDatabase myDb;
private static final String CREATE_TABLE = "CREATE TABLE " + TABLE_NAME +
"(" + _ID + " INTEGER PRIMARY KEY AUTOINCREMENT,"
+ SUBJECT + "TEXT NOT NULL,"
+ DESC + "TEXT"+ ")" ;
public DatabaseHelper(Context context) {
super(context, DATABASE_NAME, null, DATABASE_VERSION);
}
#Override
public void onCreate(SQLiteDatabase db) {
db.execSQL(CREATE_TABLE);
}
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
db.execSQL(" DROP TABLE IF EXISTS " + TABLE_NAME);
onCreate(db);
}
public long insert(String name, String desc) {
myDb = this.getWritableDatabase();
ContentValues contentValues = new ContentValues();
contentValues.put(DatabaseHelper.SUBJECT, name);
contentValues.put(DatabaseHelper.DESC, desc);
long id = myDb.insert(DatabaseHelper.TABLE_NAME, null, contentValues);
myDb.close();
return id;
}
public Cursor read(){
SQLiteDatabase myDb = this.getWritableDatabase();
String[] columns = new String[] {DatabaseHelper._ID,DatabaseHelper.SUBJECT,DatabaseHelper.DESC};
Cursor cursor = myDb.query(DatabaseHelper.TABLE_NAME,columns,null,null,null,null,null);
if(cursor!=null){
cursor.moveToFirst();
}
myDb.close();
return cursor;
}
}
MainActivity.class
import android.content.Intent;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.ListView;
import java.util.ArrayList;
public class MainActivity extends AppCompatActivity {
Button addUser;
ArrayList<String> list;
ArrayAdapter<String> adapter;
DatabaseHelper dbManager;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
addUser = findViewById(R.id.add_button);
list = new ArrayList<>();
adapter = new ArrayAdapter<>(this, R.layout.populate_list, R.id.name, list);
dbManager = new DatabaseHelper(this);
addUser.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
addAccount();
}
});
}
public void addAccount() {
Intent intent = new Intent(MainActivity.this, AddUser.class);
startActivityForResult(intent, 1);
}
#Override
public void onActivityResult(int requestCode, int resultCode, Intent intent) {
if (requestCode == 1) {
final String name = intent.getStringExtra("name");
final String occupation = intent.getStringExtra("occupation");
ListView listView = findViewById(R.id.parentLayout);
dbManager.read();
list.add(name);
listView.setAdapter(adapter);
adapter.notifyDataSetChanged();
listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
Intent i = new Intent(MainActivity.this, UpdateActivity.class);
i.putExtra(name, "username");
i.putExtra(occupation, "occupation");
startActivity(i);
}
});
}
}
}
AddUser.class
import android.content.Intent;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
public class AddUser extends AppCompatActivity {
EditText userName, job;
Button submitButton, cancelButton;
DatabaseHelper dbManager;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_add_user);
dbManager = new DatabaseHelper(this);
userName = findViewById(R.id.userText);
job = findViewById(R.id.occupation);
submitButton = findViewById(R.id.submit_button);
cancelButton = findViewById(R.id.cancel_button);
cancelButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent(AddUser.this, MainActivity.class);
startActivity(intent);
}
});
submitButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = getIntent();
String name = userName.getText().toString();
String desc = job.getText().toString();
intent.putExtra(name, "name");
intent.putExtra(desc, "occupation");
dbManager.insert(name, desc);
setResult(1, intent);
finish();
}
});
}
}
You can try using a rawquery like this :
String sql = " SELECT * FROM " + TABLE_NAME + " WHERE " + ONE_COLUMN_NAME + "=?" + " AND " + PERHAPS_ANOTHER_COLUMN + " =?";
ArrayList<YourKindOfObject> array = new ArrayList<>();
Cursor cursor = sqLiteDatabase.rawQuery(sql, new String[]{firstParameter, secondParameter});
while (cursor.moveToNext()) {
YourKindOfObject yourKindOfObject = new YourKindOfObject();
yourKindOfObject.setOneThing(cursor.getString(cursor.getColumnIndex(ColumnName));
yourKindOfObject.setOneOtherThing(cursor.getString(cursor.getColumnIndex(ColumnName1)));
array.add(yourKindOfObject);
}
cursor.close();
return array;
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 want to make it so that there is a ListView with a Button above it. The users clicks that button, and it opens a dialog with an EditText and an OK and Cancel button. When the user clicks OK, whatever text is entered into the EditText gets put into the SQLiteDatabase, which is reflected in the ListView.
I've already set up my SQLiteDatabase and have set an adapter for the List to show the SQLiteDatabase, but I need to figure out how to use the edittext.getText().toString() method to add to the SQLiteDatabase. I will need a code example.
If you need it, here's my main .java:
package com.gantt.shoppinglist;
import android.app.Dialog;
import android.app.ListActivity;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.SimpleCursorAdapter;
public class ShoppingList extends ListActivity {
/** Called when the activity is first created. */
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
final DataHelper dataHelper = new DataHelper(this);
ListView lv = (ListView) findViewById(android.R.id.list);
SimpleCursorAdapter adapter = null;
final SQLiteDatabase db = dataHelper.selectAll();
Cursor c = db.rawQuery("SELECT DISTINCT oid as _id,name FROM table1 ORDER BY name", null);
if (c.moveToFirst()) {
String[] columnNames = new String[]{"name"};
int[] list = new int[]{android.R.id.list};
adapter = new SimpleCursorAdapter(this, R.layout.rowlayout, c, columnNames, list);
}
lv.setAdapter(adapter);
Button button1main = (Button) findViewById(R.id.add);
button1main.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
final Dialog additem = new Dialog(ShoppingList.this);
additem.setContentView(R.layout.maindialog);
final EditText et = (EditText)additem.findViewById(R.id.edittext);
additem.setTitle("Type your item");
additem.setCancelable(true);
et.setHint("Type the name of an item...");
Button button = (Button) additem.findViewById(R.id.cancel);
button.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
additem.dismiss();
}
});
additem.show();
Button ok = (Button) additem.findViewById(R.id.ok);
ok.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
et.getText().toString();
additem.dismiss();
et.setText("");
}
});
}
});
}
}
Here is my DataHelper class:
package com.gantt.shoppinglist;
import java.util.ArrayList;
import java.util.List;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
import android.database.sqlite.SQLiteStatement;
import android.util.Log;
public class DataHelper {
public static final String DATABASE_NAME = "items.db";
public static final int DATABASE_VERSION = 1;
public static final String TABLE_NAME = "table1";
public static final String KEY_ROWID = "_id";
private Context context;
private SQLiteDatabase db;
private SQLiteStatement insertStmt;
private static final String INSERT = "insert into "
+ TABLE_NAME + "(name) values (?)";
public DataHelper(Context context) {
this.context = context;
OpenHelper openHelper = new OpenHelper(this.context);
this.db = openHelper.getWritableDatabase();
this.insertStmt = this.db.compileStatement(INSERT);
}
public long insert(String name) {
this.insertStmt.bindString(1, name);
return this.insertStmt.executeInsert();
}
public void deleteAll() {
this.db.delete(TABLE_NAME, null, null);
}
public SQLiteDatabase selectAll() {
List<String> list = new ArrayList<String>();
Cursor cursor = this.db.query(TABLE_NAME, new String[] { "name" },
null, null, null, null, "name desc");
if (cursor.moveToFirst()) {
do {
list.add(cursor.getString(0));
} while (cursor.moveToNext());
}
if (cursor != null && !cursor.isClosed()) {
cursor.close();
}
return db;
}
public static String getDatabaseName() {
return DATABASE_NAME;
}
private static class OpenHelper extends SQLiteOpenHelper {
OpenHelper(Context context) {
super(context, getDatabaseName(), null, DATABASE_VERSION);
}
#Override
public void onCreate(SQLiteDatabase db) {
db.execSQL("CREATE TABLE " + TABLE_NAME + "(id INTEGER PRIMARY KEY, name TEXT");
}
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
Log.w("Example", "Upgrading database, this will drop tables and recreate.");
db.execSQL("DROP TABLE IF EXISTS " + TABLE_NAME);
onCreate(db);
}
}
}
Using the current methods you have, and assuming that you understand the code that you used for the database adapter, just do this:
String item = et.getText().toString();// these two lines are the
dataHelper.insert(item); // only change you have to do
additem.dismiss();
et.setText("");
After doing this, you have to call the notifyDataSetChanged method of your SimpleCursorAdapter object.
A simple sample method for your DataHelper class:
public long createUser(String email, String password, String fullName) {
ContentValues initialValues = new ContentValues();
initialValues.put("email", email);
initialValues.put("password", password);
initialValues.put("fullName", fullName);
return mDb.insert(TABLE_NAME, null, initialValues);
}