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();
Related
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 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.
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;
}
}
hi i want to put cursor content in textview .
im using sqlite data base when get the id of the current user and display them in a textview i tried to search but i found nothing
here is the code
package com.example.i.projet;
import android.database.Cursor;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.widget.EditText;
public class AfficherActivity extends AppCompatActivity {
BaseDeDonee bdd;
EditText nom , prenom , email,numt;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_afficher);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
bdd = new BaseDeDonee(this);
int k =bdd.tempID();// to get id of corrent user
String id = Integer.toString(k) ;
Cursor res = bdd.afficherinfoP(id);// function return cursor
nom =(EditText) findViewById(R.id.nom);
prenom=(EditText) findViewById(R.id.prenom);
email=(EditText) findViewById(R.id.email);
numt=(EditText) findViewById(R.id.numtele);
if(res.getCount()<=0){
// show message empty
}else{
res.moveToFirst();
nom.setText(res.getString(res.getColumnIndex("nom")));
prenom.setText(res.getString(res.getColumnIndex("prenom")));
numt.setText(res.getInt(res.getColumnIndex("numero_tel")));
email.setText( res.getString(res.getColumnIndex("profile")));
}
}
}
and the data base
public class BaseDeDonee extends SQLiteOpenHelper {
public static final String DATABASE_NAME = "Platforme.db";
public static final String TABLE_PERSONNE = "UsersTable";
public static final String COL_1 = "ID";
public static final String COL_2 = "nom";
public static final String COL_3 = "prenom";
public static final String COL_4 = "numero_tel";
public static final String COL_5 = "profile";
public static final String COL_s = "password";
public static final String COL_k = "etat";
public static final String TABLE_COMPTE = "CompteTable";
public static final String COL_6 = "numero_compte";
public static final String COL_7 = "cle_compte";
public static final String COL_8 = "solde_courante";
public static final String COL_9 = "type_compte";
public static final String TABLE_OPPERATIONS = "OpperationsTable";
public static final String COL_10 = "num_opp";
public static final String COL_11 = "type_opp";
public static final String COL_12 = "date_opp";
public static final String COL_13 = "montant_opp";
public static final String COL_14 = "solde_courante";
//+etat de l'opp pour avoir est que personel ou du busness
public static final String TABLE_PRODUITS = "ProductsTable";
public static final String COL_15 = "nom_prod";
public static final String COL_16 = "type_prod";
public static final String COL_17 = "PrixUnit_prod";
public static final String COL_18 = "quantite_prod";
public static final String COL_19 = "PrixTotal_prod";
public static final String TABLE_FACTURES = "FacturesTable";
public static final String COL_20 = "num_fact";
public static final String COL_21 = "type_fact";
public static final String COL_22 = "Montant_fact";
public static final String COL_23 = "date_fact";
public static final String TABLE_IDENTIFICATION = "IdentificationTable";
public static final String COL_24 = "profile";
public static final String COL_25 = "password";
public static final String TABLE_DECAISSEMENT = "DecaissementTable";
public static final String COL_26 = "num_opp";
public static final String COL_27 = "type_compte";
public static final String COL_28 = "piecejustificatif";
public static final String TABLE_Temp = "tempTable";
public static final String COL_29 = "ID";
public BaseDeDonee(Context context ) {
super(context, DATABASE_NAME, null, 1);
}
#Override
public void onCreate(SQLiteDatabase db) {
db.execSQL("create table " + TABLE_PERSONNE +" (ID INTEGER PRIMARY KEY AUTOINCREMENT,nom TEXT,prenom TEXT,numero_tel INTEGER,profile TEXT,password Text,etat Text)");
db.execSQL("create table " + TABLE_COMPTE +" (numero_compte INTEGER PRIMARY KEY,cle_compte INTEGER,solde_courante DOUBLE,type_compte TEXT,ID INTEGER REFERENCES TABLE_PERSONNE)");
db.execSQL("create table " + TABLE_PRODUITS +" (nom_prod TEXT PRIMARY KEY,type_prod TEXT,PrixUnit_prod DOUBLE,quantite_prod INTEGER,PrixTotal_prod DOUBLE,num_opp INTEGER REFERENCES TABLE_OPPERATIONS)");
db.execSQL("create table " + TABLE_FACTURES +" (num_fact INTEGER PRIMARY KEY AUTOINCREMENT,type_fact TEXT,Montant_fact DOUBLE,date_fact DATE,num_opp INTEGER REFERENCES TABLE_OPPERATIONS,ID INTEGER REFERENCES TABLE_PERSONNE)");
db.execSQL("create table " + TABLE_OPPERATIONS +" (num_opp INTEGER PRIMARY KEY AUTOINCREMENT,type_opp TEXT,montant_opp DOUBLE,date_opp DATE,ID INTEGER REFERENCES TABLE_PERSONNE ,solde_courante DOUBLE REFERENCES TABLE_COMPTE)");
db.execSQL("create table " + TABLE_IDENTIFICATION +" (profile TEXT REFERENCES TABLE_PERSONNE PRIMARY KEY ,password TEXT REFERENCES TABLE_PERSONNE)");
db.execSQL("create table " + TABLE_DECAISSEMENT + " (piecejustificatif TEXT PRIMARY KEY,num_opp INTEGER REFERENCES TABLE_OPPERATIONS,type_compte TEXT REFERENCES TABLE_COMPTE)");
db.execSQL("create table " + TABLE_Temp + " (ID INTEGER PRIMARY KEY )");
}
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
db.execSQL("DROP TABLE IF EXISTS " + TABLE_PERSONNE + TABLE_COMPTE + TABLE_PRODUITS + TABLE_FACTURES + TABLE_OPPERATIONS + TABLE_IDENTIFICATION + TABLE_DECAISSEMENT + TABLE_Temp);
onCreate(db);
}
public boolean insertData(String nom ,String prenom ,String tel,String profile,String password ,String etat){
SQLiteDatabase db = this.getWritableDatabase();
ContentValues contentValues = new ContentValues();
Cursor res = db.query(TABLE_PERSONNE,new String[]{"*"},"profile =?",new String[]{profile},null,null,null);
contentValues.put(COL_2,nom);
contentValues.put(COL_3,prenom);
contentValues.put(COL_4,tel);
contentValues.put(COL_5,profile);
contentValues.put(COL_s,password);
contentValues.put(COL_k,etat);
if(res!=null && res.moveToFirst()){
return false;
}else{
long result= db.insert(TABLE_PERSONNE, null, contentValues);
if (result==-1){
return false;
}else return true; }
}
public boolean insertl(String profile ,String password ){
SQLiteDatabase db = this.getWritableDatabase();
ContentValues ContentVlues = new ContentValues();
ContentVlues.put(COL_24,profile);
ContentVlues.put(COL_25,password);
long result =db.insert(TABLE_IDENTIFICATION,null,ContentVlues);
if (result==-1)
return false;
else return true ;
}
public boolean insertfacture(String type ,String Montantfact, String date){
SQLiteDatabase db = this.getWritableDatabase();
ContentValues ContentVlues = new ContentValues();
ContentVlues.put(COL_21,type);
ContentVlues.put(COL_22,Montantfact);
ContentVlues.put(COL_23,date);
long result =db.insert(TABLE_FACTURES,null,ContentVlues);
if (result==-1)
return false;
else return true ;
}
public boolean insertCompte(String numero_compte ,String cle_compte, String solde_courante,String type_compte ){
SQLiteDatabase db = this.getWritableDatabase();
ContentValues ContentVlues = new ContentValues();
ContentVlues.put(COL_6,numero_compte);
ContentVlues.put(COL_7,cle_compte);
ContentVlues.put(COL_8,solde_courante);
ContentVlues.put(COL_9,type_compte);
long result =db.insert(TABLE_COMPTE,null,ContentVlues);
if (result==-1)
return false;
else return true ;
}
public boolean insertProduit(String nom_prod ,String type_prod, String PrixUnit_prod,String quantite_prod,String PrixTotal_prod){
SQLiteDatabase db = this.getWritableDatabase();
ContentValues ContentVlues = new ContentValues();
ContentVlues.put(COL_15,nom_prod);
ContentVlues.put(COL_16,type_prod);
ContentVlues.put(COL_17,PrixUnit_prod);
ContentVlues.put(COL_18,quantite_prod);
ContentVlues.put(COL_19,PrixTotal_prod);
long result =db.insert(TABLE_PRODUITS,null,ContentVlues);
if (result==-1)
return false;
else return true ;
}
public boolean inseloginid(int id ){
SQLiteDatabase db = this.getWritableDatabase();
Cursor res = db.rawQuery("select * from "+TABLE_Temp,null);
ContentValues ContentVlues = new ContentValues();
ContentVlues.put(COL_29,id);
if(res.getCount()<=0){
long result =db.insert(TABLE_Temp,null,ContentVlues);
if (result==-1)
return false;
else return true ;
}else return true;
}
public Cursor afficherinfoP (String id ){
SQLiteDatabase db = this.getWritableDatabase();
Cursor res = db.query(TABLE_PERSONNE,null,"ID = ? ", new String[]{id},null,null,null);
return res;
}
public Boolean finde(String lemail, String lpass) {
SQLiteDatabase db = this.getWritableDatabase();
Cursor res = db.query(TABLE_IDENTIFICATION, null, "profile=? AND password=?",new String[]{lemail,lpass},null,null,null);
if(res.getCount()<=0){
res.close();
return false;
}else {
res.close();
return true;
}
}
public int findID (String lemail){
SQLiteDatabase db = this.getWritableDatabase();
int k ;
Cursor res = db.query(TABLE_PERSONNE, null, "profile=?", new String[]{lemail}, null, null, null);
if(res!=null && res.moveToFirst()){
//cursor contains data
int ind =res.getColumnIndex("id");
k = res.getInt(ind);
}else k=0;
return k;
}
public int tempID (){
SQLiteDatabase db = this.getWritableDatabase();
int k =-1;
Cursor res = db.rawQuery("select * from " + TABLE_Temp, null);
if (res!=null && res.moveToFirst()){
k = res.getInt(res.getColumnIndex("ID"));
}
return k ;
}
public double rapportJ(String date,int id ){
Double k= Double.valueOf(0);
SQLiteDatabase db = this.getWritableDatabase();
Cursor res = db.rawQuery("Select * from"+TABLE_FACTURES+"where date_fact="+date+"and id="+id,null);
while (res.moveToNext()){
k=k+ res.getDouble(2);
}
Cursor ress=db.rawQuery("Select * from"+TABLE_OPPERATIONS+"where date_opp="+date+"and id="+id,null);
while (ress.moveToNext()){
k=k+ ress.getDouble(2);
}
return k;
}
}
stack trace
So I found the following issues following your logic:
public boolean inseloginid(int id ){
SQLiteDatabase db = this.getWritableDatabase();
Cursor res = db.rawQuery("select * from "+TABLE_Temp,null);
ContentValues ContentVlues = new ContentValues();
ContentVlues.put(COL_29,id);
if(res.getCount()>0){ // I changed this condition from <= to >
db.delete(TABLE_Temp,null,null); // added this line
long result =db.insert(TABLE_Temp,null,ContentVlues);
if (result==-1)
return false;
else return true ;
}else return true;
}
The reason is that it will not insert the current login if there is a previous value stored. After the correction, if there is a value stored, it'll clear the table and enter the login ID. In the main activity call bdd.inseloginid(loggedID); before int k = bdd.tempID();. That inserts the ID into temp then you pull it with int k = bdd.tempID();. That'll pull the correct data from the database when you call bdd.afficherinfoP(id);.
When it comes to displaying them with the EditText views:
numt.setText(res.getInt(res.getColumnIndex("numero_tel")));
returns a string because "numero_tel" is an integer in your table declaration, so turn it into a string:
numt.setText(Integer.toString(res.getInt(res.getColumnIndex("numero_tel"))));
There may be easier ways to do this but I tried to keep your logic intact. It's also worth mentioning that you have to clear TABLE_temp because in bdd.tempID(); your logic always goes to the top value. If you clear the table then the top value will be the logged in ID.
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