Unfortunately this app has stopped working (SQLiteDatabase) [duplicate] - android

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);
}
}

Related

Why my database deletion code did not works

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 + "");

Application crashes on Inserting into SQLITE database [duplicate]

This question already has answers here:
Unfortunately MyApp has stopped. How can I solve this?
(23 answers)
Closed 5 years ago.
There goes the code . I just cant figure out what is the problem. I am just taking the email and password as input from user and trying to store into a table named stu. The application crashes on clicking the sign in button which redirects to a next page using "intent" and inserting values into a table.
It would be of great help if problem could be identified that cause app to crash .
Thanks
Database Helper.java
package com.example.zain.smd1;
import android.content.ContentValues;
import android.content.Context;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
public class DatabaseHelper extends SQLiteOpenHelper {
public static final String DB_NAME = "student.db";
public static final String Table_name = "stu";
public static final String COL1 = "Id";
public static final String COL2 = "EMAIL";
public static final String COL3 = "PASS";
private static final String PASS = "PASS";
private static final String EMAIL = "EMAIL";
public DatabaseHelper(Context context) {
super(context,DB_NAME,null,1);
}
#Override
public void onCreate(SQLiteDatabase db) {
db.execSQL("create table " + Table_name + " (Id INTEGER PRIMARY KEY AUTOINCREMENT, EMAIL TEXT , PASS TEXT)");
}
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
db.execSQL("DROP TABLE IF EXISTS "+Table_name);
onCreate(db);
}
public boolean insertdata(String email , String pass){
SQLiteDatabase db = this.getWritableDatabase();
ContentValues content = new ContentValues();
content.put(EMAIL,email);
content.put(PASS,pass);
long result = db.insert(Table_name,null,content);
if (result==-1){
return false;
}
else
return true;
}
}
Main Activity.java
package com.example.zain.smd1;
import android.content.Intent;
import android.content.SharedPreferences;
import android.graphics.Color;
import android.preference.PreferenceManager;
import android.support.constraint.ConstraintLayout;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.EditText;
import android.widget.RelativeLayout;
import android.widget.Toast;
public class MainActivity extends AppCompatActivity {
EditText et1,et2;
String email,pass;
RelativeLayout r1;
SharedPreferences sp;
DatabaseHelper db;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
et1= (EditText) findViewById(R.id.eTemail);
et2 = (EditText) findViewById(R.id.eTpassword);
r1 = (RelativeLayout) findViewById(R.id.colorChange);
}
public void login(View view){
email = et1.getText().toString();
pass = et2.getText().toString();
if(email.equals("admin")&& pass.equals("admin")){
Toast.makeText(getApplicationContext(),
"Redirecting...",Toast.LENGTH_SHORT).show();
r1.setBackgroundColor(Color.RED);
/*sp= PreferenceManager.getDefaultSharedPreferences(getApplicationContext());
SharedPreferences.Editor e= sp.edit();
e.putString("name",email);
e.putString("password",pass);
e.apply();*/
boolean ischecked = db.insertdata(et1.getText().toString(),et2.getText().toString());
if(ischecked==true) {
Toast.makeText(getApplicationContext(),
"Added",Toast.LENGTH_SHORT).show();
Intent intent = new Intent(this, Main2Activity.class);
startActivity(intent);
}
}
else {
r1.setBackgroundColor(Color.GREEN);
Toast.makeText(getApplicationContext(),
"Invalid password or email",Toast.LENGTH_SHORT).show();
}
/*
String name=sp.getString("name","");
String pass= sp.getString("password","");
et1.setText(name);
et2.setText(pass);
*/
}
}
Application crashes on inserting into SQLite database . I just couldn't figure out whats wrong
Try to uninstall the existing application from your Debugging device and then install it again. Sometimes when you change the structure of your table after installing it and again you are installing then it doesn't create new table.
you should try this...
DatabaseHelper db;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
//add this line in your code..
db = new DatabaseHelper(this);
et1= (EditText) findViewById(R.id.eTemail);
et2 = (EditText) findViewById(R.id.eTpassword);
r1 = (RelativeLayout) findViewById(R.id.colorChange);
}

SQLiteAssetHelper and getWritableDatabase

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.

java.lang.NullPointerException when adding data to sqlite

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.

Android application - Logging causing error

Hi I am working with my application project.. It just happen that after I click on the login button, an error message pops out saying that Sorry! The application has stopped unexpectedly. Please try again. What is the error of this? please help thanks
This was my code for the data base of the user..
package com.gomez.android;
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.util.Log;
public class dbuser{
public static final String user_name = "username";
public static final String user_password = "password";
public static final String row_id = "_id";
private static final String TAG = "UdbAdapter";
private DatabaseHelper UdbHelper;
private SQLiteDatabase Udb;
/**
* Database creation sql statement
*/
private static final String DATABASE_CREATE =
"create table pages (_id integer primary key autoincrement, "
+ "username text not null, password text not null);";
private static final String DATABASE_NAME = "UserAccount";
private static final String DATABASE_TABLE = "User";
private static final int DATABASE_VERSION = 1;
private Context context = null;
private static class DatabaseHelper extends SQLiteOpenHelper {
DatabaseHelper(Context context) {
super(context, DATABASE_NAME, null, DATABASE_VERSION);
}
#Override
public void onCreate(SQLiteDatabase db) {
db.execSQL(DATABASE_CREATE);
}
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
Log.w(TAG, "Upgrading database from version " + oldVersion + " to "
+ newVersion + ", which will destroy all old data");
db.execSQL("DROP TABLE IF EXISTS pages");
onCreate(db);
}
}
public dbuser(Context cntxt) {
this.context = cntxt;
UdbHelper = new DatabaseHelper(context);
}
public void open() throws SQLException {
Udb = UdbHelper.getWritableDatabase();
}
public void close() {
UdbHelper.close();
}
public long createaccount(String username, String password)
{
Udb = UdbHelper.getWritableDatabase();
ContentValues initialValues = new ContentValues();
initialValues.put(user_name, username);
initialValues.put(user_password, password);
return Udb.insert(DATABASE_TABLE, null, initialValues);
}
public boolean Login(String username, String password)throws SQLException
{
Cursor mCursor = Udb.rawQuery(DATABASE_TABLE, new String[]{username,password});
if (mCursor != null){
if(mCursor.getCount() > 0){
return true;
}
}
return false;
}
}
and this was my login page code.....
package com.gomez.android;
import com.gomez.android.dbuser;
import android.os.Bundle;
import android.app.Activity;
import android.content.Intent;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;
public class login extends Activity{
//Declare views
private EditText uname;
private EditText pword;
private Button btnlogin;
private Button btncancel;
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
//set Activity Layout
setContentView(R.layout.login);
//Get EditText and Button References
uname = (EditText)findViewById(R.id.username);
pword = (EditText)findViewById(R.id.password);
btnlogin = (Button)findViewById(R.id.login_enter);
btncancel = (Button)findViewById(R.id.cancel);
//set Click Listener
btnlogin.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
//Check Login
final String username = uname.getText().toString();
final String password = pword.getText().toString();
dbuser users = new dbuser(login.this);
users.open();
if(users.Login(username, password)){
if(username.equalsIgnoreCase(username)&& password.equalsIgnoreCase(password))
{
Toast.makeText(login.this,"Successfully Logged In", Toast.LENGTH_LONG).show();
Intent i = new Intent(login.this, firstpage.class);
startActivity(i);
}
else{
Toast.makeText(login.this,"Invalid Username/Password", Toast.LENGTH_LONG).show();
}
users.close();
}
}
});
btncancel.setOnClickListener(new OnClickListener(){
#Override
public void onClick(View v){
//close application
finish();
}
});
}
}
I can't be sure what the problem is with your code since you didn't provide any information from the LogCat, but it is possible that getWriteableDatabase() is returning a cached database when running the application (I often ran into this problem when implementing and testing a database for the first time).
To ensure this is not the problem, go to Settings -> Applications -> Manage Applications -> [Your Application] -> Clear Data, before running the application from Eclipse. This is an easy way to ensure you are working with your most up-to-date implementation during the early stages of implementing/testing the database.
This very well might not be the problem, but it is one of those things that you wouldn't expect to be the issue (which often leads to hours of frustration), so I thought I'd bring it up :).

Categories

Resources