couldn't get values from sqlite table - java

In my application I want save data in database.
Here is my code of SQLiteHelper
public class UserSqliteHelper extends SQLiteOpenHelper {
private final String LOGCAT = "JBF/SQLite";
private static final int DATABASE_VERSION = 1;
// Database Name
private static final String DATABASE_NAME = "jbfjsonEntityDB";
private static final String TABLE_NAME = "jbfjsonEntity";
private static final String KEY_JSON = "json";
private static final String KEY_URL_PATH = "url_path";
private static final String KEY_TIME = "added_on";
public UserSqliteHelper(Context context) {
super(context, "dictionarysqlitehelper.db", null, 1);
Log.d(LOGCAT, "Created");
}
#Override
public void onCreate(SQLiteDatabase db) {
String CREATE_CONTACTS_TABLE = "CREATE TABLE " + TABLE_NAME + "("
+ KEY_JSON + " TEXT, "
+ KEY_TIME + " TIMESTAMP NOT NULL DEFAULT current_timestamp, "
+ KEY_URL_PATH + " TEXT )";
db.execSQL(CREATE_CONTACTS_TABLE);
}
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
String query = "DROP TABLE IF EXISTS " + TABLE_NAME ;
db.execSQL(query); onCreate(db);
}
public void addJsonEntity(JsonEntity jsonEntity) {
SQLiteDatabase db = this.getWritableDatabase();
ContentValues values = new ContentValues();
values.put(KEY_JSON, jsonEntity.getJson());
values.put(KEY_URL_PATH, jsonEntity.getUrl_path());
// Inserting Row
db.insert(TABLE_NAME, null, values);
db.close();
}
public JSONObject getJsonByUrl(String url) {
String json = "";
SQLiteDatabase db = this.getReadableDatabase();
try {
// Cursor c = db.query(TABLE_NAME, null, KEY_URL_PATH + "=?", new String[]{url}, null, null, null);
String selectQuery = "SELECT * FROM " + TABLE_NAME + " where " + KEY_URL_PATH + "='"+url+"'";
Cursor c = db.rawQuery(selectQuery, null);
if (c == null) {
return null;
} else {
c.moveToFirst();
json =c.getString(c.getColumnIndex(KEY_JSON));
if (json != null) {
return new JSONObject(json);
} else {
return null;
}
}
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
}
When I call from my activity this
UserSqliteHelper sqliteHelper = new UserSqliteHelper(SplashActivity.this);
sqliteHelper.getWritableDatabase();
sqliteHelper.addJsonEntity(new JsonEntity(STRING_CONFIGS_URL,response.toString()));
System.out.println("json ==== "+sqliteHelper.getJsonByUrl(GET_USER_INFO_URL));
I always got this error
android.database.CursorIndexOutOfBoundsException: Index 0 requested, with a size of 0
Could anyone tell me what I did wrong in here. Why I can't get my database values?

The query didn't match any data. moveToFirst() fails and the cursor doesn't point to a valid row. You should check that moveToFirst() succeeds - it returns a boolean.
Why it didn't match any data is because you're storing and retrieving data by different keys: STRING_CONFIGS_URL and GET_USER_INFO_URL.

instead of c==null try c.getColumnCount == 0

Related

E/SQLiteLog: (1) table Estudiantes has no column named calificacion in android

This is the class that I´m using
public class DBHelper extends SQLiteOpenHelper {
private static final String DB_FILE = "Database.db";
private static final String TABLE = "Estudiantes";
private static final String FIELD_ID = "id";
private static final String FIELD_NAME = "nombre";
private static final String FIELD_GRADE = "calificacion";
public DBHelper(Context context){
super(context, DB_FILE, null, 1);
}
#Override
public void onCreate(SQLiteDatabase db) {
String query = "CREATE TABLE " + TABLE + "(" +
FIELD_ID + " INTEGER PRIMARY KEY, " +
FIELD_NAME + " TEXT, " +
FIELD_GRADE + " INTEGER);";
db.execSQL(query);
}
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
String query = "DROP TABLE IF EXISTS ?";
String[] params = {TABLE};
db.execSQL(query, params);
}
public void save(String nombre, int calificacion){
SQLiteDatabase db = getWritableDatabase();
ContentValues valores = new ContentValues();
valores.put(FIELD_NAME, nombre);
valores.put(FIELD_GRADE, calificacion);
db.insert(TABLE, null, valores);
}
public int delete(String nombre){
SQLiteDatabase db = getWritableDatabase();
String clause = FIELD_NAME + " = ?";
String[] args = {nombre};
return db.delete(TABLE, clause, args);
}
public int find(String nombre){
SQLiteDatabase db = getReadableDatabase();
String filtrito = FIELD_NAME + " = ?";
String[] args = {nombre};
Cursor c = db.query(TABLE, null, filtrito, args, null, null, null);
int result = -1;
if(c.moveToFirst()) {
result = c.getInt(2);
}
return result;
}
}
This is the error message I get:
E/SQLiteLog: (1) table Estudiantes has no column named calificacion
E/SQLiteDatabase: Error inserting calificacion=80 nombre=Fer
android.database.sqlite.SQLiteException:
table Estudiantes has no column named calificacion (code 1): , while compiling:
INSERT INTO Estudiantes(calificacion,nombre) VALUES (?,?)
It looks like that you added calificacion column later in the database.
I would do one of the following:
Uninstalling and re-installing your app.
The best and better approach is to drop and recreate Estudiantes table in onUpdate method, and increase the db version wheneveryou change the schema.

How to Show SQLite table in Logcat

Database Helper
public class DatabaseHelper extends SQLiteOpenHelper {
// Table Name
public static final String TABLE_NAME = "Contacts";
// Table columns
public static final String ID = "ID";
public static final String Contact_Name = "Contact_Name";
public static final String Phone_Number = "Phone_Number";
public static final String Favourites = "Favourites";
// Database Information
static final String DB_NAME = "MessagePlus_Contacts";
// database version
static final int DB_VERSION = 1;
// Creating table query
private static final String CREATE_TABLE = "Create Table " + TABLE_NAME + "(" + ID
+ " INTEGER PRIMARY KEY AUTOINCREMENT, " + Contact_Name + " TEXT NOT NULL, " + Phone_Number + " INT NOT NULL, " + Favourites + " Boolean NOT NULL);";
private static final String Show_Table = "Select * From " + TABLE_NAME;
public DatabaseHelper(Context context) {
super(context, DB_NAME, null, DB_VERSION);
}
#Override
public void onCreate(SQLiteDatabase db) {
db.execSQL(CREATE_TABLE);
}
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
db.execSQL("DROP TABLE IF EXISTS " + TABLE_NAME);
onCreate(db);
}
public void showData(SQLiteDatabase db){db.execSQL(Show_Table);}
public void insertData(String contactName, String phoneNumber,String favourites) {
SQLiteDatabase db = this.getWritableDatabase();
ContentValues values = new ContentValues();
values.put(DatabaseHelper.Contact_Name, contactName);
values.put(DatabaseHelper.Phone_Number, phoneNumber);
values.put(DatabaseHelper.Favourites, favourites);
db.insert(DatabaseHelper.TABLE_NAME, null, values);
// close db connection
db.close();
}
public int addToFavourites(String favourites) {
SQLiteDatabase db = this.getWritableDatabase();
ContentValues values = new ContentValues();
values.put(DatabaseHelper.Favourites, favourites);
// updating row
return db.update(DatabaseHelper.TABLE_NAME, values, DatabaseHelper.Phone_Number + " = ?", new String[]{favourites});
}
public int getCount() {
String countQuery = "SELECT * FROM " + DatabaseHelper.TABLE_NAME;
SQLiteDatabase db = this.getReadableDatabase();
Cursor cursor = db.rawQuery(countQuery, null);
int count = cursor.getCount();
cursor.close();
// return count
return count;
}
Modal
public class FavouritesHelper {
public String Name;
public String PhoneNumber;
public boolean Favourites;
public FavouritesHelper() {
}
public FavouritesHelper(String Name, String PhoneNumber, Boolean Favourites) {
this.Name = Name;
this.PhoneNumber = PhoneNumber;
this.Favourites = Favourites;
}
public String getName() {
return Name;
}
public void setName(String Name) {
this.Name = Name;
}
public String getPhoneNumber() {
return PhoneNumber;
}
public void setPhoneNumber(String PhoneNumber) {
this.PhoneNumber = PhoneNumber;
}
public boolean getFavourites() {
return Favourites;
}
public void setFavourites(boolean Favourites) {
this.Favourites = Favourites;
}
}
This is my database helper and I'm trying to fetch the table in logcat but I don't know how to do that. I know the code is Select * from <tablename> but how do i implement that. I want to see all the data in my table.
Soltion:
Please follow the following steps:
First Step:
Make the below method in DatabaseHelper class:
public List<FavouritesHelper> getAllData() {
List<FavouritesHelper> data = new ArrayList<>();
// Select All Query
String selectQuery = "SELECT * FROM " + FavouritesHelper.TABLE_NAME;
SQLiteDatabase db = this.getWritableDatabase();
Cursor cursor = db.rawQuery(selectQuery, null);
// looping through all rows and adding to list
if (cursor.moveToFirst()) {
do {
FavouritesHelper alldata = new FavouritesHelper();
alldata.setName(cursor.getString(cursor.getColumnIndex(FavouritesHelper.Name)));
alldata.setPhoneNumber(cursor.getString(cursor.getColumnIndex(FavouritesHelper.PhoneNumber)));
alldata.setFavourites(cursor.getBoolean(cursor.getColumnIndex(FavouritesHelper.Favourites)));
data.add(alldata);
} while (cursor.moveToNext());
}
// close db connection
db.close();
// return notes list
return data;
}
Second Step:
In your activity:
declare a global object: List<FavouritesHelper> AllData inside your class.
Third Step:
then, add this AllData = new List<FavouritesHelper>(); in your onCreate()
Fourth Step:
write this in your activity after inserting data: AllData = database.getAllData();
Fifth Step:
Print it in log using below statement:
for(FavouritesHelper helper : AllData) {
Log.e("values : ", helper.getName() + ", " + helper.getPhoneNumber() + ", " + helper.getFavourites());
}
That's it.
Try it out. Hope it Helps.
As #pskink suggested you can use dumpCursor like this
create this method inside your DatabaseHelper class
public void dumpCursorInLogCat() {
//here first getting the readable database
SQLiteDatabase db = this.getReadableDatabase();
Cursor cursor = db.rawQuery(Show_Table, null);
//here is how you can Dump cursor
DatabaseUtils.dumpCursor(cursor);
cursor.close();
}
and call this method in your activity whenever you want to show data in logcat
call it inside your activity like
new DatabaseHelper(your_activity_name.this).dumpCursorInLogCat();

SQLite DataBase Read Error 'no such file or directory '

Hello I was working with SQlite on my phone with android studio
I have a simple database like this :
DATABASE 1 :
public class myDbAdapter {
myDbHelper myhelper;
public myDbAdapter(Context context) {
myhelper = new myDbHelper(context);
}
public long insertData(String name, String ip, String port, String rele) {
SQLiteDatabase dbb = myhelper.getWritableDatabase();
ContentValues contentValues = new ContentValues();
contentValues.put(myDbHelper.NAME, name);
/* ... same for more items ...*/
long id = dbb.insert(TABLE_NAME, null, contentValues);
return id;
}
public String getData() {
SQLiteDatabase db = myhelper.getWritableDatabase();
String[] columns = {myDbHelper.UID, myDbHelper.NAME, myDbHelper.IP, myDbHelper.PORT, myDbHelper.RELE, myDbHelper.Hash};
Cursor cursor = db.query(TABLE_NAME, columns, null, null, null, null, null);
StringBuffer buffer = new StringBuffer();
int i = 0;
while (cursor.moveToNext()) {
i++;
int cid = cursor.getInt(cursor.getColumnIndex(myDbHelper.UID));
String name = cursor.getString(cursor.getColumnIndex(myDbHelper.NAME));
String ipE = cursor.getString(cursor.getColumnIndex(myDbHelper.IPE));
/* ... same for more items ...*/
buffer.append("*" + cid + "-" + name + "-" + ipE + "-" + port + "-" + rele + "\n");
}
List1.colu = i;
return buffer.toString();
}
public int delete(String uid) {
SQLiteDatabase db = myhelper.getWritableDatabase();
String delgrp = "DELETE FROM " + TABLE_NAME + " WHERE _id='" + uid + "'";
db.execSQL(delgrp);
return 1;
}
static class myDbHelper extends SQLiteOpenHelper {
public static final String DATABASE_NAME = "myDatabase"; // Database Name
public static final String TABLE_NAME = "Data"; // Table Name
private static final int DATABASE_Version = 1; // Database Version
private static final String UID = "_id"; // Column I (Primary Key)
/* ... same for more items ...*/
private static final String CREATE_TABLE = "CREATE TABLE " + TABLE_NAME +
" (" + UID + " INTEGER PRIMARY KEY AUTOINCREMENT, " + NAME + " VARCHAR(255) ," + IPE + " VARCHAR(255) ," + TEST1 + " VARCHAR(255) ," + TEST2 + " VARCHAR(255) ," + Hash + " VARCHAR(225));";
private static final String DROP_TABLE = "DROP TABLE IF EXISTS " + TABLE_NAME;
private Context context;
public myDbHelper(Context context) {
super(context, DATABASE_NAME, null, DATABASE_Version);
this.context = context;
}
public void onCreate(SQLiteDatabase db) {
try {
db.execSQL(CREATE_TABLE);
} catch (Exception e) {
// Message.message(context,""+e);
}
}
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
try {
// Message.message(context,"OnUpgrade");
db.execSQL(DROP_TABLE);
onCreate(db);
} catch (Exception e) {
// Message.message(context,""+e);
}
}
}
I Wanted to add another TABLE to same database (MyDataBase)
So i created another java class named MyDbAdapter2
Same codes as above just changed class names and Table name
helper = new myDbAdapter(this);
helper2 = new myDbAdapter2(this);
DATABASE 2 :
public class myDbAdapter2 {
myDbHelper myhelper;
public myDbAdapter2(Context context) {
myhelper = new myDbHelper(context);
}
public long insertData(String name, String ip) {
/*...*/
}
public String getData() {
SQLiteDatabase db = myhelper.getWritableDatabase();
String[] columns = {myDbHelper.UID, myDbHelper.ITEM, myDbHelper.SUBITEM};
Cursor cursor = db.query(TABLE_NAME, columns, null, null, null, null, null);
StringBuffer buffer = new StringBuffer();
int i = 0;
while (cursor.moveToNext()) {
i++;
int cid = cursor.getInt(cursor.getColumnIndex(myDbHelper.UID));
String name = cursor.getString(cursor.getColumnIndex(myDbHelper.ITEM));
String ipe = cursor.getString(cursor.getColumnIndex(myDbHelper.SUBITEM));
buffer.append("*" + cid + "-" + name + "-" + ipe + "\n");
}
// List1.colu=i;
return buffer.toString();
}
static class myDbHelper extends SQLiteOpenHelper {
public static final String DATABASE_NAME = "myDatabase"; // Database Name
public static final String TABLE_NAME = "Data2"; // Table Name
private static final int DATABASE_Version = 1; // Database Version
private static final String UID = "_id"; // Column I (Primary Key)
/*...*/ //Column II
// ... // Column III
private static final String CREATE_TABLE = "CREATE TABLE " + TABLE_NAME +
" (" + UID + " INTEGER PRIMARY KEY AUTOINCREMENT, " + ITEM + " VARCHAR(255) ," + SUBITEM + " VARCHAR(225));";
private static final String DROP_TABLE = "DROP TABLE IF EXISTS " + TABLE_NAME;
private Context context;
public myDbHelper(Context context) {
super(context, DATABASE_NAME, null, DATABASE_Version);
this.context = context;
}
public void onCreate(SQLiteDatabase db) {
try {
db.execSQL(CREATE_TABLE);
} catch (Exception e) {
// Message.message(context,""+e);
}
}
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
try {
// Message.message(context,"OnUpgrade");
db.execSQL(DROP_TABLE);
onCreate(db);
}catch (Exception e) {
// Message.message(context,""+e);
}
}
}
}
When i try to access the other (Data2) database it cause a error !
android.database.sqlite.SQLiteException: no such table: Data2 (Sqlite code 1): , while compiling: SELECT _id, Item, SubItem FROM Data2, (OS error - 2:No such file or directory)
I Saw this on Log :
09-13 09:31:05.788 18454-18454/com.example.discopc.yubismart I/HwSecImmHelper: mSecurityInputMethodService is null
09-13 09:31:06.468 18454-18604/com.example.discopc.yubismart E/SQLiteLog: (1)
09-13 09:31:06.571 18454-18604/com.example.discopc.yubismart I/Process: Sending signal. PID: 18454 SIG: 9
Whats the problem ? First database works fine but second one not ,
Thanks.... ?
As you said - I Wanted to add another TABLE to same database (MyDataBase)
You should not use two different class for creating two different table in sqlite database. While executing one single of your adapter classes its creating one table and if your db version is same / different in adapter classes then one of two table would not be created / would be deleted.
Here db version is same that's why second table is not creating.
Create as many as your required tables inside onCreate() of your myDbHelper class and inside onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) execute drop table code for each table.
When you need another new table just create table as above and write code for drop table inside onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion).
You just need to remember for creating new tables or any structural change inside your sqlite database would be reflected only after changing the VERSION CODE of database.
You have created a database once with name MyDataBase having table Data.
You are again trying to create same MyDataBase with table Data2 that is causing the problem.
"I Want to create only 1 database , changing name to MyDataBase2 will work but why ?"
When you are changing name to MyDataBase2 it works as this one is a completely new database and you can create the Data2 table in it.
So if you want to create Data2 in your first version of database you have to create the table Data2 in it but not a completely new data base. If you want to know more about it please find it here.
I believe this answered your question.

Why am i using result.getInt(2) / result.getInt(3) and result.getString(0)

I am abit confused why in the RoutineRetrieved function I am using result.getInt(2) when assigning the ACTIVITYIMAGE and result.getInt(3) when assigning the SLOT.... while in the ColourChange function I am using result.getInt(0) when assigning the DAY.
I previously assumed I was pointing to the columns in my sqlite database. But now I am confused. Could someone explain what these numbers mean?
RoutineRetrieved function:
private void routineRetrieved() {
Cursor result = myDb.retrieveRoutine(currentDay);
if (result.getCount() == 0) {
// Do nothing
} else {
while (result.moveToNext()) {
int ActivityImage = result.getInt(2);
int Slot = result.getInt(3);
ImageView emptySlot = (ImageView) findViewById(Slot);
emptySlot.setImageResource(ActivityImage);
}
}
}
ColourChange function:
private void colourChange() {
Cursor result = myDb.checkColour();
if (result.getCount() == 0) {
// Default colour remains
} else {
while (result.moveToNext()) {
String day = result.getString(0);
findViewById(getResources().getIdentifier(day + "button", "id", getPackageName()))
.setBackgroundColor(getResources().getColor(R.color.colorSuccess));
}
}
}
Database.java
public class Database extends SQLiteOpenHelper
{
public static final String DATABASE_NAME = "application.db";
public static final int DATABASE_VERSION = 9;
// Table Name
public static final String RoutineTable = "Routines";
// Column Names
public static final String RoutineColumn1 = "DayOfWeek";
public static final String RoutineColumn2 = "Activity";
public static final String RoutineColumn3 = "Slot";
public Database(Context context)
{
super(context, DATABASE_NAME, null, DATABASE_VERSION);
}
#Override
public void onCreate(SQLiteDatabase db) {
db.execSQL("CREATE TABLE `Routines` (`Routine` INTEGER NOT NULL PRIMARY KEY AUTOINCREMENT,`DayOfWeek` TEXT NOT NULL,`Activity` INTEGER NOT NULL, `Slot` INTEGER NOT NULL);");
}
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion)
{
onCreate(db);
}
public Cursor retrieveRoutine(String selectedDay) { WHERE DayOfWeek equals selectedDay and store this as result.
SQLiteDatabase db = this.getWritableDatabase();
Cursor result = db.rawQuery("select * from " + RoutineTable + " WHERE DayOfWeek = '" + selectedDay + "'", null);
return result;
}
public boolean insertRoutine(int activityImage, String selectedDay, int activitySlot) {
SQLiteDatabase db = this.getWritableDatabase();
ContentValues contentValues = new ContentValues();
contentValues.put(RoutineColumn1,selectedDay);
contentValues.put(RoutineColumn2,activityImage);
contentValues.put(RoutineColumn3,activitySlot);
long result = db.insert(RoutineTable, null, contentValues);
if(result == -1)
return false;
else
return true;
}
public Cursor checkColour() {
SQLiteDatabase db = this.getWritableDatabase();
Cursor result = db.rawQuery("SELECT DayOfWeek FROM " + RoutineTable + " GROUP BY DayOfWeek", null);
return result;
}
The number parameter in the methods getInt and getString is index, starting by 0, of the column you want to get, relatively to the query you've done.
You have 2 different queries. In the method checkColour() you have the following query, which have only one field:
"SELECT DayOfWeek FROM " + RoutineTable + " GROUP BY DayOfWeek"
So, when you call
Cursor result = myDb.retrieveRoutine(currentDay);
String fieldValue = result.getString(0);
fieldValue will have the value of the first field of the query, in this case DayOfWeek
The same in the other query, that is a SELECT * of the table Routines. In this case the index refers to the field position in the CREATE TABLE statement.

java.lang.NumberFormatException: Invalid int: "null"

The method getAllActivities() must return all activities from database in array list format
But I got: java.lang.NumberFormatException: Invalid int: "null",
at activity.setActivityType(Integer.parseInt(cursor.getString(1)));
I don't know what is wrong
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.SQLiteStatement;
import com.yast.util.Constants;
import com.yast.util.Utils;
import java.util.ArrayList;
import java.util.List;
public class DatabaseHandler extends SQLiteOpenHelper {
private static final int DATABASE_VERSION = 1;
private static final String DATABASE_NAME = "YastDB.db";
// Activities table name
private static final String TABLE_ACTIVITIES = "Activities";
// Activities Table Columns names
private static final String KEY_ID = "id";
private static final String KEY_ACTIVITYTYPE = "ActivityType";
private static final String KEY_HARTRATE = "HartRate";
private static final String KEY_HARTBATNO = "HartBatNo";
private static final String KEY_DISTANCE = "Distance";
private static final String KEY_SPEED = "Speed";
private static final String KEY_STRIDES = "Strides";
private static final String KEY_STARTDATETIME = "StartDateTime";
private static final String KEY_ENDDATETIME = "EndDateTime";
public static final String KEY_CURRENTDATETIME = "CurrentDateTime";
private String[] PROJECTION = new String[]{ KEY_ID,
KEY_ACTIVITYTYPE, KEY_HARTRATE,KEY_HARTBATNO, KEY_DISTANCE,
KEY_SPEED,KEY_STRIDES,KEY_STARTDATETIME,KEY_ENDDATETIME
,KEY_CURRENTDATETIME};
public DatabaseHandler(Context context) {
super(context, DATABASE_NAME, null, DATABASE_VERSION);
}
// Creating Tables
#Override
public void onCreate(SQLiteDatabase db) {
String CREATE_Activitys_TABLE = "CREATE TABLE " + TABLE_ACTIVITIES + "("
+ KEY_ID + " INTEGER PRIMARY KEY AUTOINCREMENT," +
KEY_ACTIVITYTYPE + " INTEGER,"+
KEY_HARTRATE + " INTEGER, "+
KEY_HARTBATNO + " INTEGER,"+
KEY_DISTANCE + " INTEGER," +
KEY_SPEED + " INTEGER," +
KEY_STRIDES + " INTEGER," +
KEY_STARTDATETIME + " TEXT," +
KEY_ENDDATETIME + " TEXT," +
KEY_CURRENTDATETIME + " TEXT" +
")";
db.execSQL(CREATE_Activitys_TABLE);
}
// Upgrading database
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
// Drop older table if existed
db.execSQL("DROP TABLE IF EXISTS " + TABLE_ACTIVITIES);
// Create tables again
onCreate(db);
}
//CRUD operations (Create, Read, Update and Delete)
// Adding new activity
public void addActivity(ActivityEntity activity) {
SQLiteDatabase db = this.getWritableDatabase();
ContentValues values = new ContentValues();
values.put(KEY_ACTIVITYTYPE, activity.getActivityType()); // Activity type
values.put(KEY_HARTRATE, activity.getHartRate());
values.put(KEY_HARTBATNO, activity.getHartBatNo());
values.put(KEY_DISTANCE, activity.getDistance());
values.put(KEY_SPEED, activity.getSpeed());
values.put(KEY_STRIDES, activity.getStrides());
values.put(KEY_STARTDATETIME,activity.getStartDateTime().toString());
values.put(KEY_ENDDATETIME, activity.getEndDateTime().toString());
values.put(KEY_CURRENTDATETIME, activity.getCurrentDateTime().toString());
// Inserting Row
db.insert(TABLE_ACTIVITIES, null, values);
db.close(); // Closing database connection
}
// Getting single Activity
/*
The following method getActivity() will read single contact row.
It accepts id as parameter and will return the matched row from the database.
*/
public ActivityEntity getActivity(int id) {
ActivityEntity activity = null;
SQLiteDatabase db = this.getReadableDatabase();
String where = KEY_ID + "=?";
String[] selectionArg = new String[]{String.valueOf(id)};
Cursor cursor = db.query(TABLE_ACTIVITIES, PROJECTION, where, selectionArg,
null, null, null, null);
if (cursor != null) {
cursor.moveToFirst();
activity = new ActivityEntity(Integer.parseInt(cursor.getString(0)),
Integer.parseInt(cursor.getString(1)),
Integer.parseInt(cursor.getString(2)),
Integer.parseInt(cursor.getString(3)),
Integer.parseInt(cursor.getString(4)),
Integer.parseInt(cursor.getString(5)),
Integer.parseInt(cursor.getString(6)),
cursor.getString(7),
cursor.getString(8),
cursor.getString(9));
}
return activity;
}
// Getting All Activities
public ArrayList<ActivityEntity> getAllActivitys() {
ArrayList<ActivityEntity> activitiesList = new ArrayList<ActivityEntity>();
SQLiteDatabase db = this.getWritableDatabase();
Cursor cursor = db.query(TABLE_ACTIVITIES, PROJECTION, null, null, null, null, null, null);
// looping through all rows and adding to list
if (cursor.moveToFirst()) {
do {
ActivityEntity activity = new ActivityEntity();
activity.setID(Integer.parseInt(cursor.getString(0)));
activity.setActivityType(Integer.parseInt(cursor.getString(1)));
activity.setHartRate(Integer.parseInt(cursor.getString(2)));
activity.setHartBatNo(Integer.parseInt(cursor.getString(3)));
activity.setDistance(Integer.parseInt(cursor.getString(4)));
activity.setSpeed(Integer.parseInt(cursor.getString(5)));
activity.setStrides(Integer.parseInt(cursor.getString(6)));
activity.setStartDateTime(cursor.getString(7));
activity.setEndDateTime(cursor.getString(8));
activity.set_currentDateTime(cursor.getString(9));
// Adding activity to list
activitiesList.add(activity);
} while (cursor.moveToNext());
}
return activitiesList;
}
public int getActivitiesCount() {
String countQuery = "SELECT * FROM " + TABLE_ACTIVITIES;
SQLiteDatabase db = this.getReadableDatabase();
Cursor cursor = db.rawQuery(countQuery, null);
cursor.close();
// return count
return cursor.getCount();
}
// Updating single Activity
public int updateActivity(ActivityEntity activity) {
SQLiteDatabase db = this.getWritableDatabase();
String where = KEY_ID + "=?";
ContentValues values = new ContentValues();
values.put(PROJECTION[1], activity.getActivityType());
values.put(PROJECTION[2], activity.getHartRate());
values.put(PROJECTION[3], activity.getHartBatNo());
values.put(PROJECTION[4], activity.getDistance());
values.put(PROJECTION[5], activity.getSpeed());
values.put(PROJECTION[6], activity.getStrides());
values.put(PROJECTION[7], activity.getStartDateTime().toString());
values.put(PROJECTION[8], activity.getEndDateTime().toString());
values.put(PROJECTION[9], activity.getCurrentDateTime().toString());
// updating row
return db.update(TABLE_ACTIVITIES, values, where, new String[] { String.valueOf(activity.getID()) });
}
public void deleteActivity(ActivityEntity activity)
{
String where = KEY_ID + "=?";
SQLiteDatabase db = this.getWritableDatabase();
db.delete(TABLE_ACTIVITIES, where,
new String[] { String.valueOf(activity.getID()) });
db.close();
}
public void bulkInsert(ArrayList<ActivityEntity> arrayOfActivities) {
SQLiteDatabase db = this.getWritableDatabase();
String sql = "INSERT INTO "+ TABLE_ACTIVITIES +" VALUES (?,?,?,?,?,?,?,?,?,?);";
SQLiteStatement statement = db.compileStatement(sql);
db.beginTransaction();
for (ActivityEntity a : arrayOfActivities ) {
statement.clearBindings();
statement.bindLong(1, (long) a.getID());
statement.bindLong(2, (long) a.getActivityType());
statement.bindLong(3, (long) a.getHartRate());
statement.bindLong(4, (long) a.getHartBatNo());
statement.bindLong(5, (long) a.getDistance());
statement.bindLong(6, (long) a.getSpeed());
statement.bindLong(7, (long) a.getStrides());
statement.bindString(8, a.getStartDateTime());
statement.bindString(9, a.getEndDateTime());
statement.bindString(10,a.getCurrentDateTime());
statement.clearBindings();
statement.execute();
}
db.setTransactionSuccessful();
db.endTransaction();
}
}
ActivityEntity.java calss:
import com.yast.util.Constants;
import com.yast.util.Utils;
import java.util.Date;
public class ActivityEntity {
int id;
int activityType;
int hartRate;
int hartBatNo;
int distance;
int speed;
int strides;
String startDateTime;
String endDateTime;
String currentDateTime;
public ActivityEntity(){
}
// constructor
public ActivityEntity(int Id, int activityType, int hartRate, int _hartBatNo, int distance, int speed, int strides, String startDateTime, String endDateTime, String currentDateTime){
this.id = Id;
this.activityType = activityType;
this.hartRate = hartRate;
this.hartBatNo = _hartBatNo;
this.distance = distance;
this.speed = speed;
this.strides = strides;
this.startDateTime = startDateTime;
this.endDateTime = endDateTime;
this.currentDateTime = currentDateTime;
}
public void setID(int id){
this.id = id;
}
public int getID(){
return this.id;
}
public void setActivityType(int activityType){
this.activityType = activityType;
}
public int getActivityType(){
return this.activityType;
}
public void setHartRate(int hartRate){
this.hartRate = hartRate;
}
public int getHartRate(){
return this.hartRate;
}
public void setHartBatNo(int hartBatNo){
this.hartBatNo = hartBatNo;
}
public int getHartBatNo(){
return this.hartBatNo;
}
public void setDistance(int distance){
this.distance = distance;
}
public int getDistance(){
return this.distance;
}
public void setSpeed(int speed){
this.speed = speed;
}
public int getSpeed(){
return this.speed;
}
public void setStrides(int strides){
this.strides = strides;
}
public int getStrides(){
return this.strides;
}
public void setStartDateTime(String startDateTime){
this.startDateTime = startDateTime;
}
public String getStartDateTime(){
return this.startDateTime;
}
public void setEndDateTime(String endDateTime){
this.endDateTime = endDateTime;
}
public String getEndDateTime(){
return this.endDateTime;
}
public void set_currentDateTime(String currentDateTime){
this.currentDateTime = currentDateTime;
}
public String getCurrentDateTime(){
return this.currentDateTime;
}
#Override
public String toString() {
return "ActivityEntity{" +
"id=" + id +
", activityType=" + activityType +
", hartRate=" + hartRate +
", hartBatNo=" + hartBatNo +
", distance=" + distance +
", speed=" + speed +
", strides=" + strides +
", startDateTime='" + startDateTime + '\'' +
", endDateTime='" + endDateTime + '\'' +
", currentDateTime='" + currentDateTime + '\'' +
'}';
}
}
in your code, if cursor.getString(int num) returns null, then Integer.parseInt(String str) will throw NumberFormatException.
To avoid this, you should have check for what the cursor.getString(int num) returns.
OR, you can use try-catch and print the appropriate message in catch if you'll get NumberFormatException.
You should check your cursor value is null or not.
if(cursor.isNull(column))
{
//Value is null
}else{
return cursor.getString(column);
}
Before you convert the value to Integer, you have to check whether the value is integer or not. If it is not an integer then replace it to default integer.
activity.setActivityType(Integer.parseInt(nulltoIntegerDefalt(cursor.getString(1))));
activity.setActivityType(Integer.parseInt(nulltoIntegerDefalt(cursor.getString(1))));
activity.setHartRate(Integer.parseInt(nulltoIntegerDefalt(cursor.getString(2))));
activity.setHartBatNo(Integer.parseInt(nulltoIntegerDefalt(cursor.getString(3))));
activity.setDistance(Integer.parseInt(nulltoIntegerDefalt(cursor.getString(4))));
activity.setSpeed(Integer.parseInt(nulltoIntegerDefalt(cursor.getString(5))));
activity.setStrides(Integer.parseInt(nulltoIntegerDefalt(cursor.getString(6))));
String nulltoIntegerDefalt(String value){
if(!isIntValue(value)) value="0";
return value;
}
boolean isIntValue(String val)
{
try {
val=val.replace(" ","");
Integer.parseInt(val);
} catch (Exception e) {return false;}
return true;
}
"null" isn't a valid int. Check for null first.
You need to be more careful checking for nullness:
1) cursor itself could be null
2) cursor.getString(1) could be null
Putting this together:
if (cursor != null && cursor.getString(1) != null){
/*your parse will be safe here*/
}
Note that I'm exploiting the fact that an if will evaluate from left to right and will stop evaluation once the result is known.
As an optimisation, you might want to store the result of cursor.getString(1) to prevent your having to evaluate this twice. But get the code working first.
Cursor cursor = db.query(TABLE_ACTIVITIES, PROJECTION, null, null, null, null, null, null);
Your SQL query string, the first null input in the query method, is null. You have not provided a query. I am assuming you want all columns from the table, so perhaps fill the query like:
String SQLSTATEMENT = "SELECT " + KEY_ID + "," + KEY_ACTIVITYTYPE + "," KEY_HARTRATE + "," KEY_HARTBATNO + "," KEY_DISTANCE + "," KEY_SPEED,KEY_STRIDES + "," KEY_STARTDATETIME + "," KEY_ENDDATETIM + "," KEY_CURRENTDATETIME;
Cursor cursor = db.query(TABLE_ACTIVITIES, PROJECTION, SQLSTATEMENT, null, null, null, null, null);
activity.setActivityType(Integer.parseInt(cursor.getString(1)));
in this cursor.getString(1) is getting null and That is why you are getting null pointer exception. Check for that String value.
The problem should be solved now, so I'm just solving the exception
An easier way is to change if(){}else{}" by "try{}catch(Exception e){}
Example :
try {
//Avoid/Éviter (FATAL EXCEPTION: main java.lang.NumberFormatException: Invalid int: "")
//exemple / Exemple d'action
int userWeight = Integer.parseInteger(userData);
Intent intent = new Intent(MainActivity.this, SecondActivity.class);
intent.putExtra("weight", userWeight);
// control Toast/Toast de contrôle
Toast.makeText(MainActivity.this, "OK", Toast.LENGTH_LONG).show();
}
catch (Exception e) {
Toast.makeText(MainActivity.this, "not OK", Toast.LENGTH_LONG).show();
}
Thanks to #user3091530 answer. I have used my own ParsInt method.
Create a class named Math.
public class Math {
//Checking the value if null return zero
public int ParsIntOrDefalt(String value){
return Integer.parseInt(NullIntegerDefalt(value));
}
private String NullIntegerDefalt(String value) {
if (!isIntValue(value)) value = "0";
return value;
}
private boolean isIntValue(String val){
try {
val=val.replace(" ","");
Integer.parseInt(val);
} catch (Exception e) {return false;}
return true;
}
}
So, we can use it instead of the main Integer.parseInt() method:
Math math = new Math();
activity.setActivityType(math.ParsIntOrDefalt(cursor.getString(1)));

Categories