Android SQLite Database : Cannot resolve constructor - java

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

Related

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

Authentication code not working in android studio(SQLite)

I am new to android studio and trying to work on simple login form which is my lab assignment.
When I click on login button it says username or password wrong even if it is true.
SqlHelper.java
package com.example.mogli.henabenparekhrajthakkar_comp304_lab4;
import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
import android.util.Log;
import android.widget.Toast;
import java.util.ArrayList;
import java.util.List;
/**
* Created by Mogli on 11/30/2017.
*/
public class SqlHelper extends SQLiteOpenHelper {
private static final int DATABASE_VERSION = 1;
private static final String DATABASE_NAME = "hospital.db";
//nurse table name & columns
private static final String NURSE_TABLE_NAME = "nurses";
private static final String NURSE_COLUMN_ID = "nurseId";
private static final String NURSE_COLUMN_FIRST_NAME = "nurseFirstName";
private static final String NURSE_COLUMN_LAST_NAME = "nurseLastName";
private static final String NURSE_COLUMN_DEPARTMENT = "nurseDepartment";
private static final String NURSE_COLUMN_PASSWORD = "nursePassword";
//doctor table name & columns
private static final String DOCTOR_TABLE_NAME = "doctors";
private static final String DOCTOR_COLUMN_ID = "doctorId";
private static final String DOCTOR_COLUMN_FIRST_NAME = "doctorFirstName";
private static final String DOCTOR_COLUMN_LAST_NAME = "doctorLastName";
private static final String DOCTOR_COLUMN_DEPARTMENT = "doctorDepartment";
private static final String DOCTOR_COLUMN_PASSWORD = "doctorPassword";
private static final String NURSE_TABLE_CREATE = "create table if not exists nurses( nurseId text primary key not null, "
+ "nurseFirstName text not null, nurseLastName text not null, nurseDepartment text not null, nursePassword text not null );";
private static final String DOCTOR_TABLE_CREATE = "create table if not exists doctors( doctorId text primary key not null, "
+ "doctorFirstName text not null, doctorLastName text not null, doctorDepartment text not null, doctorPassword text not null );";
//insert query
/*private String insertIntoNurse = "INSERT INTO nurses (nurseId, nurseFirstName, nurseLastName, nurseDepartment, nursePassword)"
+"VALUES ('john123', 'john', 'doe', 'd1', '123john' ), ('jonahdoe', 'jonah', 'doe', 'd2', '123jonah'), ('hannah123', 'hannah', 'montana', 'd3', 'hm123');";*/
public SqlHelper(Context context)
{
super(context, DATABASE_NAME, null, DATABASE_VERSION);
}
#Override
public void onCreate(SQLiteDatabase sqLiteDatabase) {
try {
sqLiteDatabase.execSQL(NURSE_TABLE_CREATE);
sqLiteDatabase.execSQL(DOCTOR_TABLE_CREATE);
}
catch(Exception e)
{
Log.d("myMsg", "Error creating table");
}
}
#Override
public void onUpgrade(SQLiteDatabase sqLiteDatabase, int i, int i1) {
String nurse_query = "DROP TABLE IF EXISTS " + NURSE_TABLE_NAME;
String doctor_query = "DROP TABLE IF EXISTS " + DOCTOR_TABLE_NAME;
sqLiteDatabase.execSQL(nurse_query);
sqLiteDatabase.execSQL(doctor_query);
onCreate(sqLiteDatabase);
}
public boolean checkUser(String email, String password) {
// array of columns to fetch
String[] columns = {
NURSE_COLUMN_ID
};
SQLiteDatabase db = this.getReadableDatabase();
// selection criteria
String selection = NURSE_COLUMN_ID + " = ?" + " AND " + NURSE_COLUMN_PASSWORD + " = ?";
// selection arguments
String[] selectionArgs = {email, password};
// query user table with conditions
/**
* Here query function is used to fetch records from user table this function works like we use sql query.
* SQL query equivalent to this query function is
* SELECT user_id FROM user WHERE user_email = 'jack#androidtutorialshub.com' AND user_password = 'qwerty';
*/
Cursor cursor = db.query(NURSE_TABLE_NAME, //Table to query
columns, //columns to return
selection, //columns for the WHERE clause
selectionArgs, //The values for the WHERE clause
null, //group the rows
null, //filter by row groups
null); //The sort order
int cursorCount = cursor.getCount();
cursor.close();
db.close();
if (cursorCount > 0) {
return true;
}
return false;
}
public String searchPass(String NURSE_COLUMN_ID)
{
SQLiteDatabase sqLiteDatabase = this.getWritableDatabase();
String query = "select nurseId, nursePassword from "+ NURSE_TABLE_NAME;
Cursor cursor =sqLiteDatabase.rawQuery(query, null);
String a, b;
b = "";
if(cursor.moveToFirst())
{
do
{
a = cursor.getString(0);
b = cursor.getString(1);
if(a.equals(NURSE_COLUMN_ID))
{
b = cursor.getString(1);
break;
}
}
while(cursor.moveToNext());
}
return b;
}
public void addNurses(Nurse nurse)
{
SQLiteDatabase db = this.getWritableDatabase();
ContentValues values = new ContentValues();
values.put(NURSE_COLUMN_ID, nurse.getNurseId());
values.put(NURSE_COLUMN_FIRST_NAME, nurse.getNurseFirstName());
values.put(NURSE_COLUMN_LAST_NAME, nurse.getNurseLastName());
values.put(NURSE_COLUMN_DEPARTMENT, nurse.getNurseDepartment());
values.put(NURSE_COLUMN_PASSWORD, nurse.getNursePassword());
db.insert(NURSE_TABLE_NAME,null,values);
db.close();
}
public List<Nurse> getAllNurses() {
List<Nurse> nurseList = new ArrayList<Nurse>();
// Select All Query
String selectQuery = "SELECT * FROM " + NURSE_TABLE_NAME;
SQLiteDatabase db = this.getWritableDatabase();
Cursor cursor = db.rawQuery(selectQuery, null);
// looping through all rows and adding to list
if (cursor.moveToFirst()) {
do {
Nurse nurse = new Nurse();
nurse.setNurseId(cursor.getString(0));
nurse.setNurseFirstName(cursor.getString(1));
nurse.setNurseLastName(cursor.getString(2));
nurse.setNurseDepartment(cursor.getString(3));
nurse.setNursePassword(cursor.getString(4));
// Adding contact to list
nurseList.add(nurse);
} while (cursor.moveToNext());
}
// return contact list
return nurseList;
}
}
In the log file the database is created and data is inserted. but the login code is giving false in the log console even if the username and password is correct.

Retrieve data from SQLite on android

I am trying to read data from SQLite in android using three parameters, id, name and date. For example, id="number" and name="something" and date between ("first date", "second date"). the problem is that, i cannot figure out what to do with the last function. There are two more parameters left and i dont know what to do or where to place it. So does anyone have any experience and familiar with this code style and can share or help me? (I take this code from book too and there was not any solution for related to this at all in the book.)
//Table person; It contain the same attribute as Person class
public static final class PersonTable
{
public static final String NAME = "Persons";
public static final class Cols
{
static final String ID = "id";
static final String NAME = "name";
static final String DATE = "date";
}
}
public class PersonCursorWrapper extends CursorWrapper
{
public PersonCursorWrapper(Cursor cursor)
{
super(cursor);
}
public Person getPerson()
{
int id = geIntI(getColumnIndex(PersonTable.Cols.ID));
String name = getString(getColumnIndex(PersonTable.Cols.NAME));
long date = getLong(getColumnIndex(PersonTable.Cols.DATE));
Person Person = new Person();
Person.id(id);
Person.setDate(new Date(date));
Person.setName(name);
return Person;
}
}
}
private PersonCursorWrapper queryPersons(String whereClause, String[] whereArgs)
{
Cursor cursor = mDatabase.query
(
PersonTable.NAME,
null,
whereClause,
whereArgs,
null,
null,
null
);
return new PersonCursorWrapper(cursor);
}
public Person getPerson(int id, String name, String date)
{
PersonCursorWrapper cursor = queryPersons(
PersonTable.Cols.ID + " = ?"+" "+
PersonTable.Cols.NAME + " = ?"+" "+
PersonTable.Cols.DATE + " = ?",
new String[] { id.toString() }
);
try
{
if (cursor.getCount() == 0)
{
return null;
}
cursor.moveToFirst();
return cursor.getPerson();
}
finally
{
cursor.close();
}
}
You have three parameter markers (?), so you have to give it three parameters:
cursor = queryPersons(
...,
new String[] { id.toString(), name, date }
);
For android sqlite database operations you can simply use SQLiteOpenHelper class provided with android.
This is a complete implementation for your case with SQLiteOpenHelper.
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;
public class DatabaseHandler2 extends SQLiteOpenHelper {
// Database details
private static final int DATABASE_VERSION = 1;
private static String DATABASE_NAME = "dbname.db";
// Table names
private static String TABLE_PERSON = "person";
// Table Columns name
private static final String COLUMN_ID = "workout_id";
private static final String COLUMN_NAME = "exercise_id";
// Create queries
private static final String CREATE_TABLE_PERSON = "CREATE TABLE " + TABLE_PERSON + "(" + COLUMN_ID + " INTEGER PRIMARY KEY AUTOINCREMENT, " + COLUMN_NAME + " TEXT NOT NULL)";
public DatabaseHandler2(Context context) {
super(context, DATABASE_NAME, null, DATABASE_VERSION);
}
#Override
public void onCreate(SQLiteDatabase db) {
db.execSQL(CREATE_TABLE_PERSON);
}
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
db.execSQL("DROP TABLE IF EXISTS " + CREATE_TABLE_PERSON);
}
public Person getPerson(int id) {
Person person = new Person();
String selectQuery = "SELECT * FROM " + TABLE_PERSON + " WHERE " + COLUMN_ID + "=" + id;
SQLiteDatabase rdb;
rdb = this.getReadableDatabase();
Cursor cursor = rdb.rawQuery(selectQuery, null);
if (cursor.moveToFirst()) {
do {
person.setId(cursor.getInt(0));
person.setName(cursor.getString(1));
} while (cursor.moveToNext());
}
cursor.close();
rdb.close();
return person;
}
public List<Person> getAllPersons() {
List<Person> personList = new ArrayList<Person>();
String selectQuery = "SELECT * FROM " + TABLE_PERSON;
SQLiteDatabase rdb;
rdb = this.getReadableDatabase();
Cursor cursor = rdb.rawQuery(selectQuery, null);
if (cursor.moveToFirst()) {
do {
Person person = new Person();
person.setId(cursor.getInt(0));
person.setName(cursor.getString(1));
personList.add(person);
} while (cursor.moveToNext());
}
cursor.close();
rdb.close();
return personList;
}
public void savePerson(Person person) {
SQLiteDatabase wdb;
ContentValues values = new ContentValues();
values.put(COLUMN_ID, person.getId());
values.put(COLUMN_NAME, person.getName());
wdb = this.getWritableDatabase();
long rowId = wdb.insert(TABLE_PERSON, null, values);
wdb.close();
}
public void deletePerson(int id) {
SQLiteDatabase db = this.getWritableDatabase();
db.delete(TABLE_PERSON, COLUMN_ID + "='" + id + "'", null);
db.close();
}
public boolean renamePerson(int id, String newName) {
SQLiteDatabase db = this.getWritableDatabase();
ContentValues values = new ContentValues();
values.put(COLUMN_NAME, newName);
int numOfRowsEffected = db.update(TABLE_PERSON, values, COLUMN_ID + "='" + id + "'", null);
db.close();
return numOfRowsEffected > 0 ? true : false;
}
}
Here is the Person class
public class Person {
private int id;
private String name;
public Person() {
}
public Person(int id, String name) {
this.id = id;
this.name = name;
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
}

Android - Displaying database information in another class

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

Unable to convert BLOB to String

In my code, the user supposed to add details of a product including name, image, category and other details. But after entering the data and saving it, it cannot view the data that they input. Instead it shows: unable to convert BLOB to String.
My coding for adding data.
items Item= new items();
db.getWritableDatabase();
ByteArrayOutputStream stream = new ByteArrayOutputStream();
byte imageInByte[] = stream.toByteArray();
Bitmap bMap= BitmapFactory.decodeByteArray(imageInByte, 0, imageInByte.length);
ivThumbnailPhoto.setImageBitmap(bMap);
Item.setName(name.getText().toString());
Item.setCategory(SpCate.getSelectedItem().toString());
Item.setDetails(details.getText().toString());
Item.setImage(imageInByte);
db.addItemSpinner(new items());
// Save the Data in Database
MyDb entry= new MyDb(SellingItem.this);
entry.getWritableDatabase();
entry.addItemSpinner(Item);
entry.close();
Toast.makeText(getApplicationContext(), "Account Successfully Created ", Toast.LENGTH_LONG).show();
Log.d("name", Item.getName());
Log.d("category", Item.getCategory());
Log.d("detailsL", Item.getDetails());
Intent i=new Intent(SellingItem.this,SearchItem.class);
startActivity(i);
My Database to input data.
public void addItemSpinner(items i) {
SQLiteDatabase db = this.getWritableDatabase();
ContentValues values = new ContentValues();
values.put(COLUMN_NAME, i.name); // Contact Name
values.put(COLUMN_IMAGE, i.image); // Contact Phone
values.put(COLUMN_CATE, i.category); // Contact Name
values.put(COLUMN_DETAILS, i.details); // Contact Phone
// Inserting Row
db.insert(TABLE_NAME, null, values);
db.close(); // Closing database connection
}
logcat shows this.
java.lang.RuntimeException: Unable to start activity ComponentInfo{com.example.projectonline/com.example.projectonline.SearchItem}: android.database.sqlite.SQLiteException: unknown error (code 0): Unable to convert BLOB to string
This is my items code.
package com.example.projectonline;
import android.graphics.Bitmap;
public class items {
int id;
String name, category, details;
byte[] image;
public items(){
}
public items(int id, String name, String category, byte[]image, String details)
{
this.id=id;
this.name= name;
this.category=category;
this.image= image;
this.details=details;
}
public items(String name, String category, byte[]image, String details){
this.name = name;
this.category = category;
this.image = image;
this.details = details;
}
public String getDetails() {
return details;
}
public void setDetails(String details) {
this.details = details;
}
public byte[] getImage() {
return image;
}
public void setImage(byte[] image) {
this.image = image;
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getCategory() {
return category;
}
public void setCategory(String category) {
this.category = category;
}
public Bitmap getBitmap() {
// TODO Auto-generated method stub
return null;
}
}
And this is what my DB looks like
public static final String TAG = "MyDb";
public static final String TABLE_NAME="PRODUCT";
public static final String COLUMN_ID="id";
public static final String COLUMN_NAME="name";
public static final String COLUMN_CATE="category";
public static final String COLUMN_IMAGE="image";
public static final String COLUMN_DETAILS="details";
private static final String DATABASE_NAME="Spinner";
private static final int DATABASE_VERSION= 1;
private static final String SQL_CREATE_ITEM = "CREATE TABLE " + TABLE_NAME + "("
+ COLUMN_ID + " INTEGER PRIMARY KEY AUTOINCREMENT, "
+ COLUMN_NAME + " TEXT NOT NULL, "
+ COLUMN_CATE + " TEXT NOT NULL, "
+ COLUMN_IMAGE + " BLOB, "
+ COLUMN_DETAILS + " TEXT NOT NULL "
+")";
Use the following code
java.sql.Blob ablob = rs.getBlob(1);
String str = new String(ablob.getBytes(1l, (int) ablob.length()));
or
Try this (a2 is BLOB col)
PreparedStatement ps1 = conn.prepareStatement("update t1 set a2=? where id=1");
Blob blob = conn.createBlob();
blob.setBytes(1, str.getBytes());
ps1.setBlob(1, blob);
ps1.executeUpdate();
It may work even without BLOB, driver will transform types automatically:
ps1.setBytes(1, str.getBytes);
ps1.setString(1, str);
Besides if you work with text CLOB seems to be a more natural col type.

Categories