How to save database in Android? - java

I'm new to android development and I'm trying to make a simple application where i can add and view my records. I can successfully add data and view them in a table, it works ever time i run the program. (I'm following this tutorial) But every time i close Eclipse and try to add new data and view them, the previous information I entered was gone. it seems like when I close eclipse, it doesn't save my database. Here is the sample code I'm following.
package com.example.hotornot;
import java.sql.Statement;
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 Example {
public static final String KEY_ROWID = "id";
public static final String KEY_NAME = "name";
public static final String KEY_NUM = "number";
public static final String DATABASE_NAME = "dbTry";
public static final String DATABASE_TABLE = "tblSamp";
public static final int DATABASE_VERSION = 1;
public DbHelper ourhelper;
public final Context ourcontext;
public SQLiteDatabase ourdatabase;
class DbHelper extends SQLiteOpenHelper{
public DbHelper(Context context) {
super(context, DATABASE_NAME, null, DATABASE_VERSION);
// TODO Auto-generated constructor stub
}
#Override
public void onCreate(SQLiteDatabase arg0) {
// TODO Auto-generated method stub
arg0.execSQL("CREATE TABLE " + DATABASE_TABLE + " (" + KEY_ROWID + " INTEGER, " + KEY_NAME + " NULL, " + KEY_NUM + " NULL);");
}
#Override
public void onUpgrade(SQLiteDatabase arg0, int arg1, int arg2) {
// TODO Auto-generated method stub
arg0.execSQL("DROP TABLE IF EXIST " + DATABASE_TABLE);
onCreate(arg0);
}
}
public Example(Context c)
{
ourcontext = c;
}
public Example open() throws SQLException
{
ourhelper = new DbHelper(ourcontext);
ourdatabase = ourhelper.getWritableDatabase();
return this;
}
public void close()
{
ourhelper.close();
}
public long createEntry(String name, String num)
{
// TODO Auto-generated method stub
ContentValues cv = new ContentValues();
cv.put(KEY_NAME, name);
cv.put(KEY_NUM, num);
return ourdatabase.insert(DATABASE_TABLE, null, cv);
}
public String getData()
{
// TODO Auto-generated method stub
String[] columns = new String[]{ KEY_ROWID,KEY_NAME, KEY_NUM};
Cursor c = ourdatabase.query(DATABASE_TABLE, columns, null, null, null, null, null);
String result = "";
int iRow = c.getColumnIndex(KEY_ROWID);
int iName = c.getColumnIndex(KEY_NAME);
int iNum = c.getColumnIndex(KEY_NUM);
for (c.moveToFirst(); ! c.isAfterLast(); c.moveToNext()){
result = result + c.getString(iRow) + " " +c.getString(iName) + " " + c.getString(iNum) + "\n";
}
return result;
}
}

You must be overwriting the existing database or uninstalling the app
please check your code
on Activity onCreate event check for the existence of db file if exist do not overwrite and skip the process definitely you will get the old records

Related

Can't find SQL column in android project

I have two classes:
Database class:
package com.qstra.soamazingtodoapp;
import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
import android.util.Log;
public class DBAdapter {
private static final String TAG = "DBAdapter"; // used for logging database
// version changes
// Field Names:
public static final String KEY_ROWID = "_id";
public static final String KEY_TASK = "task";
public static final String KEY_DATE = "date";
public static final String KEY_HOUR = "hour";
public static final String KEY_MINUTE = "minute";
public static final String[] ALL_KEYS = new String[] { KEY_ROWID, KEY_TASK,
KEY_DATE, KEY_HOUR, KEY_MINUTE };
// Column Numbers for each Field Name:
public static final int COL_ROWID = 0;
public static final int COL_TASK = 1;
public static final int COL_DATE = 2;
public static final int COL_HOUR = 3;
public static final int COL_MINUTE = 4;
// DataBase info:
public static final String DATABASE_NAME = "dbToDo";
public static final String DATABASE_TABLE = "mainToDo";
public static final int DATABASE_VERSION = 2; // The version number must be
// incremented each time a
// change to DB structure
// occurs.
// SQL statement to create database
private static final String DATABASE_CREATE_SQL = "CREATE TABLE "
+ DATABASE_TABLE + " (" + KEY_ROWID
+ " INTEGER PRIMARY KEY AUTOINCREMENT, " + KEY_TASK
+ " TEXT NOT NULL, " + KEY_DATE + " TEXT" + KEY_HOUR + " TEXT"
+ KEY_MINUTE + " TEXT" + ");";
private final Context context;
private DatabaseHelper myDBHelper;
private SQLiteDatabase db;
public DBAdapter(Context ctx) {
this.context = ctx;
myDBHelper = new DatabaseHelper(context);
}
// Open the database connection.
public DBAdapter open() {
db = myDBHelper.getWritableDatabase();
return this;
}
// Close the database connection.
public void close() {
myDBHelper.close();
}
// Add a new set of values to be inserted into the database.
public long insertRow(String task, String date, String hour, String minute) {
ContentValues initialValues = new ContentValues();
initialValues.put(KEY_TASK, task);
initialValues.put(KEY_DATE, date);
initialValues.put(KEY_HOUR, hour);
initialValues.put(KEY_MINUTE, minute);
// Insert the data into the database.
return db.insert(DATABASE_TABLE, null, initialValues);
}
// Delete a row from the database, by rowId (primary key)
public boolean deleteRow(long rowId) {
String where = KEY_ROWID + "=" + rowId;
return db.delete(DATABASE_TABLE, where, null) != 0;
}
public void deleteAll() {
Cursor c = getAllRows();
long rowId = c.getColumnIndexOrThrow(KEY_ROWID);
if (c.moveToFirst()) {
do {
deleteRow(c.getLong((int) rowId));
} while (c.moveToNext());
}
c.close();
}
// Return all data in the database.
public Cursor getAllRows() {
String where = null;
Cursor c = db.query(true, DATABASE_TABLE, ALL_KEYS, where, null, null,
null, null, null);
if (c != null) {
c.moveToFirst();
}
return c;
}
// Get a specific row (by rowId)
public Cursor getRow(long rowId) {
String where = KEY_ROWID + "=" + rowId;
Cursor c = db.query(true, DATABASE_TABLE, ALL_KEYS, where, null, null,
null, null, null);
if (c != null) {
c.moveToFirst();
}
return c;
}
// Change an existing row to be equal to new data.
public boolean updateRow(long rowId, String task, String date, String hour, String minute) {
String where = KEY_ROWID + "=" + rowId;
ContentValues newValues = new ContentValues();
newValues.put(KEY_TASK, task);
newValues.put(KEY_DATE, date);
newValues.put(KEY_HOUR, hour);
newValues.put(KEY_MINUTE, minute);
// Insert it into the database.
return db.update(DATABASE_TABLE, newValues, where, null) != 0;
}
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_SQL);
}
#Override
public void onUpgrade(SQLiteDatabase _db, int oldVersion, int newVersion) {
Log.w(TAG, "Upgrading application's database from version "
+ oldVersion + " to " + newVersion
+ ", which will destroy all old data!");
// Destroy old database:
_db.execSQL("DROP TABLE IF EXISTS " + DATABASE_TABLE);
// Recreate new database:
onCreate(_db);
}
}
}
MainActivity class:
package com.qstra.soamazingtodoapp;
import com.qstratwo.soamazingtodoapp.R;
import android.app.Activity;
import android.app.Dialog;
import android.app.TimePickerDialog;
import android.database.Cursor;
import android.os.Bundle;
import android.text.TextUtils;
import android.text.format.Time;
import android.view.View;
import android.widget.AdapterView;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.SimpleCursorAdapter;
import android.widget.TimePicker;
import android.widget.Toast;
public class MainActivity extends Activity {
Time today = new Time(Time.getCurrentTimezone());
DBAdapter myDb;
EditText etTasks;
static final int DIALOG_ID = 0;
int hour_x;
int minute_x;
String string_hour_x, string_minute_x="None";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
etTasks = (EditText) findViewById(R.id.editText1);
openDB();
listViewItemClick();
listViewItemLongClick();
populateListView();
// setNotification();
}
#Override
protected Dialog onCreateDialog(int idD){
if (idD== DIALOG_ID){
return new TimePickerDialog(MainActivity.this, kTimePickerListener, hour_x,minute_x, false);
}
return null;
}
protected TimePickerDialog.OnTimeSetListener kTimePickerListener =
new TimePickerDialog.OnTimeSetListener() {
#Override
public void onTimeSet(TimePicker view, int hourOfDay, int minute) {
hour_x=hourOfDay;
minute_x=minute;
string_hour_x = Integer.toString(hour_x);
string_minute_x = Integer.toString(minute_x);
Toast.makeText(MainActivity.this, hour_x+" : "+ minute_x,Toast.LENGTH_LONG).show();
}
};
public void setNotification(View v) {
showDialog(DIALOG_ID);
}
private void openDB() {
myDb = new DBAdapter(this);
myDb.open();
}
public void onClick_AddTask (View v) {
today.setToNow();
String timestamp = today.format("%Y-%m-%d %H:%m:%s");
if(!TextUtils.isEmpty(etTasks.getText().toString())) {
myDb.insertRow(etTasks.getText().toString(),timestamp,string_hour_x, string_minute_x);
}
populateListView();
}
private void populateListView() {
Cursor cursor = myDb.getAllRows();
String[] fromFieldNames=new String[] {
DBAdapter.KEY_ROWID, DBAdapter.KEY_TASK };
int[] toViewIDs = new int[] {
R.id.textViewItemNumber, R.id.textViewItemTasks};
SimpleCursorAdapter myCursorAdapter;
myCursorAdapter = new SimpleCursorAdapter(getBaseContext(), R.layout.item_layout, cursor, fromFieldNames, toViewIDs, 0);
ListView myList = (ListView) findViewById(R.id.listViewTask);
myList.setAdapter(myCursorAdapter);
}
private void updateTask(long id){
Cursor cursor = myDb.getRow(id);
if (cursor.moveToFirst()){
String task = etTasks.getText().toString(); // POBIERANIE Z TEXTFIELD
today.setToNow();
String date = today.format("%Y-%m-%d %H:%m");
// String string_minute_x= Integer.toString(minute_x);
// String string_houte_x=Integer.toString(hour_x);
myDb.updateRow(id, task, date, string_hour_x, string_minute_x );
}
cursor.close();
}public void onClick_DeleteTasks(View v) {
myDb.deleteAll();
populateListView();
}
public void onClick_AppClose(View v) {
moveTaskToBack(true);
MainActivity.this.finish();
}
public void listViewItemLongClick(){
ListView myList = (ListView) findViewById(R.id.listViewTask);
myList.setOnItemLongClickListener(new AdapterView.OnItemLongClickListener() {
#Override
public boolean onItemLongClick(AdapterView<?> arg0, View arg1,
int arg2, long id) {
// TODO Auto-generated method stub
myDb.deleteRow(id);
populateListView();
return false;
}
});
}
private void listViewItemClick(){
ListView myList = (ListView) findViewById(R.id.listViewTask);
myList.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> arg0, View arg1, int arg2, long id) {
updateTask(id);
populateListView();
displayToast(id);
}
});
}
private void displayToast(long id){
Cursor cursor = myDb.getRow(id);
if(cursor.moveToFirst()) {
long idDB = cursor.getLong(DBAdapter.COL_ROWID);
String task = cursor.getString(DBAdapter.COL_TASK);
String date = cursor.getString(DBAdapter.COL_DATE);
String message = "ID: " + idDB + "\n" + "Task: " + task + "\n" + "Date: " + date;
Toast.makeText(MainActivity.this, message, Toast.LENGTH_LONG).show();
}
cursor.close();
}
}
(getting id and text from texfield to database works fine but..)
I'm trying to get hour and minutes values from TimePickerDialog and insert in to database but it seems not working.
Screen shot from log cat:
Why can't it see column named 'hour'?
Add commas in your statement to create database
// SQL statement to create database
private static final String DATABASE_CREATE_SQL = "CREATE TABLE "
+ DATABASE_TABLE + " (" + KEY_ROWID
+ " INTEGER PRIMARY KEY AUTOINCREMENT, " + KEY_TASK
+ " TEXT NOT NULL, " + KEY_DATE + " TEXT," + KEY_HOUR + " TEXT,"
+ KEY_MINUTE + " TEXT" + ")";

Multiple Tables In SQlite android

I wanna make a database in sqlite android ,and I wanna create 2 table in database ,and after that I wanna create tables dynamically. but my class DBAdapter just create one table and for other tables throws error "no such table" so what should I do for this? plz help me
package com.example.asa;
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 DBAdapter {
public static final String KEY_ROWID_con = "_id";
public static final String KEY_NAME_con = "name";
public static final String KEY_NUMBER_con = "number";
private static final String TAG = "DBAdapter";
private static final String DATABASE_TABLE_con = "contacts";
private static final String DATABASE_NAME = "MyDB";
private static final int DATABASE_VERSION = 2;
private static final String DATABASE_CREATE_con =
"create table contacts (_id integer primary key autoincrement, "
+ "name text not null, number text not null);";
private final Context context;
private DatabaseHelper DBHelper;
private SQLiteDatabase db;
public DBAdapter(Context ctx)
{
this.context = ctx;
DBHelper = new DatabaseHelper(context);
}
private static class DatabaseHelper extends SQLiteOpenHelper
{
DatabaseHelper(Context context)
{
super(context, DATABASE_NAME, null, DATABASE_VERSION);
}
#Override
public void onCreate(SQLiteDatabase db)
{
try {
db.execSQL(DATABASE_CREATE_con);
} catch (SQLException e) {
e.printStackTrace();
}
}
#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 chats");
onCreate(db);
}
}
//---opens the database---
public DBAdapter open() throws SQLException
{
db = DBHelper.getWritableDatabase();
return this;
}
//---closes the database---
public void close()
{
DBHelper.close();
}
//---insert a contact into the database---
public long insertContact(String name, String number)
{
ContentValues initialValues = new ContentValues();
initialValues.put(KEY_NAME_con, name);
initialValues.put(KEY_NUMBER_con, number);
return db.insert(DATABASE_TABLE_con, null, initialValues);
}
//---deletes a particular contact---
public boolean deleteContact(long rowId)
{
return db.delete(DATABASE_TABLE_con, KEY_ROWID_con + "=" + rowId, null) > 0;
}
//---retrieves all the contacts---
public Cursor getAllContacts()
{
return db.query(DATABASE_TABLE_con, new String[] {KEY_ROWID_con, KEY_NAME_con,
KEY_NUMBER_con}, null, null, null, null, null);
}
//---retrieves a particular contact---
public Cursor getContact(long rowId) throws SQLException
{
Cursor mCursor =
db.query(true, DATABASE_TABLE_con, new String[] {KEY_ROWID_con,
KEY_NAME_con, KEY_NUMBER_con}, KEY_ROWID_con + "=" + rowId, null,
null, null, null, null);
if (mCursor != null) {
mCursor.moveToFirst();
}
return mCursor;
}
//---updates a contact---
public boolean updateContact(long rowId, String name, String number)
{
ContentValues args = new ContentValues();
args.put(KEY_NAME_con, name);
args.put(KEY_NUMBER_con, number);
return db.update(DATABASE_TABLE_con, args, KEY_ROWID_con + "=" + rowId, null) > 0;
}
//---Search Contact by String ---//
public String Search(String str)
{
String [] columns = new String[]{ KEY_ROWID_con, KEY_NAME_con, KEY_NUMBER_con};
return db.query(DATABASE_TABLE_con, columns, KEY_NAME_con + "=?", new String[] { str }, null, null, null).getString(0);
}
//---insert a contact into the database---
}
try this.I was having the same problem and this solved it--
package db;
import java.util.ArrayList;
import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
public class DB_Handler_exercise extends SQLiteOpenHelper {
private static final String DATABASE_NAME = "exercise_items";
private static final int DATABASE_VERSION = 1;
//table name
private static final String TABLE_EXERCISE_TOP = "exercise_top";
private static final String TABLE_EXERCISE_BOTTOM = "exercise_bottom";
private static final String TABLE_EXERCISE_CARDIO = "exercise_cardio";
private static final String TABLE_EXERCISE_VARIATIONS= "exercise_variations";
//column name
private static final String KEY_EX_ID = "ex_id";
private static final String KEY_EX_NAME = "ex_name";
private static final String KEY_EX_NICKNAME = "ex_nickname";
private static final String KEY_NO_VARIATION = "ex_variation";
private static final String KEY_MAIN_ID = "main_id";
private static final String KEY_VARIATION_ID = "v_id";
private static final String KEY_EX_VARIATION_NAME = "ex_variation_name";
private static final String KEY_EX_VARIATION_STEPS= "ex_variation_steps";
private static final String KEY_EX_VARIATION_PHOTOS = "ex_variation_photos";
public DB_Handler_exercise(Context context) {
super(context, DATABASE_NAME, null, DATABASE_VERSION);
// TODO Auto-generated constructor stub
}
#Override
public void onDowngrade(SQLiteDatabase db, int oldVersion, int newVersion) {
// TODO Auto-generated method stub
super.onDowngrade(db, oldVersion, newVersion);
}
#Override
public void onCreate(SQLiteDatabase db) {
// TODO Auto-generated method stub
//create table exercise_top
String CREATE_TABLE_TOP="CREATE TABLE IF NOT EXISTS "+TABLE_EXERCISE_TOP + "(" + KEY_EX_ID + " INTEGER PRIMARY KEY," + KEY_EX_NAME + " TEXT," + KEY_EX_NICKNAME + " TEXT," + KEY_NO_VARIATION + " INTEGER" + ")";
db.execSQL(CREATE_TABLE_TOP);
//create table exercise_bottom
String CREATE_TABLE_BOTTOM="CREATE TABLE IF NOT EXISTS " + TABLE_EXERCISE_BOTTOM+ "(" + KEY_EX_ID + " INTEGER PRIMARY KEY," + KEY_EX_NAME + " TEXT," +KEY_EX_NICKNAME + " TEXT," + KEY_NO_VARIATION + " INTEGER" +")";
db.execSQL(CREATE_TABLE_BOTTOM);
//create table exercise_cardio
String CREATE_TABLE_CARDIO="CREATE TABLE IF NOT EXISTS "+ TABLE_EXERCISE_CARDIO+ "(" + KEY_EX_ID + " INTEGER PRIMARY KEY," + KEY_EX_NAME + " TEXT," +KEY_EX_NICKNAME + " TEXT," + KEY_NO_VARIATION + " INTEGER" +")";
db.execSQL(CREATE_TABLE_CARDIO);
//create table exercise_variations
String CREATE_TABLE_VARIATION="CREATE TABLE IF NOT EXISTS "+ TABLE_EXERCISE_VARIATIONS+ "(" + KEY_MAIN_ID + " INTEGER ," + KEY_VARIATION_ID + " INTEGER,"+ KEY_EX_NAME+" TEXT,"+ KEY_EX_NICKNAME+" TEXT," + KEY_EX_VARIATION_NAME + " TEXT," +KEY_EX_VARIATION_STEPS + " TEXT," + KEY_EX_VARIATION_PHOTOS + " TEXT" +")";
db.execSQL(CREATE_TABLE_VARIATION);
}
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
// TODO Auto-generated method stub
}
//adding data on table_top
public void addData_top(Table_exercise_top top){
SQLiteDatabase db=getWritableDatabase();
ContentValues values=new ContentValues();
values.put(KEY_EX_ID, top.getEx_id());
values.put(KEY_EX_NAME, top.getEx_name());
values.put(KEY_EX_NICKNAME, top.getEx_nickname());
values.put(KEY_NO_VARIATION, top.getEx_variation());
db.insert(TABLE_EXERCISE_TOP, null, values);
db.close();
}
//adding data on table_bottom
public void addData_bottom(Table_exercise_bottom bottom){
SQLiteDatabase db=getWritableDatabase();
ContentValues values=new ContentValues();
values.put(KEY_EX_ID, bottom.getEx_id());
values.put(KEY_EX_NAME, bottom.getEx_name());
values.put(KEY_EX_NICKNAME, bottom.getEx_nickname());
values.put(KEY_NO_VARIATION, bottom.getEx_variation());
db.insert(TABLE_EXERCISE_BOTTOM, null, values);
db.close();
}
//adding data on table_cardio
public void addData_cardio(Table_exercise_cardio cardio){
SQLiteDatabase db=getWritableDatabase();
ContentValues values=new ContentValues();
values.put(KEY_EX_ID, cardio.getEx_id());
values.put(KEY_EX_NAME, cardio.getEx_name());
values.put(KEY_EX_NICKNAME, cardio.getEx_nickname());
values.put(KEY_NO_VARIATION, cardio.getEx_variation());
db.insert(TABLE_EXERCISE_CARDIO, null, values);
db.close();
}
//adding data on table_variation
public void addData_variation(Table_variation variation){
SQLiteDatabase db=getWritableDatabase();
ContentValues values=new ContentValues();
values.put(KEY_MAIN_ID, variation.getMain_id());
values.put(KEY_VARIATION_ID, variation.getV_id());
values.put(KEY_EX_NAME, variation.getEx_name());
values.put(KEY_EX_NICKNAME, variation.getEx_nickname());
values.put(KEY_EX_VARIATION_NAME, variation.getVariation_name());
values.put(KEY_EX_VARIATION_STEPS, variation.getVariation_steps());
values.put(KEY_EX_VARIATION_PHOTOS, variation.getVariation_photos());
db.insert(TABLE_EXERCISE_VARIATIONS, null, values);
db.close();
}
}

Android Sqlite java.lang.nullpointer exception

I am using SQLite in Android eclipse, however it gives me a java.lang.nullpointerexception in the function createEntry. I tried using Questoid SQLite manager to view the database file and it does show up with the table created. Where's the bug?
public class Transact {
public static final String KEY_ROWID = "_id";
public static final String KEY_TAG = "saved_tag";
private static final String DATABASE_NAME = "MyDatabaseName";
private static final String DATABASE_TABLE = "tagsTable";
private static final int DATABASE_VERSION = 1;
private DbHelper ourHelper;
private final Context ourContext;
private SQLiteDatabase ourDatabase;
private static class DbHelper extends SQLiteOpenHelper{
public DbHelper(Context context){
super(context, DATABASE_NAME, null, DATABASE_VERSION);
}
#Override
public void onCreate(SQLiteDatabase db) {
// TODO Auto-generated method stub
db.execSQL(
"CREATE TABLE " + DATABASE_TABLE + " (" + KEY_ROWID + " INTEGER PRIMARY KEY AUTOINCREMENT, " + KEY_TAG + " TEXT NOT NULL);"
);
}
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
// TODO Auto-generated method stub
db.execSQL("DROP TABLE IF EXISTS " + DATABASE_TABLE);
onCreate(db);
}
}
public Transact(Context c ){
ourContext = c;
}
public Transact open() throws SQLException{
ourHelper = new DbHelper(ourContext);
ourHelper.getWritableDatabase();
return this;
}
public void close(){
ourHelper.close();
}
public long createEntry(String tagword) {
// TODO Auto-generated method stub
ContentValues cv = new ContentValues();
cv.put(KEY_TAG, tagword);
return ourDatabase.insert(DATABASE_TABLE, "", cv);
}
public String getData() {
// TODO Auto-generated method stub
String[] columns = new String[]{KEY_ROWID, KEY_TAG};
Cursor c = ourDatabase.query(DATABASE_TABLE, columns, null, null, null, null, null);
String result = "";
int iRow = c.getColumnIndex(KEY_ROWID);
int iTag = c.getColumnIndex(KEY_TAG);
for(c.moveToFirst();!c.isAfterLast();c.moveToNext()){
result = result + c.getString(iRow) + " " + c.getString(iTag) + "\n";
}
return null;
}
}
Code for the add button from Main.java class:
case R.id.addDB:
boolean doneAdd = true;
try{
String tag = textTag.getText().toString();
Transact entry = new Transact(Main.this);
entry.open();
entry.createEntry(tag);
entry.close();
}catch(Exception e){
String error = e.toString();
Dialog d = new Dialog(this);
d.setTitle("Error");
TextView tv = new TextView(this);
tv.setText(error);
d.setContentView(tv);
d.show();
doneAdd = false;
}finally{
if(doneAdd){
Dialog d = new Dialog(this);
d.setTitle("Addition done");
TextView tv = new TextView(this);
tv.setText("Success");
d.setContentView(tv);
d.show();
}
}
break;
You are using ourDatabase variable without initializing it. So not only insert you will get nullpointerexception everywhere where you are using ourDatabase variable
you can use something like following in constructor.
SQLiteDatabase db = context.openOrCreateDatabase(DATABASE_NAME,
Context.MODE_PRIVATE, null);
used this code in sq light java file
import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
import android.database.sqlite.SQLiteDatabase.CursorFactory;
public class SQLiteAdapter {
Cursor cursor;
public static final String MYDATABASE_NAME = "MY_DATABASE";
public static final String MYDATABASE_TABLE = "MY_TABLE";
public static final int MYDATABASE_VERSION = 2;
public static final String KEY_ID = "_id";
public static final String KEY_CONTENT1 = "Content1";
public static final String KEY_CONTENT2 = "Content2";
public static final String KEY_CONTENT3 = "Content3";
public static final String KEY_CONTENT4 = "Content4";
public static final String KEY_CONTENT5 = "Content5";
public static final String KEY_CONTENT6 = "Content6";
public static final String KEY_CONTENT7 = "Content7";
public static final String KEY_CONTENT8 = "Content8";
public static final String KEY_CONTENT9 = "Content9";
public static final String KEY_CONTENT10 = "Content10";
public static final String KEY_CONTENT11 = "Content11";
public static final String KEY_CONTENT12 = "Content12";
// create table MY_DATABASE (ID integer primary key, Content text not null);
private static final String SCRIPT_CREATE_DATABASE = "create table "
+ MYDATABASE_TABLE + " (" + KEY_ID
+ " integer primary key autoincrement, " + KEY_CONTENT1
+ " text not null, " + KEY_CONTENT2 + " text not null, "
+ KEY_CONTENT3 + " text not null, " + KEY_CONTENT4
+ " text not null, " + KEY_CONTENT5 + " text not null, "
+ KEY_CONTENT6 + " text not null, " + KEY_CONTENT7
+ " text not null, " + KEY_CONTENT8 + " text not null, "
+ KEY_CONTENT9 + " text not null, " + KEY_CONTENT10
+ " text not null, " + KEY_CONTENT11 + " blob not null, "
+ KEY_CONTENT12 + " long not null);";
private SQLiteHelper sqLiteHelper;
private SQLiteDatabase sqLiteDatabase;
private Context context;
public SQLiteAdapter(Context c) {
context = c;
}
public SQLiteAdapter openToRead() throws android.database.SQLException {
sqLiteHelper = new SQLiteHelper(context, MYDATABASE_NAME, null,
MYDATABASE_VERSION);
sqLiteDatabase = sqLiteHelper.getReadableDatabase();
return this;
}
public SQLiteAdapter openToWrite() throws android.database.SQLException {
sqLiteHelper = new SQLiteHelper(context, MYDATABASE_NAME, null,
MYDATABASE_VERSION);
sqLiteDatabase = sqLiteHelper.getWritableDatabase();
return this;
}
public void close() {
sqLiteHelper.close();
}
public class SQLiteHelper extends SQLiteOpenHelper {
public SQLiteHelper(Context context, String name,
CursorFactory factory, int version) {
super(context, name, factory, version);
}
#Override
public void onCreate(SQLiteDatabase db) {
// TODO Auto-generated method stub
db.execSQL("PRAGMA foreign_keys=ON");
db.execSQL(SCRIPT_CREATE_DATABASE);
}
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
// TODO Auto-generated method stub
}

Android - How can i search for information in a SQL Database

I was wondering how i would search for specific information stored into my database. Lets say i wanted to search for the information stored in iName, how would i do so? would i need to do some sort of sql query.
Sorry for such a basic question but im new to the whole android scene . Thank You
package f.s.l;
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.SQLiteDatabase.CursorFactory;
import android.database.sqlite.SQLiteOpenHelper;
public class HotOrNot {
public static final String KEY_ROWID ="_id";
public static final String KEY_NAME ="persons_name";
public static final String KEY_HOTNESS ="persons_hotness";
private static final String DATABASE_NAME ="HotOrNotdb";
private static final String DATABASE_TABLE ="peopleTable";
private static final int DATABASE_VERSION =1;
private DbHelper ourHelper;
private final Context ourContext;
private SQLiteDatabase ourDatabase;
private static class DbHelper extends SQLiteOpenHelper{
public DbHelper(Context context) {
super(context, DATABASE_NAME, null, DATABASE_VERSION);
// TODO Auto-generated constructor stub
}
#Override
public void onCreate(SQLiteDatabase db) {
// TODO Auto-generated method stub
db.execSQL("CREATE TABLE " + DATABASE_TABLE + " (" +
KEY_ROWID + " INTEGER PRIMARY KEY AUTOINCREMENT, " +
KEY_NAME + " TEXT NOT NULL, " +
KEY_HOTNESS + " TEXT NOT NULL);"
);
}
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
// TODO Auto-generated method stub
db.execSQL("DROP TABLE IF EXISTS " + DATABASE_TABLE);
onCreate(db);
}
}
public HotOrNot(Context c){
ourContext =c;
}
public HotOrNot open() throws SQLException{
ourHelper = new DbHelper(ourContext);
ourDatabase = ourHelper.getWritableDatabase();
return this;
}
public void close(){
ourHelper.close();
}
public long createEntry(String name, String hotness) {
// TODO Auto-generated method stub
ContentValues cv = new ContentValues();
cv.put(KEY_NAME, name);
cv.put(KEY_HOTNESS, hotness);
return ourDatabase.insert(DATABASE_TABLE, null, cv);
}
public String getData() {
// TODO Auto-generated method stub
String [] columns = new String[]{ KEY_ROWID, KEY_NAME, KEY_HOTNESS};
Cursor c = ourDatabase.query(DATABASE_TABLE, columns, null, null, null, null, null);
String result = "";
int iRow = c.getColumnIndex(KEY_ROWID);
int iName = c.getColumnIndex(KEY_NAME);
int iHotness = c.getColumnIndex(KEY_HOTNESS);
for(c.moveToFirst(); !c.isAfterLast(); c.moveToNext()) {
result = result + c.getString(iRow) + " "+ c.getString(iName) + " " + c.getString(iHotness) + "\n";
}
return result;
}
}
You need to write a function like the getData() you already have, but pass it the name... For example:
public Cursor getData(String name) {
...
Cursor c = ourDatabase.query(DATABASE_TABLE, columns, KEY_NAME + "=?", new String[] { name }, null, null, null);
...
}

Regarding Android Database

Hot To Create A Table in database only once and insert data into that table multiple times in android using SQLite DB...??
You should be sub-classing SQLiteOpenHelper and making use of its convenience methods which will remove a lot of the complexity of using SQLite. See Data Storage
Take a look at the NotePadProvider sample.
This is my activity class
public class d extends Activity {
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
String name=getIntent().getStringExtra("name");
String email=getIntent().getStringExtra("email");
String phone=getIntent().getStringExtra("phone");
Log.e("d3","came to other activity");
SmartDBHelper d=new SmartDBHelper(getApplicationContext());
d.open();
d.insertTitle(name, phone, email);
Cursor c=d.getAllTitles();
// c.getColumnName(0);
for( int i=0;i<c.getCount();i++){
if(c.moveToNext()){
Log.e("c", ""+ c.getString(0) );
Log.e("d", ""+ c.getString(1) );
Log.e("d4", ""+ c.getString(2) );
}
Log.e("r",""+c.getCount());
finish();
}
}
}
here is my sqllite class
public class SmartDBHelper extends SQLiteOpenHelper {
private SQLiteDatabase dBH;
private static final String DATABASE_NAME = "yo.db";
private static final int DATABASE_VERSION = 2;
private static final String NOTIFY_TABLE_NAME = "user_notify_data";
private static final String HR_TABLE_NAME = "user_hr_data";
private static final String NOTIFY_TABLE_CREATE =
"CREATE TABLE " + NOTIFY_TABLE_NAME + " (counter INTEGER PRIMARY KEY, " +
"userresponse TEXT, " +
"notifytime TEXT);";
private static final String HR_TABLE_CREATE =
"CREATE TABLE " + HR_TABLE_NAME +
" (counter INTEGER PRIMARY KEY, " +
"hr TEXT, " +
"act TEXT, " +
"timestamp TEXT);";
public SmartDBHelper(Context context) {
super(context, DATABASE_NAME, null, DATABASE_VERSION);
// TODO Auto-generated constructor stub
}
#Override
public void onCreate(SQLiteDatabase db) {
// TODO Auto-generated method stub
Log.e("smartdbhelper", "before creation");
db.execSQL(NOTIFY_TABLE_CREATE);
Log.e("smartdbhelper", "middle creation");
db.execSQL(HR_TABLE_CREATE);
Log.e("smartdbhelper", "after creation");
}
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
// TODO Auto-generated method stub
}
public SmartDBHelper open() throws SQLException
{
dBH = getWritableDatabase();
return this;
}
public long insertTitle(String isbn, String title, String publisher)
{
ContentValues initialValues = new ContentValues();
initialValues.put("hr", isbn);
initialValues.put("act", title);
initialValues.put("timestamp", publisher);
Log.e("insertes","i");
dBH.insert(HR_TABLE_NAME, null, initialValues);
return 11111111;
}
public Cursor getAllTitles()
{
return dBH.query(HR_TABLE_NAME, new String[] {
"hr","act","timestamp"},null,
null,
null,
null,
null);
}
//---closes the database---
public void close()
{
close();
}
}
The above code works and has been tested

Categories

Resources