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();
I am trying to create a simple SQLite database in android. I am following this tutorial. But the code gives this error "Cannot resolve constructor Contact()". Below is the code for DatabaseHandler.java. I have pointed out the line where the error occurs so it's easy to understand.
import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
import java.util.ArrayList;
import java.util.List;
/**
* Created by Usama on 10/7/2017.
*/
public class DatabaseHandler extends SQLiteOpenHelper {
// Database Version
private static final int DATABASE_VERSION = 1;
// Database Name
private static final String DATABASE_NAME = "favouritesmanager";
// Contacts table name
private static final String TABLE_CONTACTS = "favourites";
// Contacts Table Columns names
private static final String KEY_ID = "id";
private static final String KEY_NAME = "name";
private static final String KEY_PH_NO = "phone_number";
private static final String KEY_ADRESS = "adress";
public DatabaseHandler(Context context) {
super(context, DATABASE_NAME, null, DATABASE_VERSION);
}
// Creating Tables
#Override
public void onCreate(SQLiteDatabase db) {
String CREATE_CONTACTS_TABLE = "CREATE TABLE " + TABLE_CONTACTS + "("
+ KEY_ID + " INTEGER PRIMARY KEY," + KEY_NAME + " TEXT,"
+ KEY_PH_NO + " TEXT" + KEY_ADRESS + " TEXT" + ")";
db.execSQL(CREATE_CONTACTS_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_CONTACTS);
// Create tables again
onCreate(db);
}
// Adding new contact
public void addContact(Contact contact) {
SQLiteDatabase db = this.getWritableDatabase();
ContentValues values = new ContentValues();
values.put(KEY_NAME, contact.getName()); // Contact Name
values.put(KEY_PH_NO, contact.getPhoneNumber()); // Contact Phone Number
values.put(KEY_ADRESS, contact.getAdress()); //address
// Inserting Row
db.insert(TABLE_CONTACTS, null, values);
db.close(); // Closing database connection
}
// Getting All Contacts
public List<Contact> getAllContacts() {
List<Contact> contactList = new ArrayList<Contact>();
// Select All Query
String selectQuery = "SELECT * FROM " + TABLE_CONTACTS;
SQLiteDatabase db = this.getWritableDatabase();
Cursor cursor = db.rawQuery(selectQuery, null);
// looping through all rows and adding to list
if (cursor.moveToFirst()) {
do {
Contact contact = new Contact(); <<<< HERE IS THE ERROR
contact.setID(Integer.parseInt(cursor.getString(0)));
contact.setName(cursor.getString(1));
contact.setPhoneNumber(cursor.getString(2));
contact.setAdress(cursor.getString(3));
// Adding contact to list
contactList.add(contact);
} while (cursor.moveToNext());
}
// return contact list
return contactList;
}
}
and here is the contact.java class
public class Contact {
int _id;
String _name;
String _phone_number;
String _adress;
// constructor
public Contact(int id, String name, String _phone_number, String adress){
this._id = id;
this._name = name;
this._phone_number = _phone_number;
this._adress = adress;
}
// constructor
public Contact(String name, String _phone_number, String adress){
this._name = name;
this._phone_number = _phone_number;
this._adress = adress;
}
// getting ID
public int getID(){
return this._id;
}
// setting id
public void setID(int id){
this._id = id;
}
// getting name
public String getName(){
return this._name;
}
// setting name
public void setName(String name){
this._name = name;
}
// getting phone number
public String getPhoneNumber(){
return this._phone_number;
}
// setting phone number
public void setPhoneNumber(String phone_number){
this._phone_number = phone_number;
}
//getting adress
public String getAdress(){
return this._adress;
}
//setting adress
public void setAdress(String adresstowrite){
this._adress = adresstowrite;
}
}
Any fixes for this error please?
Create empty constructor.
// Empty constructor
public Contact(){
}
I have created a database in DB.java following various tutorials.
They have methods to get data and insert into the database using SQLite.
My questions are
1) How do I get DB.java to instantiate, as you see i have insertStudent("hello", "male", 4, "password", "computing", "module"); just for a bit of test data, I want to know what I would do with this in order for it to insert, I know I haven't called DB.java anywhere for it to do that, but I am unsure which way to go about it.
2) Once it has created the database, I want it to display the data from the database on the main activity. I decided to make the getData method static, then I called it in my main activity by using DB.getData(db); however it's stating db cannot be resolved to a variable. So i've messed up somewhere.
Any guidance is appreciated.
Below is my DB.java
package com.example.project;
import com.example.project.tableStudents.tableColumns;
import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteDatabase.CursorFactory;
import android.database.sqlite.SQLiteOpenHelper;
import android.util.Log;
public class DB extends SQLiteOpenHelper {
public static final int db_version = 1;
public static final String Table = "Students";
public static final String Student_ID = "Student_ID";
public static final String Student_Name = "Student_Name";
public static final String Student_Password = "Student_Password";
public static final String Student_Gender = "gender";
public static final String Student_Age = "age";
public static final String Student_Course = "course";
public static final String Student_Modules = "modules";
public DB(Context context) {
super(context, tableColumns.Database, null, db_version);
// Insert Students
insertStudent("hello", "male", 4, "password", "computing", "module");
}
#Override
public void onCreate(SQLiteDatabase db) {
//Create Table
db.execSQL("CREATE TABLE " + Table + "(" +
Student_ID + " INTEGER PRIMARY KEY, " +
Student_Name + " TEXT, " +
Student_Password + " TEXT, " +
Student_Gender + " TEXT, " +
Student_Age + " INTEGER, " +
Student_Course + " TEXT, " +
Student_Modules + "TEXT)"
);
Log.d("DB", "DB Created");
}
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
db.execSQL("DROP TABLE IF EXISTS " + Table);
onCreate(db);
}
public static Cursor getData(DB db)
{
SQLiteDatabase SQ = db.getReadableDatabase();
String[] columns ={tableColumns.Student_ID, tableColumns.Student_Password};
Cursor cursor = SQ.query(tableColumns.Table, columns, null, null, null, null, null);
return cursor;
}
public boolean insertStudent(String name, String gender, int age, String password, String course, String modules) {
SQLiteDatabase db = getWritableDatabase();
ContentValues contentValues = new ContentValues();
contentValues.put(Student_Name, name);
contentValues.put(Student_Password, password);
contentValues.put(Student_Gender, gender);
contentValues.put(Student_Age, age);
contentValues.put(Student_Course, course);
contentValues.put(Student_Modules, modules);
db.insert(Table, null, contentValues);
//Log for admin insert
//Log.d("DB", "Inserted Successfully");
return true;
}
}
And my tableStudents.java for controlling the students table
package com.example.project;
import android.provider.BaseColumns;
public class tableStudents {
//Constructor
public tableStudents()
{
}
public static abstract class tableColumns implements BaseColumns
{
public static final String Student_ID= "Student_ID";
public static final String Student_Password = "Student_Password";
public static final String Student_Gender = "gender";
public static final String Student_Age = "age";
public static final String Student_Course = "course";
public static final String Student_Modules = "modules";
public static final String Database = "databasename";
public static final String Table = "tablename";
}
}
1) To instantiate and insert data -
In your main activity
DB db = new DB(this);
db.insertStudent(name, gender, age, password, course, modules);
2) For convenience, consider
Student.java
public class Student{
public String name, gender, password, course, modules;
public int age;
Student(){ //constructor
}
Student(String name, String gender, int age, String password, String course, String modules){ //constructor
this.name = name;
this.gender = gender;
this.age = age;
this.password = password;
this.course = course;
this.modules = modules;
}
}
Now modify your getData function in DB.java to this -
public List<Student> getData() {
List<Student> studentList = new ArrayList<Student>();
// Select All Query
String selectQuery = "SELECT * FROM " + Table;
SQLiteDatabase db = this.getWritableDatabase();
Cursor cursor = db.rawQuery(selectQuery, null);
// looping through all rows and adding to list
if (cursor.moveToFirst()) {
do {
Student student = new Student();
student.name = cursor.getString(0);
student.gender = cursor.getString(1);
student.age = Integer.parseInt(cursor.getString(2));
student.password = cursor.getString(3);
student.course = cursor.getString(4);
student.modules = cursor.getString(5);
studentList.add(student);
} while (cursor.moveToNext());
}
// return contact list
return studentList;
}
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)));
I am having big trouble with this issue. I have my sqlite table called Category, where I put columns "name" and "limit" as text and integer. Here is some code:
private static final String CREATE_TABLE_CATEGORY = "CREATE TABLE "
+ TABLE_CATEGORIES + "(" + KEY_ID + " INTEGER PRIMARY KEY," + KEY_CATEGORY_NAME
+ " TEXT," + KEY_SET_LIMIT + " INTEGER" + ")";
There's model class of Category:
public class Category {
int id, limit;
String categoryName;
// Constructors
public Category(){
}
public Category(String categoryName, int limit){
this.categoryName = categoryName;
this.limit = limit;
}
//Setters
public void setCategoryName(String categoryName){
this.categoryName = categoryName;
}
public void setId(int id){
this.id = id;
}
public void setLimit(int limit) {
this.limit = limit;
}
// Getters
public String getCategoryName(){
return this.categoryName;
}
public int getId(){
return this.id;
}
public int getLimit() {
return this.limit;
}
#Override
public String toString(){
return getId() + " " + getCategoryName() + " " + getLimit();
}
}
And there's create category and update method:
public long createCategory(Category cat) {
SQLiteDatabase db = this.getWritableDatabase();
ContentValues values = new ContentValues();
values.put(KEY_CATEGORY_NAME, cat.getCategoryName());
values.put(KEY_SET_LIMIT, cat.getLimit());
// insert row
long cat_id = db.insert(TABLE_CATEGORIES, null, values);
return cat_id;
}
public int updateCategoryLimit(long cat_id, int limit) {
SQLiteDatabase db = this.getWritableDatabase();
ContentValues values = new ContentValues();
values.put(KEY_SET_LIMIT, limit);
// updating row
return db.update(TABLE_CATEGORIES, values, KEY_ID + " = ?",
new String[] { String.valueOf(cat_id) });
}
In spinner I have Overriden method toString from Category Class. It shows something like this below. From the left: ID, Category_Name, Category_Limit. The problem is that I set all limits to 10. Even if I use other integers, it always show '2'. Help please :)
Here's link to image: http://i.stack.imgur.com/Ae3YZ.png
The insert() call returns -1 if an error occurred. I think you should check it.
And make sure you write the correct column name.
I tried you code,works fine!
05-11 23:13:14.110: I/db update s=(30650): s= 1
ContentValues values = new ContentValues();
values.put(KEY_SET_LIMIT, 29);
int s= db.update(TABLE_CATEGORIES, values, KEY_ID + " = ?", new String[] { String.valueOf(2) });
Log.i("db update s=", "s= " +s);