SQLite database table recreating at each application reboot - java

I am new to Android development. I have a problem in my application. My SQLite database table
is recreating on each system reboot, and all saved contents are wiped out from table. Can anyone please help me to solve this problem?
here is my Database class....
package Nsh.android.sms;
import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteDatabase.CursorFactory;
import android.database.sqlite.SQLiteOpenHelper;
import android.provider.SyncStateContract.Helpers;
public class Database {
public static final String MYDATABASENAME="Mylanguagedbnew.db";
public static final String MYDATABASETABLE="Mylanguagedb_table1";
public static final int MYDATABASEVERSION=1;
public static final String KEY_id="_id";
public static final String KEY_language="languages";
public static final String KEY_description="languagedescription";
private static final String SCRIPT_CREATE_DATABASE="create table if not exists
"+MYDATABASETABLE+" ("+KEY_id+" integer primary key autoincrement, "+KEY_language+"
text not null, "+KEY_description+ " text not null);";
private datahelper sqliteopenhelper;
public static String userselectedlang;
private SQLiteDatabase sqlitedatabase;
private Context context;
public Database(Context c){
System.out.println("DBcontext!!!1111");
context=c;
}
public Database openToread()throws android.database.SQLException{
System.out.println("DBINSERTTTTTTTTT!!!OPENREAD22222");
sqliteopenhelper=new datahelper(context,MYDATABASENAME,null,MYDATABASEVERSION);
System.out.println("DBINSERTTTTTTTTT!!!OPENREAD22222");
sqlitedatabase=sqliteopenhelper.getReadableDatabase();
System.out.println("DBINSERTTTTTTTTT!!!OPENREAD22222");
return this;
}
public Database openTowrite()throws android.database.SQLException{
System.out.println("DBINSERTTTTTTTTT!!!OPENWRITE22222");
sqliteopenhelper=new datahelper(context,MYDATABASENAME,null,MYDATABASEVERSION);
sqlitedatabase=sqliteopenhelper.getWritableDatabase();
return this;
}
public void close(){
sqliteopenhelper.close();
}
public Cursor retriveall(){
System.out.println("RETRIEVE ALL OK!!!!!!!!!");
String[] columns={KEY_id,KEY_language,KEY_description};
Cursor cursor=sqlitedatabase.query(MYDATABASETABLE, columns,null,null,null,null,null);
return cursor;
}
public Cursor retrivelanguages(){
String[] columns={KEY_language};
Cursor c=sqlitedatabase.query(MYDATABASETABLE, columns,null,null,null,null,null);
return c;
}
public Cursor retrieveselectedlanguagedecription(){
userselectedlang=listlang.selectedlanguage;
String query="select languagedescription from Mylanguagedb_table1 where languages
='"+userselectedlang+"';";
Cursor c1=sqlitedatabase.rawQuery(query,null);
return c1;
}
public long insert(String language,String languagedescription){
System.out.println("DBINSERTTTTTTTTT!!!INSERT !!!!!!!!!1111");
ContentValues contentvalues=new ContentValues();
contentvalues.put(KEY_language,language);
contentvalues.put(KEY_description,languagedescription);
return sqlitedatabase.insert(MYDATABASETABLE, null,contentvalues);
}
public int deleteall(){
return sqlitedatabase.delete(MYDATABASETABLE,null,null);
}
/*public int deleterow(){
String selectedrow=listlang.selectedlanguage;
return sqlitedatabase.delete(MYDATABASETABLE,selectedrow, null);
}*/
private static class datahelper extends SQLiteOpenHelper{
public datahelper(Context context, String name, CursorFactory factory,
int version) {
super(context, name, factory, version);
// TODO Auto-generated constructor stub
}
#Override
public void onCreate(SQLiteDatabase db) {
// TODO Auto-generated method stub
db.execSQL(SCRIPT_CREATE_DATABASE);
}
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
// TODO Auto-generated method stub
//db.update(table, values, whereClause, whereArgs)
}
}
}

when app start it will create new db and table if not exist else it will continue with exit db.
put this code in your app's Start-up Activity's onCreate() method to check whether Database is already exist or not.
//this is the name of my database
public static final String DATABASE_NAME = "mydatabase.db";
//this is the complete path of my database stored. you can check in DDMS
public static final String DATABASE_PATH = "/data/data/com.rdc.mydatabase/databases/";
Context context = getBaseContext();
boolean databaseStatus = checkDataBase( DATABASE_PATH,DATABASE_NAME);
//this will check when app start
if (databaseStatus == false) {
DBAdapter database = new DBAdapter(context);
//here you can call your create table method
//database.createLoginTable();
Log.v("Debug", "Login table created.");
}
else{
Log.v("Debug", "Database already exist");
}
//method to check whether db is already exist or not and returns boolean
private boolean checkDataBase(String databasePath, String databaseName) {
SQLiteDatabase checkDB = null;
try {
checkDB = SQLiteDatabase.openDatabase(databasePath + databaseName,
null, SQLiteDatabase.OPEN_READONLY);
checkDB.close();
Log.v("Debug", "Database exist");
return true;
} catch (SQLiteException e) {
Log.v("Debug", "Database not exist");
}
return false;
}
i hope it will help you!!

You can solve this problem by using SharedPreferences in onCreate() method ,you can limit the insertion of the data (if it is fixed data) only when the app first time executed.This will solve the duplication.
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.splash);
SharedPreferences pref = getSharedPreferences(PREFS_NAME1,MODE_PRIVATE);
boolean first1 = pref.getBoolean(PREF_FIRST1, false);
if(first1!=true)
{
getSharedPreferences(PREFS_NAME1,MODE_PRIVATE)
.edit()
.putBoolean(PREF_FIRST1, true)
.commit();
// insert data here or use Background Task to do that
}
}

Related

How can I add a delete function to my Sqlite Database?

I am building a training log that uses an sqlite database to save what the user inputs. Currently, I only have an add method that appends to the database, but am unsure as to how to create a delete method that removes the row created. The user data is initially created and added in TrainingLogCreate (class), which accesses DBAdapter's (Class) add method. What can I add to my remove method in DBAdapter to be able to remove a user entry?
TrainingLogCreate:
public class TrainingLogCreate extends AppCompatActivity {
EditText nameTxt;
EditText posTxt;
Button savebtn;
Context context = this;
public TrainingLogCreate() {
// Required empty public constructor
}
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.training_log_create);
savebtn = (Button) findViewById(R.id.saveButton);
nameTxt = (EditText) findViewById(R.id.exercizeActivity);
posTxt = (EditText) findViewById(R.id.exercizeDetails);
final DBAdapter db = new DBAdapter(this);
SimpleDateFormat dateFormat = new SimpleDateFormat("MM/dd/yyyy");
String datetime;
try {
Date date = new Date();
datetime = dateFormat.format(date);
} finally {
}
final String dateTxt = datetime;
savebtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
//OPEN
db.openDB();
//INSERT
long result = db.add(nameTxt.getText().toString(), posTxt.getText().toString(), dateTxt.toString());
if (result > 0) {
nameTxt.setText("");
posTxt.setText("");
} else {
Toast.makeText(getApplicationContext(), "Failure", Toast.LENGTH_SHORT).show();
}
//CLOSE DB
db.close();
//Open Fragment
finish();
}
});
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
MenuInflater mif = getMenuInflater();
mif.inflate(R.menu.training_create_menu, menu);
getActionBar().show();
return super.onCreateOptionsMenu(menu);
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// handle item selection
switch (item.getItemId()) {
case R.id.action_save:
//add save functionality
return true;
default:
return super.onOptionsItemSelected(item);
}
}
}
DBAdapter:
public class DBAdapter {
//COLUMNS
static final String ROWID="id";
static final String NAME = "name";
static final String POSITION = "position";
static final String DATE = "date";
//DB PROPERTIES
static final String DBNAME="m_DB";
static final String TBNAME="m_TB";
static final int DBVERSION='1';
static final String CREATE_TB="CREATE TABLE m_TB(id INTEGER PRIMARY KEY AUTOINCREMENT,"
+ "name TEXT NOT NULL,position TEXT NOT NULL,date TEXT NOT NULL);";
final Context c;
SQLiteDatabase db;
DBHelper helper;
public DBAdapter(FragmentActivity ctx) {
// TODO Auto-generated constructor stub
this.c=ctx;
helper=new DBHelper(c);
}
// INNER HELPER DB CLASS
private static class DBHelper extends SQLiteOpenHelper
{
public DBHelper(Context context ) {
super(context, DBNAME, null, DBVERSION);
// TODO Auto-generated constructor stub
}
#Override
public void onCreate(SQLiteDatabase db) {
try
{
db.execSQL(CREATE_TB);
} catch (SQLException e) {
e.printStackTrace();
}
}
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
// TODO Auto-generated method stub
Log.w("DBAdapetr","Upgrading DB");
db.execSQL("DROP TABLE IF EXISTS m_TB");
onCreate(db);
}
}
// OPEN THE DB
public DBAdapter openDB()
{
try
{
db=helper.getWritableDatabase();
}catch(SQLException e)
{
Toast.makeText(c, e.getMessage(), Toast.LENGTH_LONG).show();
}
return this;
}
//CLOSE THE DB
public void close()
{
helper.close();
}
//INSERT INTO TABLE
public long add(String name,String pos, String date)
{
try
{
ContentValues cv=new ContentValues();
cv.put(NAME, name);
cv.put(POSITION, pos);
cv.put(DATE, date);
return db.insert(TBNAME, ROWID, cv);
}catch(SQLException e)
{
e.printStackTrace();
}
return 0;
}
//REMOVE FROM TABLE
public long remove(String name)
{
}
//GET ALL VALUES
public Cursor getAllNames()
{
String[] columns={ROWID,NAME,POSITION,DATE};
return db.query(TBNAME, columns, null, null, null, null, null);
}
}
You can have a delete method like this
public void deleteInterestId(int id) {
SQLiteDatabase db = this.getWritableDatabase();
db.delete(TABLE_TIMEKEEPER, KEY_ID + "=?", new String[]{String.valueOf(id)});
db.close();
}
You have to pass the id which you want to delete. You have to customize this method a bit but it will give you an idea
And the most important thing for delete is that you have to also create a column named id and increase it's value as record are inserted. Because you can't delete on base of id that is created automatically by database

Android Studio App Crash from Sqlite database

I'm hoping my question isn't too broad. What I would really like to know is how to tell exactly where my code is hitting a wall.
I'm not getting errors from my debugger, the app just crashes when the emulator starts an activity that uses a sqlite database (3rd activity in). I am positive it is the addition of sqlite into my code that causes the crash because it ran before I added it.
This code simply needs to access and read from an external database that I created and pasted into the assets folder. I reviewed the sqlite database in firefox's SQLite Manager; the information seems to be formatted correctly.
I created an assets folder within app/src/Main to facilitate the addition of the external database "ex3.db". Then I copied and pasted the database file there.
So here is the code. LetterImage is a class that holds strings retrieved from the sqlite database. MyDBHandler creates an empty database, copies the old one into it, and fills LetterImage with the values returned from a query based on a string. LoadSubjectActivity calls them both to search the database and return a string.
LetterImage:
public class LetterImage {
private Integer _ID;
private String _letter;
private String _bigfilename;
private String _littlefilename;
//Constructor(s)
public LetterImage(){
}
public LetterImage(Integer ID, String letter, String bigfilename, String littlefilename){
this._ID = ID;
this._letter = letter;
this._bigfilename = bigfilename;
this._littlefilename = littlefilename;
}
public LetterImage(String letter){
this._letter = letter;
}
//End Constructors
//Begin setters and getters
//ID is primary key
public void setID(Integer ID){
this._ID = ID;
}
public Integer getID(){
return this._ID;
}
//letter is main identifier used to search database
// passed to LoadSubjectActivity
// from ChooseSubjectABCActivity as extra from intent
public void setLetter(String letter){
this._letter = letter;
}
public String getLetter(){
return this._letter;
}
//Capital letter image file name
public void setBigFileName(String bigfilename){
this._bigfilename = bigfilename;
}
public String getBigFileName(){
return this._bigfilename;
}
//Lowercase Letter image file name
public void setLittleFileName(String littlefilename){
this._littlefilename = littlefilename;
}
public String getLittleFileName(){
return this._littlefilename;
}
}
Now, here is MyDBHandler:
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteException;
import android.database.sqlite.SQLiteOpenHelper;
import android.content.Context;
import android.database.Cursor;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.sql.SQLException;
public class MyDBHandler extends SQLiteOpenHelper{
private final Context myContext;
private static Context context;
private static final int DATABASE_VERSION = 1;
private static String DB_PATH = "data/data" + context.getPackageName() + "/databases/";
private static final String DATABASE_NAME = "ex3.db";
public static final String TABLE_IMAGES = "tbl1";
private SQLiteDatabase myDataBase;
//Fields in Database
public static final String COLUMN_ID = "_id";
public static final String COLUMN_BIGIMAGEFILE = "bigImage";
public static final String COLUMN_LITTLEIMAGEFILE = "littleImage";
public static final String COLUMN_LETTER = "letter";
//Constructor
public MyDBHandler(Context context) {
super(context, DATABASE_NAME, null, DATABASE_VERSION);
this.myContext = context;
}
//if there is no existing database, create an empty one
public void createDatabase() throws IOException{
boolean dbExist = checkDataBase();
if(dbExist) {
//do nothing
}else {
//call this method and create an empty database
this.getReadableDatabase();
try {
copyDataBase();
} catch(IOException e){
throw new Error("Error copying database");
}
}
}
//check to see if there is an existing database
private boolean checkDataBase(){
SQLiteDatabase checkDB = null;
try{
String myPath = DB_PATH + DATABASE_NAME;
checkDB = SQLiteDatabase.openDatabase(myPath, null, SQLiteDatabase.OPEN_READONLY);
} catch (SQLiteException e){
throw new Error("Unable to open database");
}
if(checkDB != null){
checkDB.close();
}
return checkDB != null ? true : false;
}
//fills new empty database with existing database ex3
private void copyDataBase() throws IOException{
InputStream myInput = myContext.getAssets().open(DATABASE_NAME);
String outFileName = DB_PATH + DATABASE_NAME;
OutputStream myOutput = new FileOutputStream(outFileName);
byte[] buffer = new byte[1024];
int length;
while ((length = myInput.read(buffer))>0){
myOutput.write(buffer, 0, length);
}
myOutput.flush();
myOutput.close();
myInput.close();
}
//opens the new database
public void openDatabase() throws SQLException {
String myPath = DB_PATH + DATABASE_NAME;
myDataBase = SQLiteDatabase.openDatabase(myPath, null, SQLiteDatabase.OPEN_READONLY);
}
#Override
public synchronized void close(){
if(myDataBase != null)
myDataBase.close();
super.close();
}
#Override
public void onCreate(SQLiteDatabase db){
}
#Override
public void onUpgrade(SQLiteDatabase db, int OldVersion, int newVersion){
}
//creates an instance of letter LetterImage
//queries the new database by searching for the row with where the value of COLUMN_LETTER = letter
//fills LetterImage with the values from that row
public LetterImage findLetter(String letter) {
String query = "Select * FROM " + TABLE_IMAGES + " WHERE " + COLUMN_LETTER + " = \"" + letter + "\"";
SQLiteDatabase db = this.getWritableDatabase();
Cursor cursor = db.rawQuery(query, null);
LetterImage LetterImage = new LetterImage();
if (cursor.moveToFirst()) {
cursor.moveToFirst();
LetterImage.setID(Integer.parseInt(cursor.getString(0)));
LetterImage.setBigFileName(cursor.getString(1));
LetterImage.setLittleFileName(cursor.getString(2));
LetterImage.setLetter(cursor.getString(3));
cursor.close();
} else {
LetterImage = null;
}
db.close();
return LetterImage;
}
}
Finally, here are the pertinent parts of the LoadSubjectActivity class:
public class LoadSubjectActivity extends MainActivity{
private DrawingView drawView;
private ImageButton currPaint;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.content_load_subject);
//receives string letter, from last activity
//letter will be used to search array and return files names of the images to be used
Intent intent = getIntent();
String letter = intent.getExtras().getString("letter");
//displayFN calls testDB(letter) to test the database
//It should simply display the string returned by testDB()
TextView displayFN = (TextView)findViewById(R.id.display_filenames);
displayFN.setText(testDB(letter.toLowerCase()));
//Eventually, button images will be filled dynamically
ImageButton bigLetter = (ImageButton)findViewById(R.id.big_letter);
ImageButton littleLetter = (ImageButton)findViewById(R.id.little_letter);
bigLetter.setImageResource(R.drawable.biga);
littleLetter.setImageResource(R.drawable.littlea);
drawView = (DrawingView)findViewById(R.id.drawing);
LinearLayout paintLayout = (LinearLayout)findViewById(R.id.paint_colors);
currPaint = (ImageButton)paintLayout.getChildAt(0);
currPaint.setImageDrawable(ContextCompat.getDrawable(this, R.drawable.paint_pressed));
}
//Function to test the database takes a string as an argument to search the database
public String testDB(String letter){
//create a new instance of dbHandler
MyDBHandler dbHandler = new MyDBHandler(this);
//try to either create an empty database or open the existing one
try{
dbHandler.createDatabase();
} catch (IOException ioe){
throw new Error("Unable to create database");
}
try{
dbHandler.openDatabase();
} catch(SQLException sqle){
sqle.printStackTrace();
throw new Error ("unable to open database");
}
LetterImage letterImage = dbHandler.findLetter(letter);
String blFileName = letterImage.getBigFileName();
//return the big letter image file name;
return blFileName;
}
Anyway, I apologize in advance for any obvious problems. I have traced the logic to the best of my ability...I am teaching myself java and sql...this is my first android project. Any and all insight is greatly appreciated.
I figured out one way to fix this:
1.) rewrite checkDatabase(). I referenced this tutorial: How to use an existing database with an Android application, and found this:
private boolean checkDataBase(){
File dbFile = new File(DB_PATH + DATABASE_NAME);
//Log.v("dbFile", dbFile + " "+ dbFile.exists());
return dbFile.exists();
}
2.) Hard code DB_PATH name, since context.getFilesDir and getDatabasePath() weren't returning the paths I needed.
***going through logcat and tracing the errors back to the exact place the problem started was how I found what I needed to change. In this instance, checkDatabase() wasn't returning false to createDatabase(), so the code was trying to open a database that didn't exist.

Error while compliling DROP IF EXISTS , syntax error near table Android SQLite

I am trying to make a small program that contains two EditTexts for user to enter his name and his password and a button which adds them in a table using SQLite in Android,
but I got that message by my SQLException :
android.database.sqlite.SQLiteException:near "table":syntax error (code1):,while compiling: DROP TABLE IF EXISTS
and in my logcat this line appear : (1) near "table" : syntax error
and I can't figure out where the problem
Here is my code :
package com.example.database;
import android.content.ContentValues;
import android.content.Context;
import android.database.SQLException;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteDatabase.CursorFactory;
import android.database.sqlite.SQLiteOpenHelper;
public class DataBaseAdapter {
Helper helper ;
public DataBaseAdapter(Context context){
helper = new Helper ( context);
}
public long insertData (String name , String password)
{
SQLiteDatabase db = helper.getWritableDatabase();
ContentValues contenValues = new ContentValues ();
contenValues.put(Helper.NAME, name);
contenValues.put(Helper.PASSWORD, password);
long id = db.insert(Helper.TABEL_NAME, null, contenValues);
return id ;
}
static class Helper extends SQLiteOpenHelper {
private static final String DATABSE_NAME = "myDataBase";
private static final String TABEL_NAME = "table";
private static final int DATABASE_VERSION = 10;
public static final String NAME = "Name";
public static final String PASSWORD = "password";
private static final String CREATE_TABLE = "CREATE TABLE "+TABEL_NAME+" (_id INTEGER PRIMARY KEY AUTOINCREMENT , "+NAME+" TEXT not null , "+PASSWORD+" TEXT not null)";
private Context context;
private static final String DROP_TABLE = "DROP TABLE IF EXISTS " + TABEL_NAME;
public Helper(Context context) {
super(context, DATABSE_NAME, null, DATABASE_VERSION);
// TODO Auto-generated constructor stub
this.context = context;
Message.message(context, "constructor called");
}
#Override
public void onCreate(SQLiteDatabase db) {
// CREATE DATABSE
try {
db.execSQL(CREATE_TABLE);
Message.message(context, "OnCreate called");
} catch (SQLException e) {
// TODO Auto-generated catch block
Message.message(context, "" + e);
}
}
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
try {
db.execSQL(DROP_TABLE);
Message.message(context, "onUpgrade called");
onCreate(db);
} catch (SQLException e) {
// TODO Auto-generated catch block
Message.message(context, "" + e);
}
}
}
}
and in the MainActivity
public class MainActivity extends Activity {
EditText userName, password;
DataBaseAdapter helper;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
helper = new DataBaseAdapter(this);
userName = (EditText) findViewById(R.id.userText);
password = (EditText) findViewById(R.id.passText);
}
public void addUser(View view) {
String user = userName.getText().toString();
String pass = password.getText().toString();
long id = helper.insertData(user, pass);
if ( id <0 )
{
Message.message(this, "fail");
} else {
Message.message(this, "Suceeded");
}
}
}
You can't create (nor do any other operation) a table named... table, because table is a reserved word in SQLite (and in SQL in general).
Since the table is not created, it can't be deleted.
Try calling it myTable (or possibly a more significant name), such as the element name (normally, in its plural form: i.e.: Persons, Contacts, Animals, Orders, ...)
Try putting table in single quotes and using semicolon in the end of the statement, like this:
private static final String TABEL_NAME = "table";
private static final String DROP_TABLE = "DROP TABLE IF EXISTS '" + TABEL_NAME + "';";

How to check whether the table has been created and how to get the values from a radiobutton and a spinner using SQlite?

I'm Developing an android app in which there are Login activity and a Questionnaire activity contains Questions which as radio Buttons and also a Button(Next).So now I wanted to create a database to store the values of the respective fields. I've typed the code for dataHandler and Login.java now the problem is i wanted to know whether the table has been created and also how to view my table please help me and also please check whether my code is correct.
Thanks in Advance.
Here is code for the DatabaseAdapter.java
public class DatabaseAdapter {
DatabaseHandler dbhandler;
public DatabaseAdapter(Context context){
dbhandler =new DatabaseHandler(context);
}
public long insertData(String name,String desig,String years,String dept)
{
SQLiteDatabase db=dbhandler.getWritableDatabase();
ContentValues content=new ContentValues();
content.put(DatabaseHandler.NAME, name);
content.put(DatabaseHandler.DESIGNATION,desig);
content.put(DatabaseHandler.YEARS, years);
content.put(DatabaseHandler.DEPARTMENT, dept);
long id=db.insertOrThrow(DatabaseHandler.TABLE_NAME, null, content);
return id;
}
static class DatabaseHandler extends SQLiteOpenHelper {
private static final String NAME="name";
private static final String DESIGNATION="desig";
private static final String YEARS="years";
private static final String DEPARTMENT="dept";
private static final String TABLE_NAME="visteon";
private static final String DATA_BASE_NAME="VisteonSurvey";
private static final int DATABASE_VERSION=2;
private static final String CREATE_TABLE="CREATE TABLE "+TABLE_NAME+"("+NAME+" VARCHAR(255),"+DESIGNATION+"text not null,"+YEARS+" text not null,"+DEPARTMENT+" text not null);";
public DatabaseHandler(Context context)
{
super(context,DATA_BASE_NAME,null,DATABASE_VERSION);
}
#Override
public void onCreate(SQLiteDatabase db) {
try{
db.execSQL(CREATE_TABLE);
}
catch(SQLException e)
{
e.printStackTrace();
}
}
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
try {
db.execSQL("DROP TABLE IF EXISTS visteon");
onCreate(db);
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
Here is code for Login.java
public void OnClickListener(View v)
{
name=(EditText)findViewById(R.id.editText1);
years1=(RadioButton)findViewById(R.id.radioButton3);
years2=(RadioButton)findViewById(R.id.radioButton4);
years3=(RadioButton)findViewById(R.id.radioButton5);
manager=(RadioButton)findViewById(R.id.radioButton1);
teamleader=(RadioButton)findViewById(R.id.radioButton2);
rg1=(RadioGroup)findViewById(R.id.Designation);
rg2=(RadioGroup)findViewById(R.id.Years);
dept=(Spinner)findViewById(R.id.spinner1);
proceed = (Button)findViewById(R.id.button1);
proceed.setOnClickListener(new View.OnClickListener()
{
#Override
public void onClick(View v)
{
if (validationSuccess())
{
if(manager.isChecked())
{
Intent managerIntent = new Intent(getApplicationContext(), ManagerQuestionnaire1.class); // <----- START "SEARCH" ACTIVITY
startActivityForResult(managerIntent, 0);
}
else
{
Intent teamleaderIntent = new Intent(getApplicationContext(), TeamleaderQuestionnaire1.class); // <----- START "TYPE ENTRIES OUT" ACTIVITY
startActivityForResult(teamleaderIntent, 0);
}
}
else {
AlertDialog();
}
String user=name.getText().toString();
String designation=rg1.getContext().toString();
String experience=rg2.getContext().toString();
String department=dept.getContext().toString();
long id= DatabaseHandler.insertData (user, designation, experience, department);
Toast.makeText(getBaseContext(),"Form Updated",Toast.LENGTH_LONG).show();
}
});

Android sqlite problem

I read several tutorials and the sqlite section in a book and applied it which works great. Now I messed with it to try and understand it but now it will just force close every single time and i'm not sure why. I've been over my code again and again but maybe I can't find the problem because i'm new to sqlite/databases in general. Any help would be appreciated:
public class Events extends Activity {
private TextView tv;
private DataHelper dh;
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
tv = new TextView(this);
dh = new DataHelper(this);
dh.deleteAll();
//dh.addEvent("James");
//Cursor c = dh.getEvent();
//startManagingCursor(c);
//tv.setText(dh.showEvent(c));
setContentView(tv);
}
}
public class EventsData extends SQLiteOpenHelper {
private static final String DATABASE_NAME = "events.db";
private static final int DATABASE_VERSION = 1;
private static final String DATABASE_CREATE = "CREATE TABLE" + TABLE_NAME + "(" + TITLE + " TEXT)";
private static final String DATABASE_UPGRADE = "DROP TABLE IF EXISTS " + TABLE_NAME;
public EventsData(Context context) {
super(context, DATABASE_NAME, null, DATABASE_VERSION);
}
#Override
public void onCreate(SQLiteDatabase db) {
// TODO Auto-generated method stub
db.execSQL(DATABASE_CREATE);
}
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
// TODO Auto-generated method stub
db.execSQL(DATABASE_UPGRADE);
onCreate(db);
}
}
public class DataHelper {
private Context context;
private SQLiteDatabase db;
private EventsData eventsData;
public DataHelper(Context context) {
this.context = context;
eventsData = new EventsData(this.context);
}
public void addEvent(String name) {
db = eventsData.getWritableDatabase();
ContentValues cv = new ContentValues();
cv.put(TITLE, name);
db.insertOrThrow(TABLE_NAME, null, cv);
}
}
Commenting out addEvent() will run the app fine but once I uncomment it, it force closes.
Fast shot: There's no space after CREATE TABLE.
You can check the logcat for the error message. It will tell you what is causing the force close. Link to debugging using logcat Debugging in Android using Eclipse

Categories