Can't find SQL column in android project - java

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

Related

Total price using rawQuery in android [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 8 years ago.
Improve this question
I've been trying to get the price value from the database and try to make a grand total. I used the rawQuery but always crashed.I think theres a problem in my rawQuery..i still cant get the total after many times i've tried..
this is the code:
DBAdapter
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;
// ------------------------------------ DBAdapter.java ---------------------------------------------
// TO USE:
// Change the package (at top) to match your project.
// Search for "TODO", and make the appropriate changes.
public class DBAdapter {
/////////////////////////////////////////////////////////////////////
// Constants & Data
/////////////////////////////////////////////////////////////////////
// For logging:
private static final String TAG = "DBAdapter";
// DB Fields
public static final String KEY_ROWID = "_id";
public static final int COL_ROWID = 0;
/*
* CHANGE 1:
*/
// TODO: Setup your fields here:
public static final String KEY_NAME = "name";
public static final String KEY_QUANTITY = "studentnum";
public static final String KEY_PRICE = "favcolour";
// TODO: Setup your field numbers here (0 = KEY_ROWID, 1=...)
public static final int COL_NAME = 1;
public static final int COL_QUANTITY = 2;
public static final int COL_PRICE = 3;
public static final String[] ALL_KEYS = new String[] {KEY_ROWID, KEY_NAME, KEY_QUANTITY, KEY_PRICE};
// DB info: it's name, and the table we are using (just one).
public static final String DATABASE_NAME = "MyDb";
public static final String DATABASE_TABLE = "mainTable";
// Track DB version if a new version of your app changes the format.
public static final int DATABASE_VERSION = 2;
private static final String DATABASE_CREATE_SQL =
"create table " + DATABASE_TABLE
+ " (" + KEY_ROWID + " integer primary key autoincrement, "
/*
* CHANGE 2:
*/
// TODO: Place your fields here!
// + KEY_{...} + " {type} not null"
// - Key is the column name you created above.
// - {type} is one of: text, integer, real, blob
// (http://www.sqlite.org/datatype3.html)
// - "not null" means it is a required field (must be given a value).
// NOTE: All must be comma separated (end of line!) Last one must have NO comma!!
+ KEY_NAME + " text not null, "
+ KEY_QUANTITY + " integer not null, "
+ KEY_PRICE + " string not null"
// Rest of creation:
+ ");";
// Context of application who uses us.
private final Context context;
private DatabaseHelper myDBHelper;
private SQLiteDatabase db;
/////////////////////////////////////////////////////////////////////
// Public methods:
/////////////////////////////////////////////////////////////////////
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 the database.
public long insertRow(String name, String studentNum, String favColour) {
/*
* CHANGE 3:
*/
// TODO: Update data in the row with new fields.
// TODO: Also change the function's arguments to be what you need!
// Create row's data:
ContentValues initialValues = new ContentValues();
initialValues.put(KEY_NAME, name);
initialValues.put(KEY_QUANTITY, studentNum);
initialValues.put(KEY_PRICE, favColour);
// Insert it 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 Cursor getTotalPrice() {
Cursor c = db.rawQuery("SELECT SUM("+ KEY_PRICE +")from " + DATABASE_TABLE, null);
return c;
}
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 name, int studentNum, String favColour) {
String where = KEY_ROWID + "=" + rowId;
/*
* CHANGE 4:
*/
// TODO: Update data in the row with new fields.
// TODO: Also change the function's arguments to be what you need!
// Create row's data:
ContentValues newValues = new ContentValues();
newValues.put(KEY_NAME, name);
newValues.put(KEY_QUANTITY, studentNum);
newValues.put(KEY_PRICE, favColour);
// Insert it into the database.
return db.update(DATABASE_TABLE, newValues, where, null) != 0;
}
/////////////////////////////////////////////////////////////////////
// Private Helper Classes:
/////////////////////////////////////////////////////////////////////
/**
* Private class which handles database creation and upgrading.
* Used to handle low-level database access.
*/
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);
}
}
}
Listprice:
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.support.v7.app.ActionBarActivity;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.*;
/**
* Created by User on 6/2/2015.
*/
public class Listprice extends ActionBarActivity {
DBAdapter myDb;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.listprice);
openDB();
TextView textView = (TextView) findViewById(R.id.order90);
TextView textView1 = (TextView) findViewById(R.id.quan90);
TextView textView2 = (TextView) findViewById(R.id.price90);
TextView textView3 = (TextView) findViewById(R.id.totalprice);
Bundle extras = getIntent().getExtras();
if (extras != null) {
String newText = extras.getString("firstmessage");
String newText1 = extras.getString("secondmessage");
String newText2 = extras.getString("thirdmessage");
if (newText != null) {
textView.setText(newText);
}
if (newText1 != null) {
textView1.setText(newText1);
}
if (newText2 != null) {
textView2.setText(newText2);
}
}
String num1 = textView.getText().toString().trim();
int num2 = Integer.parseInt(textView1.getText().toString());
int num3 = Integer.parseInt(textView2.getText().toString());
int num4 = num2 * num3;
registerListClickCallBack();
myDb.insertRow(num1, "Quantity = " + num2, ""+num4);
populateListViewFromDB();
Cursor sum=myDb.getTotalPrice();
textView3.setText(""+sum);
}
private void populateListViewFromDB() {
Cursor cursor = myDb.getAllRows();
//Query for the record we just added.
//Use the ID:
startManagingCursor(cursor);
String[] fromFieldNames = new String[]
{DBAdapter.KEY_NAME, DBAdapter.KEY_QUANTITY, DBAdapter.KEY_PRICE};
int[] toViewIDs = new int[]
{R.id.item_name, R.id.quantities, R.id.pricest};
SimpleCursorAdapter myCursorAdapter =
new SimpleCursorAdapter(
this,
R.layout.item_layout,
cursor,
fromFieldNames,
toViewIDs
);
// Set the adapter for the list view
ListView myList = (ListView) findViewById(R.id.listViewFromDB);
myList.setAdapter(myCursorAdapter);
}
private void openDB(){
myDb = new DBAdapter(this);
myDb.open();
}
#Override
protected void onDestroy() {
super.onDestroy();
closeDB();
}
private void closeDB() {
myDb.close();
}
private void registerListClickCallBack() {
ListView myList = (ListView) findViewById(R.id.listViewFromDB);
myList.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View viewClicked,
int position, long idInDB) {
updateItemForId(idInDB);
}
});
}
private void updateItemForId(final long idInDB) {
final Cursor cursor = myDb.getRow(idInDB);
if (cursor.moveToFirst()) {
AlertDialog.Builder alertDialog = new AlertDialog.Builder(Listprice.this);
// Setting Dialog Title
alertDialog.setTitle("Confirm Delete...");
// Setting Dialog Message
alertDialog.setMessage("Are you sure you want delete this?");
// Setting Positive "Yes" Button
alertDialog.setPositiveButton("YES", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog,int which) {
// Write your code here to invoke YES event
Toast.makeText(getApplicationContext(), "You clicked on YES", Toast.LENGTH_SHORT).show();
myDb.deleteRow(idInDB);
populateListViewFromDB();
}
});
// Setting Negative "NO" Button
alertDialog.setNegativeButton("NO", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
// Write your code here to invoke NO event
Toast.makeText(getApplicationContext(), "You clicked on NO", Toast.LENGTH_SHORT).show();
dialog.cancel();
}
});
// Showing Alert Message
alertDialog.show();
}
cursor.close();
populateListViewFromDB();
}
public void clear(View view) {
myDb.deleteAll();
populateListViewFromDB();
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.menu_main, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
//noinspection SimplifiableIfStatement
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
public void addFood(View view) {
Intent gotofood = new Intent(this, food.class);
startActivity(gotofood);
}
public void addDrinks(View view) {
Intent gotodrinks = new Intent(this, drink.class);
startActivity(gotodrinks);
}
public void gotomainmaenu(View view) {
Intent gotomain = new Intent(this, MainActivity.class);
startActivity(gotomain);
}
}
It sounds like you want the sum of each item's price multiplied by that item's quantity. If so, this should work:
public double getTotalPrice() {
String sql = "select sum(" + KEY_QUANTITY + " * " + KEY_PRICE + ") from "
+ DATABASE_TABLE;
Cursor cursor = db.rawQuery(sql, null);
if (cursor.moveToFirst()) {
return cursor.getDouble(0);
}
return 0;
}

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

filtering data from the database using setFilterQueryProvider?

I have here my code. Data on the database are filtered by the title, how can i filter data by title or author? I think it is on these lines of codes on Catalogue.java:
dataAdapter.setFilterQueryProvider(new FilterQueryProvider() {
public Cursor runQuery(CharSequence constraint) {
return dbHelper.fetchCollectionsByTitle(constraint.toString());
Here are my codes:
Catalogue.java
package com.cvsu.catalogue.db;
import com.cvsu.catalogue.R;
import android.annotation.SuppressLint;
import android.app.Activity;
import android.content.Intent;
import android.database.Cursor;
import android.os.Bundle;
import android.text.Editable;
import android.text.TextWatcher;
import android.view.View;
import android.widget.AdapterView;
import android.widget.EditText;
import android.widget.FilterQueryProvider;
import android.widget.ListView;
import android.widget.SimpleCursorAdapter;
//import android.widget.Toast;
import android.widget.AdapterView.OnItemClickListener;
#SuppressLint("NewApi")
public class Catalogue extends Activity {
private CollectionsDbAdapter dbHelper;
private SimpleCursorAdapter dataAdapter;
public final static String TITLE_EXTRA = "com.cvsu.catalogue.db._TITLE";
public final static String AUTHOR_EXTRA = "com.cvsu.catalogue.db._AUTHOR";
public final static String LOCATION_EXTRA = "com.cvsu.catalogue.db._LOCATION";
public final static String CALLNUMBER_EXTRA = "com.cvsu.catalogue.db._CALLNUMBER";
public final static String PUBLISHER_EXTRA = "com.cvsu.catalogue.db._PUBLISHER";
public final static String DATEPUBLISHED_EXTRA = "com.cvsu.catalogue.db._DATEPUBLISHED";
public final static String DESCRIPTION_EXTRA = "com.cvsu.catalogue.db._DESCRIPTION";
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.catalogue_title);
dbHelper = new CollectionsDbAdapter(this);
dbHelper.open();
//Generate ListView from SQLite Database
displayListView();
}
private void displayListView() {
Cursor cursor = dbHelper.fetchAllCollections();
// The desired columns to be bound
String[] columns = new String[] {
CollectionsDbAdapter.KEY_TITLE,
CollectionsDbAdapter.KEY_AUTHOR,
CollectionsDbAdapter.KEY_LOCATION,
CollectionsDbAdapter.KEY_CALLNUMBER,
CollectionsDbAdapter.KEY_PUBLISHER,
CollectionsDbAdapter.KEY_DATEPUBLISHED,
CollectionsDbAdapter.KEY_DESCRIPTION
};
// the XML defined views which the data will be bound to
int[] to = new int[] {
R.id.txtTitle,
R.id.txtAuthor,
//R.id.location,
//R.id.callnumber,
//R.id.publisher,
//R.id.datepublished,
//R.id.description,
};
// create the adapter using the cursor pointing to the desired data
//as well as the layout information
dataAdapter = new SimpleCursorAdapter(
this, R.layout.book_info_title,
cursor,
columns,
to,
0);
final ListView listView = (ListView) findViewById(R.id.listView1);
// Assign adapter to ListView
listView.setAdapter(dataAdapter);
listView.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> listview, View view,
int position, long id ) {
// Get the cursor, positioned to the corresponding row in the result set
/*Cursor cursor = (Cursor) listView.getItemAtPosition(position);
// Get the state's capital from this row in the database.
String bookTitle =
cursor.getString(cursor.getColumnIndexOrThrow("title"));
Toast.makeText(getApplicationContext(),
bookTitle, Toast.LENGTH_SHORT).show();*/
Intent i = new Intent (CatalogueTitle.this, BookInfoPage.class);
i.putExtra(TITLE_EXTRA, String.valueOf(id));
i.putExtra(AUTHOR_EXTRA, String.valueOf(id));
i.putExtra(LOCATION_EXTRA, String.valueOf(id));
i.putExtra(CALLNUMBER_EXTRA, String.valueOf(id));
i.putExtra(PUBLISHER_EXTRA, String.valueOf(id));
i.putExtra(DATEPUBLISHED_EXTRA, String.valueOf(id));
i.putExtra(DESCRIPTION_EXTRA, String.valueOf(id));
startActivity(i);
}
});
EditText myFilter = (EditText) findViewById(R.id.myFilter);
myFilter.addTextChangedListener(new TextWatcher() {
public void afterTextChanged(Editable s) {
}
public void beforeTextChanged(CharSequence s, int start,
int count, int after) {
}
public void onTextChanged(CharSequence s, int start,
int before, int count) {
dataAdapter.getFilter().filter(s.toString());
}
});
dataAdapter.setFilterQueryProvider(new FilterQueryProvider() {
public Cursor runQuery(CharSequence constraint) {
return dbHelper.fetchCollectionsByTitle(constraint.toString());
}
});
}
public static void main(String[] args) {
}
}
Collections.Java
package com.cvsu.catalogue.db;
public class Collections {
String title = null;
String author = null;
String location = null;
String callnumber = null;
String publisher = null;
String datepublished = null;
String description = null;
public String getTitle() {
return title;
}
public void setTitle(String title) {
this.title = title;
}
public String getAuthor() {
return author;
}
public void setAuthor(String author) {
this.author = author;
}
public String getLocation() {
return location;
}
public void setLocation(String location) {
this.location = location;
}
public String getCallNumber() {
return callnumber;
}
public void setCallNumber(String callnumber) {
this.callnumber = callnumber;
}
public String getPublisher() {
return publisher;
}
public void setPublisher(String publisher) {
this.publisher = publisher;
}
public String getDatePublished() {
return datepublished;
}
public void setDatePublished(String datepublished) {
this.datepublished = datepublished;
}
public String getDescription() {
return description;
}
public void setDescription(String description) {
this.description = description;
}
}
CollectionsDbAdapter.java
package com.cvsu.catalogue.db;
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 CollectionsDbAdapter {
public static final String KEY_ROWID = "_id";
public static final String KEY_TITLE = "title";
public static final String KEY_AUTHOR = "author";
public static final String KEY_LOCATION = "location";
public static final String KEY_CALLNUMBER = "callnumber";
public static final String KEY_PUBLISHER = "publisher";
public static final String KEY_DATEPUBLISHED = "datepublished";
public static final String KEY_DESCRIPTION = "description";
private static final String TAG = "CollectionsDbAdapter";
private DatabaseHelper mDbHelper;
private SQLiteDatabase mDb;
private static final String DATABASE_NAME = "LibraryCollections";
private static final String SQLITE_TABLE = "Collections";
private static final int DATABASE_VERSION = 1;
private final Context mCtx;
private static final String DATABASE_CREATE =
"CREATE TABLE if not exists " + SQLITE_TABLE + " (" +
KEY_ROWID + " integer PRIMARY KEY autoincrement," +
KEY_TITLE + "," +
KEY_AUTHOR + "," +
KEY_LOCATION + "," +
KEY_CALLNUMBER + "," +
KEY_PUBLISHER + "," +
KEY_DATEPUBLISHED + "," +
KEY_DESCRIPTION + "," +
" UNIQUE (" + KEY_CALLNUMBER +"));";
private static class DatabaseHelper extends SQLiteOpenHelper {
DatabaseHelper(Context context) {
super(context, DATABASE_NAME, null, DATABASE_VERSION);
}
#Override
public void onCreate(SQLiteDatabase db) {
Log.w(TAG, DATABASE_CREATE);
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 " + SQLITE_TABLE);
onCreate(db);
}
}
public CollectionsDbAdapter(Context ctx) {
this.mCtx = ctx;
}
public CollectionsDbAdapter open() throws SQLException {
mDbHelper = new DatabaseHelper(mCtx);
mDb = mDbHelper.getWritableDatabase();
return this;
}
public void close() {
if (mDbHelper != null) {
mDbHelper.close();
}
}
public long createCollections(String title, String author,
String location, String callnumber, String publisher, String datepublished, String description) {
ContentValues initialValues = new ContentValues();
initialValues.put(KEY_TITLE, title);
initialValues.put(KEY_AUTHOR, author);
initialValues.put(KEY_LOCATION, location);
initialValues.put(KEY_CALLNUMBER, callnumber);
initialValues.put(KEY_PUBLISHER, publisher);
initialValues.put(KEY_DATEPUBLISHED, datepublished);
initialValues.put(KEY_DESCRIPTION, description);
return mDb.insert(SQLITE_TABLE, null, initialValues);
}
public Cursor fetchCollectionsByTitle(String inputText) throws SQLException {
Log.w(TAG, inputText);
Cursor mCursor = null;
if (inputText == null || inputText.length () == 0) {
mCursor = mDb.query(SQLITE_TABLE, new String[] {KEY_ROWID,
KEY_TITLE, KEY_AUTHOR, KEY_LOCATION, KEY_CALLNUMBER, KEY_PUBLISHER, KEY_DATEPUBLISHED, KEY_DESCRIPTION},
null, null, null, null, null);
}
else {
mCursor = mDb.query(true, SQLITE_TABLE, new String[] {KEY_ROWID,
KEY_TITLE, KEY_AUTHOR, KEY_LOCATION, KEY_CALLNUMBER, KEY_PUBLISHER, KEY_DATEPUBLISHED, KEY_DESCRIPTION},
KEY_TITLE + " like '%" + inputText + "%'", null,
null, null, null, null);
}
if (mCursor != null) {
mCursor.moveToFirst();
}
return mCursor;
}
public Cursor fetchCollectionsByAuthor(String inputText) throws SQLException {
Log.w(TAG, inputText);
Cursor mCursor = null;
if (inputText == null || inputText.length () == 0) {
mCursor = mDb.query(SQLITE_TABLE, new String[] {KEY_ROWID,
KEY_TITLE, KEY_AUTHOR, KEY_LOCATION, KEY_CALLNUMBER, KEY_PUBLISHER, KEY_DATEPUBLISHED, KEY_DESCRIPTION},
null, null, null, null, null);
}
else {
mCursor = mDb.query(true, SQLITE_TABLE, new String[] {KEY_ROWID,
KEY_TITLE, KEY_AUTHOR, KEY_LOCATION, KEY_CALLNUMBER, KEY_PUBLISHER, KEY_DATEPUBLISHED, KEY_DESCRIPTION},
KEY_AUTHOR + " like '%" + inputText + "%'", null,
null, null, null, null);
}
if (mCursor != null) {
mCursor.moveToFirst();
}
return mCursor;
}
public Cursor fetchAllCollections() {
Cursor mCursor = mDb.query(SQLITE_TABLE, new String[] {KEY_ROWID,
KEY_TITLE, KEY_AUTHOR, KEY_LOCATION, KEY_CALLNUMBER, KEY_PUBLISHER, KEY_DATEPUBLISHED, KEY_DESCRIPTION},
null, null, null, null, null);
if (mCursor != null) {
mCursor.moveToFirst();
}
return mCursor;
}
}
#Override
public Cursor runQuery(CharSequence constraint) {
Cursor cur = null;
database.openDataBase();
if(constraint!=null){
cur = database.selectDataWithConstrain(constraint.toString());
}
return cur;
}
using this constarint write a query in your Database Class and get the data required either title or author
public Cursor selectDataWithConstrain(String c) {
// TODO Auto-generated method stub
Cursor cursor = myDataBase.rawQuery("SELECT * FROM tbl_xxx WHERE title LIKE '%"+c+"%'", null);
return cursor;
}
public Cursor fetchdatabyfilter(String inputText, String filtercolumn) throws SQLException {
Cursor row = null;
String query = "SELECT * FROM " + dbTable;
if (inputText == null || inputText.length() == 0 ) {
row = sqlDb.rawQuery(query, null);
} else {
query = "SELECT * FROM " + dbTable + " WHERE " + filtercolumn + " like '%" + inputText + "%' ";
row = sqlDb.rawQuery(query, null);
}
if (row != null)
{
row.moveToFirst();
}
return row;
}
mainactivity:
adapter.setFilterQueryProvider(new FilterQueryProvider() {
public Cursor runQuery(CharSequence constraint) {
return db.fetchdatabyfilter(constraint.toString(),"title" );
}
});

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
}

cursor.getstring() is getting the wrong field in the database

So this is my code:
public void onItemClick(AdapterView<?> listView, View view, int position, long id)
{
Cursor cursor = (Cursor) listView.getItemAtPosition(position);
int _id = cursor.getInt(0);
String _recipe = cursor.getString(1);
Intent intent = new Intent(Luzon1Activity.this,RecipeInstruction.class);
intent.putExtra("id", _id);
intent.putExtra("recipe", _recipe);
startActivity(intent);
}
This is my code for the next activity:
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.recipeinstruction);
dbHelper = new Dbadapter(this);
dbHelper.open();
bg = (RelativeLayout) findViewById(R.id.relativeLayout1);
Bundle extras = getIntent().getExtras();
if (extras != null) {
id = extras.getInt("id");
recipe = extras.getString("recipe");
}
Toast.makeText(this, id+"\n"+recipe, Toast.LENGTH_SHORT).show();
bg.setBackgroundResource(getImageId(this, recipe));
}
My problem is on this part: String _recipe = cursor.getString(1).
It always gives me the wrong data. I tried to change the number but still it gives me the wrong data.
This is my database:
package com.pinoycookbook;
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 ROWID = "_id";
public static final String NAME = "foodname";
public static final String ORIGIN = "origin";
public static final String RECIPE = "recipe";
public static final String CATEGORY = "category";
private static final String TAG = "Dbadapter";
private DatabaseHelper mDbHelper;
private SQLiteDatabase mDb;
private static final String DATABASE_NAME = "PinoyCookbook.sqlite";
public static final String SQLITE_TABLE = "Food";
private static final int DATABASE_VERSION = 1;
private final Context mCtx;
private static final String DATABASE_CREATE =
"CREATE TABLE if not exists " + SQLITE_TABLE + " (" +
ROWID + " integer PRIMARY KEY autoincrement," +
NAME + " TEXT," +
RECIPE + " TEXT," +
ORIGIN + " TEXT," +
CATEGORY+ " TEXT,"+
" UNIQUE (" + ROWID +"));";
private static class DatabaseHelper extends SQLiteOpenHelper
{
DatabaseHelper(Context context) {
super(context, DATABASE_NAME, null, DATABASE_VERSION);
}
#Override
public void onCreate(SQLiteDatabase db) {
Log.w(TAG, DATABASE_CREATE);
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 " + SQLITE_TABLE);
onCreate(db);
}
}
public Dbadapter(Context ctx) {
this.mCtx = ctx;
}
public Dbadapter open() throws SQLException {
mDbHelper = new DatabaseHelper(mCtx);
mDb = mDbHelper.getWritableDatabase();
return this;
}
public void close() {
if (mDbHelper != null) {
mDbHelper.close();
}
}
public long createData(String foodname, String recipe, String origin, int i) {
ContentValues initialValues = new ContentValues();
initialValues.put(NAME, foodname);
initialValues.put(RECIPE, recipe);
initialValues.put(ORIGIN, origin);
initialValues.put(CATEGORY, i);
return mDb.insert(SQLITE_TABLE, null, initialValues);
}
public boolean deleteAllData() {
int doneDelete = 0;
doneDelete = mDb.delete(SQLITE_TABLE, null , null);
Log.w(TAG, Integer.toString(doneDelete));
return doneDelete > 0;
}
public void insertData() {
createData("Adobong Manok","adobongmanok","Manila",1);
createData("Lechon","lechon","Cebu",2);
createData("Crispy Pata","crispypata","Cebu",2);
createData("Bulalo","bulalo","Batangas",1);
createData("Taba ng Talangka Rice","talangkarice","Roxas",2);
createData("Arroz Caldo","arrozcaldo","Roxas",2);
createData("Sinigang","sinigang","Manila",1);
}
}
So i recommend you to use getColumnIndex() method rather than hardcode it.
String _recipe = cursor.getString(cursor.getColumnIndex(Dbadapter.RECIPE));
It will ensure that you will get always right field. And if it still get wrong data problem is in query not in Cursor
Note: An usage of static fields that hold column names is always the best practise.
Update:
I've tried it before and it gives me this error:
java.lang.IllegalArgumentException: column 'recipe' does not exist
You need to find out your actual table structure. Try to perform this statement:
PRAGMA table_info(Dbadapter.SQLITE_TABLE);
What says docs(source):
This pragma returns one row for each column in the named table.
Columns in the result set include the column name, data type, whether
or not the column can be NULL, and the default value for the column.
The "pk" column in the result set is zero for columns that are not
part of the primary key, and is the index of the column in the primary
key for columns that are part of the primary key.
Example:
Here i created for you method for getting tableinfo via PRAGMA:
public String getTableInfo() {
StringBuilder b = new StringBuilder("");
Cursor c = null;
try {
db = helper.getReadableDatabase();
String query = "pragma table_info(" + Dbadapter.SQLITE_TABLE + ")";
c = db.rawQuery(query, null);
if (c.moveToFirst()) {
do {
b.append("Col:" + c.getString(c.getColumnIndex("name")) + " ");
b.append(c.getString(c.getColumnIndex("type")));
b.append("\n");
} while (c.moveToNext());
}
return b.toString();
}
finally {
if (c != null) {
c.close();
}
if (db != null) {
db.close();
}
}
}
Output will be something like this:
Column: type text
Column: date text
Only for imagination i will give you screen:
you can try it this way:
cursor.getString(cursor.getColumnIndex("recipe"));
it returns you the correct index and as result the correct value.

Categories

Resources