I am making a small app and therefore i need to use a small SQLite-database.
Please help me, i dont know how to fix this error:
At the line "SQLiteDatabase db = this.getReadableDatabase();" in the database
, (Main: int teams = db.countAllTeams())
Error: W/System.errīš Invalid int: ""
Database:
public class DatabaseHelper extends SQLiteOpenHelper {
private static final int DATABASE_VERSION = 1;
private static final String DATABASE_NAME = "database";
private static final String TABLE_TEAM = "team";
private static final String KEY_TEAM_FULLNAME = "full_name";
private static final String KEY_TEAM_SHORTNAME = "short_name";
private static final String KEY_TEAM_STADIUM = "stadium";
private static final String KEY_TEAM_LOGO = "logo";
private static final String CREATE_TABLE_TEAM = "CREATE TABLE "
+ TABLE_TEAM + "(" + KEY_TEAM_FULLNAME + " TEXT PRIMARY KEY," +
KEY_TEAM_SHORTNAME + " TEXT," +
KEY_TEAM_STADIUM + " TEXT," +
KEY_TEAM_LOGO + " INTEGER" + ")";
public DatabaseHelper(Context context) {
super(context, DATABASE_NAME, null, DATABASE_VERSION);
}
#Override
public void onCreate(SQLiteDatabase db) {
db.execSQL(CREATE_TABLE_TEAM);
}
#Override
public void onUpgrade(SQLiteDatabase db, int old, int neW) {
db.execSQL("DROP TABLE IF EXISTS " + TABLE_TEAM);
onCreate(db);
}
public void closeDB() {
SQLiteDatabase db = this.getReadableDatabase();
if (db != null && db.isOpen()) db.close();
}
public long createTeam(Team team) {
SQLiteDatabase db = this.getWritableDatabase();
ContentValues values = new ContentValues();
values.put(KEY_TEAM_FULLNAME, team.getFullName());
values.put(KEY_TEAM_SHORTNAME, team.getShortName());
values.put(KEY_TEAM_LOGO, team.getLogo());
values.put(KEY_TEAM_STADIUM, team.getStadium());
return db.insert(TABLE_TEAM, null, values);
}
public int countAllTeams(){
SQLiteDatabase db = this.getReadableDatabase();
List<Team> teams = new ArrayList<Team>();
return Integer.getInteger(db.compileStatement("SELECT COUNT(*) FROM " + TABLE_TEAM).simpleQueryForString());
}
}
Main
DatabaseHelper db;
TextView tvText;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.layout_home);
tvText = (TextView)findViewById(R.id.tvText);
String text = "";
db = new DatabaseHelper(getApplicationContext());
int teams = db.countAllTeams();
tvText.setText(teams);
}
}
Integer.getInteger does not convert a string to an integer.
The easiest way to get a single number from a query is to use DatabaseUtils:
long count = DatabaseUtils.longForQuery(db,
"SELECT COUNT(*) FROM " + TABLE_TEAM, null);
But to get the number of rows in the table, there's an even simpler function:
long count = DatabaseUtils.queryNumEntries(db, TABLE_TEAM);
Furthermore, when you give an integer to TextView.setText, it expects a resource ID.
You have to convert your count into a string manually:
tvText.setText(Integer.toString(teams));
I'd use rawQuery() instead of simpleQueryForString():
public int countAllTeams(){
SQLiteDatabase db = this.getReadableDatabase();
List<Team> teams = new ArrayList<Team>();
Cursor c = db.rawQuery("SELECT COUNT(*) FROM " + TABLE_TEAM, new String[]{});
c.moveToFirst();
return c.getInt(0);
}
.setText doesn't take in integers directly, instead try:
tvText.setText(String.valueOf(teams));
Integer value in TextView
Related
I am new in Android platform. I want to record the live magnetic sensor data directly to sQLite database in storage. I wrote code to get magnetic data but i am not able to create the database. I have pasted code below. Any help would be great.
Thank you in advance.
// code for Database Helper
public class DBHelper extends SQLiteOpenHelper{
private static final String DB_NAME = "Mag_Positioning.db";
private static final int DB_VERSION = 1;
private static final String COL_ID = "ID";
private static final String COL_XAXIS = "X-AXIS";
private static final String TABLE_NAME = "MAP_COORDINATES";
private static final String COL_YAXIS = "Y-AXIS";
private static final String COL_ZAXIS = "Z-AXIS";
public DBHelper(Context context){
super(context, DB_NAME, null, DB_VERSION);
}
#Override
public void onCreate(SQLiteDatabase db) {
String createTable = "CREATE TABLE " + TABLE_NAME + "(" + COL_ID + " INTEGER PRIMARY KEY AUTOINCREMENT," + COL_XAXIS + " INTEGER," + COL_YAXIS + " INTEGER," + COL_ZAXIS + " INTEGER" + " )";
db.execSQL(createTable);
}
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
db.execSQL("DROP TABLE IF EXISTS " + TABLE_NAME);
onCreate(db);
}
public void insert(Integer xaxis, Integer yaxis, Integer zaxis){
SQLiteDatabase db = this.getWritableDatabase();
}
}
// code for getting magnetic sensor data
// Its just fragment of code
public class MainActivity extends AppCompatActivity implements SensorEventListener {
Sensor magnetometer;
SensorManager sm;
TextView magnetismx;
TextView magnetismy;
TextView magnetismz;
DBHelper dbHelper;
public float a;
public float b;
public float c;
boolean recording = false;
boolean stoprecord = false;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
dbHelper = new DBHelper(this);
// I have declared some button here...
#Override
public void onSensorChanged(SensorEvent event) {
Sensor sensor = event.sensor;
a = event.values[0];
b = event.values[1];
c = event.values[2];
if (sensor.getType() == Sensor.TYPE_MAGNETIC_FIELD) {
magnetismx.setText(Float.toString(event.values[0]));
magnetismy.setText(Float.toString(event.values[1]));
magnetismz.setText(Float.toString(event.values[2]));
if (!recording) {
return;
}
if(stoprecord){
return;
}
}
try {
writeToCsv(Float.toString(a), Float.toString(b), Float.toString(c));
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
ps: The code for database is not working too.. The table is not created.
I sorted out the problem myself. There was some problem in database class. I have used the below code for database helper class.
ublic class DBHelper extends SQLiteOpenHelper {
private static final String DB_NAME = "Mag_Positioning.db";
private static final int DB_VERSION = 1;
//Table for measurement
private static final String ID = "id";
private static final String MAP_ID = "Mapid";
private static final String COLXAXIS = "X_AXIS";
private static final String TABLENAME = "Fingerprint";
private static final String COLYAXIS = "Y_AXIS";
private static final String COLZAXIS = "Z_AXIS";
private static final String MAPX = "X_CORD";
private static final String MAPY = "Y_CORD";
private static final String DIFF = "Diff";
private static final String FINAL = "FINAL";
private static final String KEY_FINGERPRINT_ID = "id";
private static final String KEY_MAP_NAME = "map_name";
private static final String KEY_POSITION_X = "position_x";
private static final String KEY_POSITION_Y = "position_y";
private static DBHelper mInstance;
public DBHelper(Context context) {
super(context, DB_NAME, null, DB_VERSION);
}
public static DBHelper getInstance() {
if (mInstance == null) {
synchronized (DBHelper.class) {
if (mInstance == null) {
mInstance = new DBHelper(BaseApp.getApp());
}
}
}
return mInstance;
}
#Override
public void onCreate(SQLiteDatabase db) {
String createTable = "CREATE TABLE " + TABLENAME + "("
+ ID + " INTEGER PRIMARY KEY,"
+ MAP_ID + " INTEGER ," +
MAPX + " INTEGER, " +
MAPY + " INTEGER, " +
COLXAXIS + " REAL, " +
COLYAXIS + " REAL, " +
COLZAXIS + " REAL, " +
FINAL + " REAL )";
db.execSQL(createTable);
}
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
db.execSQL("DROP TABLE IF EXISTS " + TABLENAME);
onCreate(db);
}
public void insert(int a, int b, int c, float x, float y, float z, float d) {
SQLiteDatabase db = this.getWritableDatabase();
ContentValues contentvalues = new ContentValues();
contentvalues.put("Mapid", a);
contentvalues.put("X_CORD", b);
contentvalues.put("Y_CORD", c);
contentvalues.put("X_AXIS", x);
contentvalues.put("Y_AXIS", y);
contentvalues.put("Z_AXIS", z);
contentvalues.put("FINAL", d);
db.insert("Fingerprint", null, contentvalues);
db.close();
}
public void deleteAllFingerprints() {
SQLiteDatabase db = this.getWritableDatabase();
db.delete(TABLENAME, null, null); // delete all fingerprints
db.close();
}
public Cursor getAllData() {
SQLiteDatabase db = this.getWritableDatabase();
Cursor cur = db.rawQuery("select * from " + TABLENAME, null);
return cur;
}
}
I know, there are a lot of answers already. But I'm a newbie on using SQLite yet and I tried what those answers say but nothing works.
It says my column id doesn't exist but it does exist:
public class SQLite extends SQLiteOpenHelper {
// All Static variables
// Database Version
private static final int DATABASE_VERSION = 1;
// Database Name
private static final String DATABASE_NAME = "OMDBAPI";
// Films table name
static final String TABLE_FILMS = "films";
// Contacts Table Columns names
static final String KEY_TITLE = "Title";
static final String KEY_YEAR = "Year";
static final String KEY_RELEASED = "Released";
static final String KEY_RUNTIME = "Runtime";
static final String KEY_GENRE = "Genre";
static final String KEY_DIRECTOR = "Director";
static final String KEY_WRITER = "Writer";
static final String KEY_ACTORS = "Actors";
static final String KEY_PLOT = "Plot";
static final String ID = "_id";
public SQLite(Context context) {
super(context, DATABASE_NAME, null, DATABASE_VERSION);
}
#Override
public void onCreate(SQLiteDatabase db) {
String CREATE_FILMS_TABLE = "CREATE TABLE " + TABLE_FILMS +"(" +
ID + "integer primary key autoincrement," +
KEY_TITLE + " TEXT, " +
KEY_YEAR + " TEXT, " +
KEY_RELEASED + " TEXT, " +
KEY_RUNTIME + " TEXT, " +
KEY_GENRE + " TEXT, " +
KEY_DIRECTOR + " TEXT, " +
KEY_WRITER + " TEXT, " +
KEY_ACTORS + " TEXT, " +
KEY_PLOT + " TEXT" +
");";
db.execSQL(CREATE_FILMS_TABLE);
}
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
// Drop older table if existed
db.execSQL("DROP TABLE IF EXISTS " + TABLE_FILMS);
// Create tables again
onCreate(db);
}
}
And I try to populate this on a listview:
public class Query extends Activity {
private ListView list;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.list_view);
DBController crud = new DBController(getBaseContext());
Cursor cursor = crud.loadData();
String[] titles = new String[] {SQLite.ID, SQLite.KEY_TITLE};
int[] idViews = new int[] {R.id.idnumber, R.id.grid_title};
SimpleCursorAdapter adapter = new SimpleCursorAdapter(getBaseContext(),
R.layout.adapter_layout,cursor,titles,idViews, 0);
list = (ListView)findViewById(R.id.listView);
list.setAdapter(adapter);
}
}
This is my DB CONTROLLER (Newbie mistake? Should I put the ID here too?):
public class DBController {
private SQLiteDatabase db;
private SQLite bank;
String success = "Film saved.";
String failed = "There was a problem saving the movie.";
public DBController(Context context){
bank = new SQLite(context);
}
public String insertData(String title, String release, String year, String writers, String actors, String director, String genre, String plot, String runtime){
ContentValues values;
long result;
db = bank.getWritableDatabase();
values = new ContentValues();
// Insert values
values.put(SQLite.KEY_TITLE, title);
values.put(SQLite.KEY_YEAR, release);
values.put(SQLite.KEY_RELEASED, release);
values.put(SQLite.KEY_YEAR, year);
values.put(SQLite.KEY_GENRE, genre);
values.put(SQLite.KEY_DIRECTOR, director);
values.put(SQLite.KEY_WRITER, writers);
values.put(SQLite.KEY_ACTORS, actors);
values.put(SQLite.KEY_PLOT, plot);
values.put(SQLite.KEY_RUNTIME, runtime);
result = db.insert(SQLite.TABLE_FILMS, null, values);
db.close();
if (result ==-1)
return failed;
else
return success;
}
public Cursor loadData(){
Cursor cursor;
String[] fields = {bank.KEY_TITLE,bank.KEY_RELEASED};
db = bank.getReadableDatabase();
cursor = db.query(bank.TABLE_FILMS, fields, null, null, null, null, null, null);
if(cursor!=null){
cursor.moveToFirst();
}
db.close();
return cursor;
}
}
Can someone help me find out why it says I don't have an ID column?
(Why are ppl downvote the post? I thought Stack Overflow was to help idiots like me =P)
You don't have _id column, you have _idinteger because you forgot to put a space in the CREATE query. Change the line
ID + "integer primary key autoincrement," +
to
ID + " integer primary key autoincrement," +
You can use baseColums interface that provides a primary key field (called _ID)
An example from google
Hi I am new to android development and I am attempting to make an app which stores appointments. My fragments and activities are all fine however I am trying to work out how to check my sqlite database that the string I am trying to enter isn't already stored as a unique string already, any help is much appreciated.
Here is my code for the database so far.
public class MyDataBase extends SQLiteOpenHelper {
private static final int DATABASE_VERSION = 4;
private static final String DATABASE_NAME = "appointments.db";
public static final String TABLE_APPOINTMENTS = "appointments";
public static final String COLUMN_DAY = "day";
public static final String COLUMN_MONTH = "month";
public static final String COLUMN_YEAR = "year";
public static final String COLUMN_TITLE = "title";
public static final String COLUMN_TIME = "time";
public static final String COLUMN_DESCRIPTION = "details";
public MyDataBase(Context context) {
super(context, DATABASE_NAME, null, DATABASE_VERSION);
}
#Override
public void onCreate(SQLiteDatabase db) {
String query = "CREATE TABLE " + TABLE_APPOINTMENTS
+ "(" + COLUMN_DAY + " INTEGER, " + COLUMN_MONTH + " INTEGER, " + COLUMN_YEAR + " INTEGER, "
+ COLUMN_TITLE + " TEXT NOT NULL UNIQUE, " + COLUMN_TIME + " TEXT, " + COLUMN_DESCRIPTION + " TEXT" + ")";
db.execSQL(query);
}
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
db.execSQL("DROP TABLE IF EXISTS " + TABLE_APPOINTMENTS);
onCreate(db);
}
public void addAppointment(Appointment app){
SQLiteDatabase db = getWritableDatabase();
ContentValues values = new ContentValues();
values.put(COLUMN_DAY, app.get_day());
values.put(COLUMN_MONTH, app.get_month());
values.put(COLUMN_YEAR, app.get_year());
values.put(COLUMN_TITLE, app.get_title()); // need to check that string being entered isn't already a unique entry
values.put(COLUMN_TIME, app.get_time());
values.put(COLUMN_DESCRIPTION, app.get_details());
db.insert(TABLE_APPOINTMENTS, null, values);
db.close();
}
}
Call this method and check return true mean its exist otherwise not.
public boolean checkAppointmentExist(String name){
booolean isExist = false;
String selection = COLUMN_TITLE + " = ? ";
String[] selectionArgs = new String[]{name};
Cursor cursor = database.query(TABLE_APPOINTMENTS, null, selection, selectionArgs, null, null, null);
if (cursor != null) {
if (cursor.getCount() > 0) {
isExist = true;
}
}
return isExist;
}
public void addAppointment(Appointment app){
if(!checkAppointmentExist(app.get_title())){
SQLiteDatabase db = getWritableDatabase();
ContentValues values = new ContentValues();
values.put(COLUMN_DAY, app.get_day());
values.put(COLUMN_MONTH, app.get_month());
values.put(COLUMN_YEAR, app.get_year());
values.put(COLUMN_TITLE, app.get_title()); // need to check that string being entered isn't already a unique entry
values.put(COLUMN_TIME, app.get_time());
values.put(COLUMN_DESCRIPTION, app.get_details());
db.insert(TABLE_APPOINTMENTS, null, values);
db.close();
}
}
This question already has answers here:
What is a stack trace, and how can I use it to debug my application errors?
(7 answers)
Closed 7 years ago.
I have two tables: user and balance.
User DAO:
public class NewUserDAO {
public static final String TAG = "NewUserDAO";
public static final String TABLE_NEWUSER = "newUser";
//database fields
private SQLiteDatabase mDataBase;
private DatabaseHandler mDbHelper;
private Context mContext;
private String [] mAllColumns = {
DatabaseHandler.COLUMN_NEWUSER_ID,
DatabaseHandler.COLUMN_NEWUSER_NAME, DatabaseHandler.COLUMN_NEW_USER_PASSWORD,
DatabaseHandler.COLUMN_NEW_USER_AGE };
public NewUserDAO(Context context){
this.mContext = context;
mDbHelper = new DatabaseHandler(context);
try{
open();
} catch (SQLException e){
Log.e(TAG,"SQLexception on opening database" + e.getMessage());
e.printStackTrace();
}
}
public void open() throws SQLException{
mDataBase = mDbHelper.getWritableDatabase();
}
public void close(){
mDbHelper.close();
}
public void createNewUser(NewUserTable newUserTable){
ContentValues values = new ContentValues();
values.put(DatabaseHandler.COLUMN_NEWUSER_NAME,newUserTable.getName());
values.put(DatabaseHandler.COLUMN_NEW_USER_PASSWORD, newUserTable.getPassword());
values.put(DatabaseHandler.COLUMN_NEW_USER_AGE, newUserTable.getAge());
mDataBase.insert(TABLE_NEWUSER, null, values);
mDataBase.close();
}
}
balance DAO:
public class BalanceDAO {
public static final String TAG = "BalanceDAO";
public static final String TABLE_BALANCE = "balanceOfUser";
private Context mContext;
//Database fields
private SQLiteDatabase mDatabase;
private DatabaseHandler mDhelper;
private String[] mAllColumns = {
DatabaseHandler.COLUMN_BALANCE_ID,
DatabaseHandler.COLUMN_BALANCE_DOLLARBALANCE,
DatabaseHandler.COLUMN_BALANCE_RUBBALANCE,
DatabaseHandler.COLUMN_BALANCE_NEW_USER_ID
};
public BalanceDAO (Context context){
mDhelper = new DatabaseHandler(context);
this.mContext = context;
try{
open();
}
catch (SQLException e){
Log.e(TAG, "SQLException on openning database" + e.getMessage());
e.printStackTrace();
}
}
public void open() throws SQLException {
mDatabase = mDhelper.getWritableDatabase();
}
public void close(){
mDhelper.close();
}
public void createBalance (BalanceTable balanceTable){
ContentValues values = new ContentValues();
values.put(DatabaseHandler.COLUMN_BALANCE_DOLLARBALANCE,balanceTable.getDollarBalance());
values.put(DatabaseHandler.COLUMN_BALANCE_RUBBALANCE,balanceTable.getRubBalance());
mDatabase.insert(TABLE_BALANCE, null, values);
mDatabase.close();
}
}
And SQLiteOpenHelper class:
public class DatabaseHandler extends SQLiteOpenHelper {
//COLUMNS OF THE NEW USER TABLE
public static final String TABLE_NEWUSER = "newUser";
public static final String COLUMN_NEWUSER_ID = "id";
public static final String COLUMN_NEWUSER_NAME = "name";
public static final String COLUMN_NEW_USER_PASSWORD = "password";
public static final String COLUMN_NEW_USER_AGE = "age";
//COLUMNS OF THE BALANCE TABLE
public static final String COLUMN_BALANCE_ID = "id";
public static final String TABLE_BALANCE = "balanceOfUser";
public static final String COLUMN_BALANCE_DOLLARBALANCE = "dollarBalance";
public static final String COLUMN_BALANCE_RUBBALANCE = "rubBalance";
public static final String COLUMN_BALANCE_NEW_USER_ID = "newUserId";
private static final String DATABASE_NAME = "webStore";
private static final int DATABASE_VERSION = 1;
public DatabaseHandler(Context context){
super(context, DATABASE_NAME, null, DATABASE_VERSION);
}
#Override
public void onOpen(SQLiteDatabase db) {
super.onOpen(db);
if (!db.isReadOnly()) {
// Enable foreign key constraints
db.execSQL("PRAGMA foreign_keys=ON;");
}
}
#Override
public void onCreate(SQLiteDatabase db) {
String SQL_CREATE_NEWUSER = "CREATE TABLE " + TABLE_NEWUSER + "("
+ COLUMN_NEWUSER_ID + " INTEGER PRIMARY KEY autoincrement,"
+ COLUMN_NEWUSER_NAME + " TEXT not null,"
+ COLUMN_NEW_USER_PASSWORD + " TEXT not null,"
+ COLUMN_NEW_USER_AGE + " INTEGER"
+ ")";
db.execSQL(SQL_CREATE_NEWUSER);
String SQL_CREATE_BALANCE = "CREATE TABLE " + TABLE_BALANCE + "("
+ COLUMN_BALANCE_ID + " INTEGER PRIMARY KEY autoincrement,"
+ COLUMN_BALANCE_DOLLARBALANCE + " INTEGER,"
+ COLUMN_BALANCE_RUBBALANCE + " INTEGER,"
+ COLUMN_BALANCE_NEW_USER_ID + " INTEGER," + "FOREIGN KEY("+COLUMN_BALANCE_NEW_USER_ID+") REFERENCES "
+ TABLE_NEWUSER + "(id) "+ ")" ;
db.execSQL(SQL_CREATE_BALANCE);
onCreate(db);
}
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
db.execSQL("DROP TABLE IF EXISTS " + TABLE_NEWUSER);
db.execSQL("DROP TABLE IF EXISTS " + TABLE_BALANCE);
}
}
I want to join user and balance tables. How can i do? When i call Create Method, i have exception.
public void CreateUser(View view) {
etName = (EditText)findViewById(R.id.etName);
etPassword = (EditText)findViewById(R.id.etPassword);
etAge = (EditText)findViewById(R.id.etAge);
String name = String.valueOf(etName.getText());
String password = String.valueOf(etPassword.getText());
int age = Integer.parseInt(String.valueOf(etAge.getText()));
BalanceTable balanceTable = new BalanceTable(0,0);
NewUserTable newUserTable = new NewUserTable(name,password,age);
//write to database of user from our edit texts
DatabaseHandler databaseHandler = new DatabaseHandler(this);
Log.d("Insert: ", "Inserting ..");
NewUserDAO dbForUser = new NewUserDAO(this);
dbForUser.createNewUser(newUserTable);
BalanceDAO balanceDAO = new BalanceDAO(this);
balanceDAO.createBalance(balanceTable);
}
From edit text i take data. Help please
There are a few types if join, inner (which I think is what you want) which shows the data that matches, left showing all data from the first table and any additional data from the second table that meets the on condition or right which is shows all from the second table and any form the right that matches.
to Join two table you must use a statement such as
"SELECT <all the values you want> "+
" FROM users" +
" left join balance" +
" ON users.id=balance.userid " +
" where <some condition> "+
" order by gmttimestamp ;"; "
this will give you result set of mixed tables
Heyhey :)
I looked at several Questions to the same topic, but I found no solution to my problem.
A NullPointerException at this.getReadableDatabase(); appears...
Here's my Code:
public class DatabaseHandler extends SQLiteOpenHelper {
public static final int DATABASE_VERSION = 1;
public static final String DATABASE_NAME = "TODO_APP";
/*--------------------------- TABLE ITEMS START ---------------------------*/
private static final String TABLE_ITEMS = "items";
private static String KEY_ID_ITEMS = "id_items";
private static final String KEY_CATEGORY_ITEMS = "category";
private static final String KEY_DATETIME_ITEMS = "datetime";
private static String KEY_NAME_ITEMS = "name";
private static final String KEY_DESCRIPTION_ITEMS = "description";
private static final String KEY_ALARM_ITEMS = "alarm";
public DatabaseHandler(Context context) {
super(context, DATABASE_NAME, null, DATABASE_VERSION);
}
#Override
public void onCreate(SQLiteDatabase db) {
// create table ITEMS
String CREATE_ITEMS_TABLE = "CREATE TABLE " + TABLE_ITEMS + "("
+ KEY_ID_ITEMS + " INTEGER PRIMARY KEY," + KEY_CATEGORY_ITEMS
+ " INTEGER," + KEY_DATETIME_ITEMS
+ " TIMESTAMP DEFAULT CURRENT_TIMESTAMP," + KEY_NAME_ITEMS
+ " TEXT," + KEY_DESCRIPTION_ITEMS + " TEXT," + KEY_ALARM_ITEMS
+ " INTEGER" + ");";
db.execSQL(CREATE_ITEMS_TABLE);
}
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
// Drop older table if existed
db.execSQL("DROP TABLE IF EXISTS " + TABLE_ITEMS);
// Create tables again
this.onCreate(db);
}
public void addItem(DB_Item item) {
SQLiteDatabase db = this.getWritableDatabase();
ContentValues values = new ContentValues();
values.put(KEY_CATEGORY_ITEMS, item.getCategory());
values.put(KEY_NAME_ITEMS, item.getName());
values.put(KEY_DESCRIPTION_ITEMS, item.getDescription());
values.put(KEY_ALARM_ITEMS, item.getAlarm());
// Inserting Row
db.insert(TABLE_ITEMS, null, values);
db.close(); // Closing database connection
}
public DB_Item getItem(String name) {
//!!!!! Here is one problem !!!!!
SQLiteDatabase db = this.getReadableDatabase();
Cursor cursor = db.query(TABLE_ITEMS, new String[] { KEY_ID_ITEMS,
KEY_CATEGORY_ITEMS, KEY_DATETIME_ITEMS, KEY_NAME_ITEMS,
KEY_DESCRIPTION_ITEMS, KEY_ALARM_ITEMS },
KEY_NAME_ITEMS = " = ?", new String[] { String.valueOf(name) },
null, null, null, null);
if (cursor != null) {
cursor.moveToFirst();
}
// DB_Item (int category, String name, String description, int
// alarm)
DB_Item item = new DB_Item(cursor.getInt(1), cursor.getString(3),
cursor.getString(4), cursor.getInt(5));
return item;
}
public List<DB_Item> getAllItems() {
List<DB_Item> itemList = new ArrayList<DB_Item>();
// SELECT ALL
String selectQuery = "SELECT * FROM " + TABLE_ITEMS;
//!!!!!!!!!! here is the other Problem
SQLiteDatabase database = this.getWritableDatabase();
Cursor cursor = database.rawQuery(selectQuery, null);
// go through all rows and then adding to list
if (cursor.moveToFirst()) {
do {
DB_Item item = new DB_Item();
item.setCategory(Integer.parseInt(cursor.getString(0)));
// TODO
// adding to list
itemList.add(item);
} while (cursor.moveToNext());
}
return itemList;
}
[and so on, didn't copy the whole code]
Hope you can help me...
The error appears definitely at SQLiteDatabase db = this.getReadableDatabase();
Output:
09-03 08:34:17.863: E/AndroidRuntime(7074): java.lang.RuntimeException: Unable to start activity ComponentInfo{todo.todo_list/todo.view.StartApp}: java.lang.NullPointerException
09-03 08:34:17.863: E/AndroidRuntime(7074): at todo.database.DatabaseHandler.getAllItems(DatabaseHandler.java:144)
09-03 08:34:17.863: E/AndroidRuntime(7074): at todo.helper.SortItems.sortItemsCategory(SortItems.java:16)
09-03 08:34:17.863: E/AndroidRuntime(7074): at todo.view.StartApp.onCreate(StartApp.java:36)
chnage you class to something like this:
package com.mhp.example;
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 {
/*--------------------------- TABLE ITEMS START ---------------------------*/
private static final String TABLE_ITEMS = "items";
private static String KEY_ID_ITEMS = "id_items";
private static final String KEY_CATEGORY_ITEMS = "category";
private static final String KEY_DATETIME_ITEMS = "datetime";
private static String KEY_NAME_ITEMS = "name";
private static final String KEY_DESCRIPTION_ITEMS = "description";
private static final String KEY_ALARM_ITEMS = "alarm";
private static final String TAG = "DBAdapter";
private static final String DATABASE_NAME = "dbname";
private static final int DATABASE_VERSION = 1;
tring CREATE_ITEMS_TABLE = "CREATE TABLE " + TABLE_ITEMS + "("
+ KEY_ID_ITEMS + " INTEGER PRIMARY KEY," + KEY_CATEGORY_ITEMS
+ " INTEGER," + KEY_DATETIME_ITEMS
+ " TIMESTAMP DEFAULT CURRENT_TIMESTAMP," + KEY_NAME_ITEMS
+ " TEXT," + KEY_DESCRIPTION_ITEMS + " TEXT," + KEY_ALARM_ITEMS
+ " INTEGER" + ");";
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(CREATE_ITEMS_TABLE);
} 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 contacts");
onCreate(db);
}
}
//---opens the database---
public DBAdapter open() throws SQLException
{
db = DBHelper.getWritableDatabase();
return this;
}
//---closes the database---
public void close()
{
DBHelper.close();
}
public void addItem(DB_Item item) {
ContentValues values = new ContentValues();
values.put(KEY_CATEGORY_ITEMS, item.getCategory());
values.put(KEY_NAME_ITEMS, item.getName());
values.put(KEY_DESCRIPTION_ITEMS, item.getDescription());
values.put(KEY_ALARM_ITEMS, item.getAlarm());
// Inserting Row
db.insert(TABLE_ITEMS, null, values);
}
public DB_Item getItem(String name) {
Cursor cursor = db.query(TABLE_ITEMS, new String[] { KEY_ID_ITEMS,
KEY_CATEGORY_ITEMS, KEY_DATETIME_ITEMS, KEY_NAME_ITEMS,
KEY_DESCRIPTION_ITEMS, KEY_ALARM_ITEMS },
KEY_NAME_ITEMS = " = ?", new String[] { String.valueOf(name) },
null, null, null, null);
if (cursor != null) {
cursor.moveToFirst();
}
// DB_Item (int category, String name, String description, int
// alarm)
DB_Item item = new DB_Item(cursor.getInt(1), cursor.getString(3),
cursor.getString(4), cursor.getInt(5));
return item;
}
public List<DB_Item> getAllItems() {
List<DB_Item> itemList = new ArrayList<DB_Item>();
// SELECT ALL
String selectQuery = "SELECT * FROM " + TABLE_ITEMS;
Cursor cursor = db.rawQuery(selectQuery, null);
// go through all rows and then adding to list
if (cursor.moveToFirst()) {
do {
DB_Item item = new DB_Item();
item.setCategory(Integer.parseInt(cursor.getString(0)));
// TODO
// adding to list
itemList.add(item);
} while (cursor.moveToNext());
}
return itemList;
}
}
NOTE: when you create object from DBAdapter,you should open() db and after your work close() it.
DBAdapter db = new DBAdapter(contex);
db.open();
//do you work
db.close();
Just use getReadableDatabase() without this.