I'm developing an app that uses SQLite database to store some info. When I run the app on an emulator or on my physical device plugger via USB from android studio, it works fine. However, when I use an APK version (send via email or installed from the play store) the database works but the insertRow command doesn't seem to work. All the other command seems to work for as far as I can test them. I already tried to uninstall-reinstall multiple times without success.
DBadapter
public class DBAdapter {
/////////////////////////////////////////////////////////////////////
// Constants & Data
/////////////////////////////////////////////////////////////////////
// For logging:
private static final String TAG = "DBAdapter";
// DB Fields
public static final String KEY_ROWID = "_id";
public static final int COL_ROWID = 0;
/*
* CHANGE 1:
*/
// TODO: Setup your fields here:
public static final String KEY_IMM = "imm";
public static final String KEY_TYPE = "type";
public static final String KEY_WEIGHT = "weight";
public static final String KEY_CG = "cg";
public static final String KEY_LAT = "lat";
public static final String KEY_UNIT = "unit";
public static final String KEY_EXTRA1 = "extra1";
public static final String KEY_EXTRA2 = "extra2";
public static final String KEY_EXTRA3 = "extra3";
public static final String KEY_EXTRA4 = "extra4";
public static final String KEY_EXTRA5 = "extra5";
public static final String KEY_EXTRA6 = "extra6";
public static final String KEY_EXTRA7 = "extra7";
public static final String KEY_EXTRA8 = "extra8";
public static final String KEY_EXTRA9 = "extra9";
public static final String KEY_EXTRA10 = "extra10";
public static final String KEY_EXTRA11 = "extra11";
public static final String KEY_EXTRA12 = "extra12";
public static final String KEY_EXTRA13 = "extra13";
public static final String KEY_FUEL = "fuel";
// TODO: Setup your field numbers here (0 = KEY_ROWID, 1=...)
public static final int COL_IMM = 1;
public static final int COL_TYPE = 2;
public static final int COL_WEIGHT = 3;
public static final int COL_CG = 4;
public static final int COL_LAT = 5;
public static final int COL_UNIT = 6;
public static final int COL_EXTRA1 = 7;
public static final int COL_EXTRA2 = 8;
public static final int COL_EXTRA3 = 9;
public static final int COL_EXTRA4 = 10;
public static final int COL_EXTRA5 = 11;
public static final int COL_EXTRA6 = 12;
public static final int COL_EXTRA7 = 13;
public static final int COL_EXTRA8 = 14;
public static final int COL_EXTRA9 = 15;
public static final int COL_EXTRA10 = 16;
public static final int COL_EXTRA11 = 17;
public static final int COL_EXTRA12 = 18;
public static final int COL_EXTRA13 = 19;
public static final int COL_FUEL = 20;
public static final String[] ALL_KEYS = new String[] {KEY_ROWID, KEY_IMM, KEY_TYPE, KEY_WEIGHT, KEY_CG, KEY_LAT, KEY_UNIT
, KEY_EXTRA1, KEY_EXTRA2, KEY_EXTRA3, KEY_EXTRA4, KEY_EXTRA5, KEY_EXTRA6, KEY_EXTRA7, KEY_EXTRA8, KEY_EXTRA9, KEY_EXTRA10
, KEY_EXTRA11
, KEY_EXTRA12, KEY_EXTRA13, KEY_FUEL
};
// DB info: its name, and the table we are using (just one).
public static final String DATABASE_NAME = "MyDb";
public static final String DATABASE_TABLE = "mainTable";
// Track DB version if status1 new version of your app changes the format.
public static final int DATABASE_VERSION = 12; // version 9 online (needs 11) TODO <--- If you are adding or deleting KEYS, change the version #.
private static final String DATABASE_CREATE_SQL =
"create table " + DATABASE_TABLE
+ " (" + KEY_ROWID + " integer primary key autoincrement, "
/*
* CHANGE 2:
*/
// TODO: Place your fields here!
// + KEY_{...} + " {type} not null"
// - Key is the column name you created above.
// - {type} is one of: text, integer, real, blob
// (http://www.sqlite.org/datatype3.html)
// - "not null" means it is status1 required field (must be given status1 value).
// NOTE: All must be comma separated (end of line!) Last one must have NO comma!!
+ KEY_IMM + " text not null, "
+ KEY_TYPE + " string , "
+ KEY_WEIGHT + " string , "
+ KEY_CG + " double , "
+ KEY_LAT + " double , "
+ KEY_UNIT + " string , "
+ KEY_EXTRA1 + " string , "
+ KEY_EXTRA2 + " string , "
+ KEY_EXTRA3 + " string , "
+ KEY_EXTRA4 + " string , "
+ KEY_EXTRA5 + " string , "
+ KEY_EXTRA6 + " string , "
+ KEY_EXTRA7 + " string , "
+ KEY_EXTRA8 + " string , "
+ KEY_EXTRA9 + " string , "
+ KEY_EXTRA10 + " string , "
+ KEY_EXTRA11 + " string , "
+ KEY_EXTRA12 + " string , "
+ KEY_EXTRA13 + " string , "
+ KEY_FUEL + " string "
// Rest of creation:
+ ");";
// Context of application who uses us.
private final Context context;
private DatabaseHelper myDBHelper;
private SQLiteDatabase db;
/////////////////////////////////////////////////////////////////////
// Public methods:
/////////////////////////////////////////////////////////////////////
public DBAdapter(Context ctx) {
this.context = ctx;
myDBHelper = new DatabaseHelper(context);
}
// Open the database connection.
public DBAdapter open() {
db = myDBHelper.getWritableDatabase();
return this;
}
// Close the database connection.
public void close() {
myDBHelper.close();
}
// Add a new set of values to the database.
public long insertRow(String imm, String type, String weight, String cg, String lat, String unit) {
/*
* CHANGE 3:
*/
// TODO: Update data in the row with new fields.
// TODO: Also change the function's arguments to be what you need!
// Create row's data:
ContentValues initialValues = new ContentValues();
initialValues.put(KEY_IMM, imm);
initialValues.put(KEY_TYPE, type);
initialValues.put(KEY_WEIGHT, weight);
initialValues.put(KEY_CG, cg);
initialValues.put(KEY_LAT, lat);
initialValues.put(KEY_UNIT, unit);
// Insert it into the database.
return db.insert(DATABASE_TABLE, null, initialValues);
}
// Delete status1 row from the database, by rowId (primary key)
public boolean deleteRow(long rowId) {
String where = KEY_ROWID + "=" + rowId;
return db.delete(DATABASE_TABLE, where, null) != 0;
}
// Return all data in the database.
public Cursor getAllRows() {
String where = null;
Cursor c = db.query(true, DATABASE_TABLE, ALL_KEYS,
where, null, null, null, null, null);
c.moveToLast();
if (c != null) {
c.moveToPrevious();
}
return c;
}
// Get status1 specific row (by rowId)
public Cursor getRow(long rowId) {
String where = KEY_ROWID + "=" + rowId;
Cursor c = db.query(true, DATABASE_TABLE, ALL_KEYS,
where, null, null, null, null, null);
if (c != null) {
c.moveToFirst();
}
return c;
}
// Change an existing row to be equal to new data.
public boolean updateRow(long rowId, String imm, String weight, String cg, String lat) {
String where = KEY_ROWID + "=" + rowId;
/*
* CHANGE 4:
*/
// TODO: Update data in the row with new fields.
// TODO: Also change the function's arguments to be what you need!
// Create row's data:
ContentValues newValues = new ContentValues();
newValues.put(KEY_IMM, imm);
newValues.put(KEY_WEIGHT, weight);
newValues.put(KEY_CG, cg);
newValues.put(KEY_LAT, lat);
// Insert it into the database.
return db.update(DATABASE_TABLE, newValues, where, null) != 0;
}
// Change an existing row to be equal to new data.
public boolean save11Values(long rowId, String fuel, String extra1, String extra2, String extra3, String extra4, String extra5,
String extra6, String extra7, String extra8, String extra9, String extra10) {
String where = KEY_ROWID + "=" + rowId;
// TODO: Update data in the row with new fields.
// TODO: Also change the function's arguments to be what you need!
ContentValues newValues = new ContentValues();
newValues.put(KEY_FUEL, fuel);
newValues.put(KEY_EXTRA1, extra1);
newValues.put(KEY_EXTRA2, extra2);
newValues.put(KEY_EXTRA3, extra3);
newValues.put(KEY_EXTRA4, extra4);
newValues.put(KEY_EXTRA5, extra5);
newValues.put(KEY_EXTRA6, extra6);
newValues.put(KEY_EXTRA7, extra7);
newValues.put(KEY_EXTRA8, extra8);
newValues.put(KEY_EXTRA9, extra9);
newValues.put(KEY_EXTRA10, extra10);
// Insert it into the database.
return db.update(DATABASE_TABLE, newValues, where, null) != 0;
}
public boolean save14Values(long rowId, String fuel, String extra1, String extra2, String extra3, String extra4, String extra5,
String extra6, String extra7, String extra8, String extra9, String extra10, String extra11,
String extra12, String extra13) {
String where = KEY_ROWID + "=" + rowId;
// TODO: Update data in the row with new fields.
// TODO: Also change the function's arguments to be what you need!
ContentValues newValues = new ContentValues();
newValues.put(KEY_FUEL, fuel);
newValues.put(KEY_EXTRA1, extra1);
newValues.put(KEY_EXTRA2, extra2);
newValues.put(KEY_EXTRA3, extra3);
newValues.put(KEY_EXTRA4, extra4);
newValues.put(KEY_EXTRA5, extra5);
newValues.put(KEY_EXTRA6, extra6);
newValues.put(KEY_EXTRA7, extra7);
newValues.put(KEY_EXTRA8, extra8);
newValues.put(KEY_EXTRA9, extra9);
newValues.put(KEY_EXTRA10, extra10);
newValues.put(KEY_EXTRA11, extra11);
newValues.put(KEY_EXTRA12, extra12);
newValues.put(KEY_EXTRA13, extra13);
// Insert it into the database.
return db.update(DATABASE_TABLE, newValues, where, null) != 0;
}
//TODO on upgrade///////////////////
private static final String DATABASE_ALTER_1 = "ALTER TABLE "
+ DATABASE_TABLE + " ADD COLUMN " + KEY_EXTRA11 + " string;";
private static final String DATABASE_ALTER_2 = "ALTER TABLE "
+ DATABASE_TABLE + " ADD COLUMN " + KEY_EXTRA12 + " string;";
private static final String DATABASE_ALTER_3 = "ALTER TABLE "
+ DATABASE_TABLE + " ADD COLUMN " + KEY_EXTRA13 + " string;";
private static final String DATABASE_ALTER_4 = "ALTER TABLE "
+ DATABASE_TABLE + " ADD COLUMN " + KEY_FUEL + " string;";
/////////////////////////////////////////////////////////////////////
// Private Helper Classes:
/////////////////////////////////////////////////////////////////////
/**
* Private class which handles database creation and upgrading.
* Used to handle low-level database access.
*/
private static class DatabaseHelper extends SQLiteOpenHelper
{
DatabaseHelper(Context context) {
super(context, DATABASE_NAME, null, DATABASE_VERSION);
}
#Override
public void onCreate(SQLiteDatabase _db) {
_db.execSQL(DATABASE_CREATE_SQL);
}
#Override
public void onUpgrade(SQLiteDatabase _db, int oldVersion, int newVersion) {
if (oldVersion < 10) {
_db.execSQL(DATABASE_ALTER_1);
_db.execSQL(DATABASE_ALTER_2);
}
if (oldVersion < 11) {
_db.execSQL(DATABASE_ALTER_3);
}
if (oldVersion < 12) {
_db.execSQL(DATABASE_ALTER_4);
}
}
}
}
It appears that on a previous version of my database KEY_IMM to KEY_EXTRA10 were set as NOT NULL. Using (android:debuggable="true") allowed me to see it.
Related
My application crashes when I do a SQL request.
It says that the table doesn't exist and I don't know why.
Could you help me?
Here is the logcat:
03-27 15:35:49.718 5672-5672/descartes.info.l3ag2.eyetrek E/AndroidRuntime: FATAL EXCEPTION: main
Process: descartes.info.l3ag2.eyetrek,
PID: 5672 android.database.sqlite.SQLiteException: no such table: bddchampignons (code 1):,
while compiling: SELECT * FROM bddchampignons
at android.database.sqlite.SQLiteConnection.nativePrepareStatement(Native Method)
at android.database.sqlite.SQLiteConnection.acquirePreparedStatement(SQLiteConnection.java:887)
at android.database.sqlite.SQLiteConnection.prepare(SQLiteConnection.java:498)
at android.database.sqlite.SQLiteSession.prepare(SQLiteSession.java:588)
at android.database.sqlite.SQLiteProgram.<init>(SQLiteProgram.java:58)
at android.database.sqlite.SQLiteQuery.<init>(SQLiteQuery.java:37)
at android.database.sqlite.SQLiteDirectCursorDriver.query(SQLiteDirectCursorDriver.java:44)
at android.database.sqlite.SQLiteDatabase.rawQueryWithFactory(SQLiteDatabase.java:1316)
at android.database.sqlite.SQLiteDatabase.rawQuery(SQLiteDatabase.java:1255)
at descartes.info.l3ag2.eyetrek.classes.DatabaseHandler.getAllChampignons(DatabaseHandler.java:578)
at descartes.info.l3ag2.eyetrek.fragment.mushroomanalysis.FragmentCirconstance1.lambda$onCreateView$2$FragmentCirconstance1(FragmentCirconstance1.java:147)
at descartes.info.l3ag2.eyetrek.fragment.mushroomanalysis.FragmentCirconstance1$$Lambda$2.onClick(Unknown Source)
at android.view.View.performClick(View.java:5198)
at android.view.View$PerformClick.run(View.java:21147)
at android.os.Handler.handleCallback(Handler.java:739)
at android.os.Handler.dispatchMessage(Handler.java:95)
at android.os.Looper.loop(Looper.java:148)
at android.app.ActivityThread.main(ActivityThread.java:5417)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:726)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:616)
this is the request I am doing :
List<Mushroom> MushroomList = new ArrayList<Mushroom>();
MushroomList = databaseHandler.getAllChampignons();
String res= "";
Log.e("List", MushroomList.toString());
for (Mushroom mushroom: MushroomList) {
Log.e("NAME", mushroom.getName());
res = res + mushroom.getId() + "\n";
}
createAlertBox("Resultats", res);
and this is a part of the code from my DataBaseHandler class where is the method getAllChampignons:
private static final String TABLE_CHAMPIGNON = "bddchampignons";
//(my csv file is named "bddchampignons")
public List<Mushroom> getAllChampignons() {
List<Mushroom> champignonsList = new ArrayList<Mushroom>();
String selectQuery = "SELECT * FROM " + TABLE_CHAMPIGNON;
SQLiteDatabase db = this.getReadableDatabase();
Cursor cursor = db.rawQuery(selectQuery, null);
if (cursor.moveToFirst()) {
do {
Mushroom champ = new Mushroom();
champ.setId(Integer.parseInt(cursor.getString(0)));
champ.setName(cursor.getString(1));
champ.setDiametreMin(Integer.parseInt(cursor.getString(2)));
champ.setDiametreMax(Integer.parseInt(cursor.getString(3)));
champ.setCouleurChapeau(cursor.getString(4));
champ.setFormeChapeau(cursor.getString(5));
champ.setSurfaceChapeau(cursor.getString(6));
champ.setTypeMarge(cursor.getString(7));
champ.setCouleurMarge(cursor.getString(8));
champ.setDessousChapeau(cursor.getString(9));
champ.setCouleurDessousChapeau(cursor.getString(10));
champ.setOxydationChapeau(cursor.getString(11));
champ.setCouleurOxydationChapeau(cursor.getString(12));
champ.setInsertionDessousPied(cursor.getString(13));
champ.setEspaceLamelles(cursor.getString(14));
champ.setTypeLamelles(cursor.getString(15));
champ.setCouleurPied(cursor.getString(16));
champ.setPiedCreuxPlein(cursor.getString(17));
champ.setFormePied(cursor.getString(18));
champ.setLongueurPied(cursor.getString(19));
champ.setSurfacePied(cursor.getString(20));
champ.setPositionPiedChapeau(cursor.getString(21));
champ.setPresenceAnneau(cursor.getString(22));
champ.setOrientationAnneau(cursor.getString(23));
champ.setMobiliteAnneau(cursor.getString(24));
champ.setCouleurAnneau(cursor.getString(25));
champ.setPousseTouffe(cursor.getString(26));
champ.setCouleurBasePied(cursor.getString(27));
champ.setCouleurChair(cursor.getString(28));
champ.setOxydationChair(cursor.getString(29));
champ.setCouleurOxydationChair(cursor.getString(30));
champ.setFermeteChair(cursor.getString(31));
champ.setOdeur(cursor.getString(32));
champ.setLatex(cursor.getString(33));
champ.setCouleurLatex(cursor.getString(34));
champ.setMoisPousseTot(cursor.getString(35));
champ.setMoisPousseTard(cursor.getString(36));
champ.setMilieu(cursor.getString(37));
champ.setPousseBois(cursor.getString(38));
champ.setNomVernaculaire(cursor.getString(39));
champ.setComestibilite(cursor.getString(40));
champ.setCommentaires(cursor.getString(41));
champ.setSynonymes(cursor.getString(42));
champignonsList.add(champ);
} while (cursor.moveToNext());
}
return champignonsList;
}
this is my DataBaseHandler classe where I created my table, but it doesn't work ..
I'm just showing you the part where it's about champignons(mushrooms)
and you can find :
- method onCreate where the table champignons is created
- method to create an Mushroom Object
- method which return a list with the elements corresponding to the SQL request
- method which return a list with all the elements of the database
- method
public class DatabaseHandler extends SQLiteOpenHelper {
private static final int DATABASE_VERSION = 1;
private static final String DATABASE_NAME = "db_eyetrek";
private static final String TABLE_CHAMPIGNON = "bddchampignons";
private static final String CHAMP_ID = "id";
private static final String CHAMP_NAME = "name";
private static final String CHAMP_DIAMETRE_MIN = "diametreMin";
private static final String CHAMP_DIAMETRE_MAX = "diametreMax";
private static final String COULEUR_CHAPEAU = "couleurChapeau";
private static final String FORME_CHAPEAU = "formeChapeau";
private static final String SURFACE_CHAPEAU = "surfaceChapeau";
private static final String TYPE_MARGE= "typeMarge";
private static final String COULEUR_MARGE = "couleurMarge";
private static final String DESSOUS_CHAPEAU = "dessousChapeau";
private static final String COULEUR_DESSOUS_CHAPEAU = "couleurDessousChapeau";
private static final String OXYDATION_CHAPEAU = "oxydationChapeau";
private static final String COULEUR_OXYDATION_CHAPEAU = "couleurOxydationChapeau";
private static final String INSERTION_DESSOUS_PIED= "insertionDessousPied";
private static final String ESPACE_LAMELLES = "espaceLamelles";
private static final String TYPE_LAMELLES = "typeLamelles";
private static final String COULEUR_PIED = "couleurPied";
private static final String PIED_CREUX_PLEIN = "piedCreuxPlein";
private static final String FORME_PIED = "formePied";
private static final String LONGEUR_PIED = "longueurPied";
private static final String SURFACE_PIED = "surfacePied";
private static final String POSITION_PIED_CHAPEAU = "positionPiedChapeau";
private static final String PRESENCE_ANNEAU = "presenceAnneau";
private static final String ORIENTATION_ANNEAU = "orientationAnneau";
private static final String MOBILITE_ANNEAU = "mobiliteAnneau";
private static final String COULEUR_ANNEAU = "couleurAnneau";
private static final String POUSSE_TOUFFE = "pousseTouffe";
private static final String COULEUR_BASE_PIED = "couleurBasePied";
private static final String COULEUR_CHAIR = "couleurChair";
private static final String OXYDATION_CHAIR = "oxydationChair";
private static final String COULEUR_OXYDATION_CHAIR = "couleurOxydationChair";
private static final String FERMETE_CHAIR = "fermeteChair";
private static final String ODEUR = "odeur";
private static final String LATEX = "latex";
private static final String COULEUR_LATEX = "couleurLatex";
private static final String MOIS_POUSSE_TOT = "moisPousseTot";
private static final String MOIS_POUSSE_TARD = "moisPousseTard";
private static final String MILIEU = "milieu";
private static final String POUSSE_BOIS = "pousseBois";
private static final String NOM_VERNACULAIRE = "nomVernaculaire";
private static final String COMESTIBILITE = "comestibilite";
private static final String COMMENTAIRES = "commentaires";
private static final String SYNONYMES = "synonymes";
public DatabaseHandler(Context context) {
super(context, DATABASE_NAME, null, DATABASE_VERSION);
getReadableDatabase();
}
#Override
public void onCreate(SQLiteDatabase sqLiteDatabase) {
//Création de la table champignon
String CREATE_CHAMPIGNON_TABLE = "create table if not exists " + TABLE_CHAMPIGNON + " ("
+ CHAMP_ID + " INTEGER PRIMARY KEY AUTOINCREMENT ," + CHAMP_NAME + " VARCHAR (40),"
+ CHAMP_DIAMETRE_MIN + " INTEGER (2)," + CHAMP_DIAMETRE_MAX + " VARCHAR(3) ," + COULEUR_CHAPEAU + " VARCHAR (30)," + FORME_CHAPEAU + " VARCHAR (70),"
+ SURFACE_CHAPEAU + " VARCHAR (105)," + TYPE_MARGE + " VARCHAR (101)," + COULEUR_MARGE + " VARCHAR (11)," + DESSOUS_CHAPEAU + " VARCHAR (26),"
+ COULEUR_DESSOUS_CHAPEAU + " VARCHAR (29)," + OXYDATION_CHAPEAU + " VARCHAR(20)," + COULEUR_OXYDATION_CHAPEAU + " VARCHAR(14)," + INSERTION_DESSOUS_PIED + " VARCHAR (46),"
+ ESPACE_LAMELLES + " VARCHAR (8)," + TYPE_LAMELLES + " VARCHAR (34)," + COULEUR_PIED + " VARCHAR (22)," + PIED_CREUX_PLEIN + " VARCHAR (21),"
+ FORME_PIED + " VARCHAR (165)," + LONGEUR_PIED + " VARCHAR (10)," + SURFACE_PIED + " VARCHAR (84)," + POSITION_PIED_CHAPEAU + " VARCHAR (9),"
+ PRESENCE_ANNEAU + " VARCHAR (3)," + ORIENTATION_ANNEAU + " VARCHAR (10)," + MOBILITE_ANNEAU + " VARCHAR (6)," + COULEUR_ANNEAU + " VARCHAR (43),"
+ POUSSE_TOUFFE + " VARCHAR (3),"+ COULEUR_BASE_PIED + " VARCHAR (21)," + COULEUR_CHAIR + " VARCHAR (30)," + OXYDATION_CHAIR + " VARCHAR (3),"
+ COULEUR_OXYDATION_CHAIR + " VARCHAR (21)," + FERMETE_CHAIR + " VARCHAR (16)," + ODEUR + " VARCHAR (25)," + LATEX + " VARCHAR (3)," + COULEUR_LATEX + " VARCHAR (14),"
+ MOIS_POUSSE_TOT + " VARCHAR (19)," + MOIS_POUSSE_TARD + " VARCHAR (20)," + MILIEU + " VARCHAR (49)," + POUSSE_BOIS + " VARCHAR (3)," + NOM_VERNACULAIRE + " VARCHAR (87),"
+ COMESTIBILITE + " VARCHAR (18)," + COMMENTAIRES + " VARCHAR (332)," + SYNONYMES + " VARCHAR (34) )";
sqLiteDatabase.execSQL(CREATE_CHAMPIGNON_TABLE);
}
#Override
public void onUpgrade(SQLiteDatabase sqLiteDatabase, int oldVersion, int newVersion) {
sqLiteDatabase.execSQL("DROP TABLE IF EXISTS " + TABLE_DIDACTICIEL);
sqLiteDatabase.execSQL("DROP TABLE IF EXISTS " + TABLE_LEAFS);
sqLiteDatabase.execSQL("DROP TABLE IF EXISTS " + TABLE_ANIMAL);
sqLiteDatabase.execSQL("DROP TABLE IF EXISTS " + TABLE_CHAMPIGNON);
onCreate(sqLiteDatabase);
}
public void addChampignon (Mushroom champignon) {
SQLiteDatabase db = this.getWritableDatabase();
ContentValues values = new ContentValues();
values.put(CHAMP_NAME, champignon.getName());
values.put(CHAMP_DIAMETRE_MIN, champignon.getDiametreMin());
values.put(CHAMP_DIAMETRE_MAX, champignon.getDiametreMax());
values.put(COULEUR_CHAPEAU, champignon.getCouleurChapeau());
values.put(FORME_CHAPEAU, champignon.getFormeChapeau());
values.put(SURFACE_CHAPEAU, champignon.getSurfaceChapeau());
values.put(TYPE_MARGE, champignon.getTypeMarge());
values.put(COULEUR_MARGE, champignon.getCouleurMarge());
values.put(DESSOUS_CHAPEAU, champignon.getDessousChapeau());
values.put(COULEUR_DESSOUS_CHAPEAU,champignon.getCouleurDessousChapeau());
values.put(OXYDATION_CHAPEAU, champignon.getOxydationChapeau());
values.put(COULEUR_OXYDATION_CHAPEAU, champignon.getCouleurOxydationChapeau());
values.put(INSERTION_DESSOUS_PIED, champignon.getInsertionDessousPied());
values.put(ESPACE_LAMELLES, champignon.getEspaceLamelles());
values.put(TYPE_LAMELLES, champignon.getTypeLamelles());
values.put(COULEUR_PIED, champignon.getCouleurPied());
values.put(PIED_CREUX_PLEIN, champignon.getPiedCreuxPlein());
values.put(FORME_PIED, champignon.getFormePied());
values.put(LONGEUR_PIED, champignon.getLongueurPied());
values.put(SURFACE_PIED, champignon.getSurfacePied());
values.put(POSITION_PIED_CHAPEAU, champignon.getPositionPiedChapeau());
values.put(PRESENCE_ANNEAU, champignon.getPresenceAnneau());
values.put(ORIENTATION_ANNEAU, champignon.getOrientationAnneau());
values.put(MOBILITE_ANNEAU, champignon.getMobiliteAnneau());
values.put(COULEUR_ANNEAU, champignon.getCouleurAnneau());
values.put(POUSSE_TOUFFE, champignon.getPousseTouffe());
values.put(COULEUR_BASE_PIED, champignon.getCouleurBasePied());
values.put(COULEUR_CHAIR, champignon.getCouleurChair());
values.put(OXYDATION_CHAIR, champignon.getCouleurOxydationChair());
values.put(COULEUR_OXYDATION_CHAIR, champignon.getCouleurOxydationChair());
values.put(FERMETE_CHAIR, champignon.getFermeteChair());
values.put(ODEUR, champignon.getOdeur());
values.put(LATEX, champignon.getLatex());
values.put(COULEUR_LATEX, champignon.getCouleurLatex());
values.put(MOIS_POUSSE_TOT, champignon.getMoisPousseTot());
values.put(MOIS_POUSSE_TARD, champignon.getMoisPousseTard());
values.put(MILIEU, champignon.getMilieu());
values.put(POUSSE_BOIS, champignon.getPousseBois());
values.put(NOM_VERNACULAIRE, champignon.getNomVernaculaire());
values.put(COMESTIBILITE, champignon.getComestibilite());
values.put(COMMENTAIRES, champignon.getCommentaires());
values.put(SYNONYMES, champignon.getSynonymes());
db.insert(TABLE_CHAMPIGNON, null, values);
db.close();
}
/**
* Retourne une liste des champignons correspondant à la requête
*
* #param query
* #return
*/
public List<Mushroom> getChampignonFromRequest(String query) {
List<Mushroom> mushroomList = new ArrayList<Mushroom>();
SQLiteDatabase db = this.getReadableDatabase();
Cursor cursor = db.rawQuery(query, null);
if (cursor.moveToFirst()) {
do {
Mushroom champ = new Mushroom();
champ.setId(Integer.parseInt(cursor.getString(0)));
champ.setName(cursor.getString(1));
champ.setDiametreMin(Integer.parseInt(cursor.getString(2)));
champ.setDiametreMax(Integer.parseInt(cursor.getString(3)));
champ.setCouleurChapeau(cursor.getString(4));
champ.setFormeChapeau(cursor.getString(5));
champ.setSurfaceChapeau(cursor.getString(6));
champ.setTypeMarge(cursor.getString(7));
champ.setCouleurMarge(cursor.getString(8));
champ.setDessousChapeau(cursor.getString(9));
champ.setCouleurDessousChapeau(cursor.getString(10));
champ.setOxydationChapeau(cursor.getString(11));
champ.setCouleurOxydationChapeau(cursor.getString(12));
champ.setInsertionDessousPied(cursor.getString(13));
champ.setEspaceLamelles(cursor.getString(14));
champ.setTypeLamelles(cursor.getString(15));
champ.setCouleurPied(cursor.getString(16));
champ.setPiedCreuxPlein(cursor.getString(17));
champ.setFormePied(cursor.getString(18));
champ.setLongueurPied(cursor.getString(19));
champ.setSurfacePied(cursor.getString(20));
champ.setPositionPiedChapeau(cursor.getString(21));
champ.setPresenceAnneau(cursor.getString(22));
champ.setOrientationAnneau(cursor.getString(23));
champ.setMobiliteAnneau(cursor.getString(24));
champ.setCouleurAnneau(cursor.getString(25));
champ.setPousseTouffe(cursor.getString(26));
champ.setCouleurBasePied(cursor.getString(27));
champ.setCouleurChair(cursor.getString(28));
champ.setOxydationChair(cursor.getString(29));
champ.setCouleurOxydationChair(cursor.getString(30));
champ.setFermeteChair(cursor.getString(31));
champ.setOdeur(cursor.getString(32));
champ.setLatex(cursor.getString(33));
champ.setCouleurLatex(cursor.getString(34));
champ.setMoisPousseTot(cursor.getString(35));
champ.setMoisPousseTard(cursor.getString(36));
champ.setMilieu(cursor.getString(37));
champ.setPousseBois(cursor.getString(38));
champ.setNomVernaculaire(cursor.getString(39));
champ.setComestibilite(cursor.getString(40));
champ.setCommentaires(cursor.getString(41));
champ.setSynonymes(cursor.getString(42));
mushroomList.add(champ);
} while (cursor.moveToNext());
}
cursor.close();
return mushroomList;
}
/**
* Ajout des Champignons depuis& un CSV
*
* #param inputStream
* #param context
*/
public void addChampignonFromCsv(InputStream inputStream, Context context) {
DatabaseHandler db = new DatabaseHandler(context);
Scanner scanner = new Scanner(inputStream);
while (scanner.hasNextLine()) {
String line = scanner.nextLine();
String str[] = line.split(";");
db.addChampignon(new Mushroom(Integer.parseInt(str[0]), str[1], Integer.parseInt(str[2]), Integer.parseInt(str[3]),str[4],str[5],
str[6],str[7],str[8],str[9],str[10],str[11],str[12],str[13],str[14],str[15],
str[16],str[17],str[18],str[19],str[20],str[21],str[22],str[23],str[24],str[25],
str[26],str[27],str[28],str[29],str[30],str[31],str[32],str[33],str[34],str[35],
str[36],str[37],str[38],str[39],str[40],str[41],str[42]));
}
scanner.close();
}
/**
* Retourne tous les champignons de la base de données
*
* #return
*/
public List<Mushroom> getAllChampignons() {
List<Mushroom> champignonsList = new ArrayList<Mushroom>();
String selectQuery = "SELECT * FROM " + TABLE_CHAMPIGNON;
SQLiteDatabase db = this.getReadableDatabase();
Cursor cursor = db.rawQuery(selectQuery, null);
if (cursor.moveToFirst()) {
do {
Mushroom champ = new Mushroom();
champ.setId(Integer.parseInt(cursor.getString(0)));
champ.setName(cursor.getString(1));
champ.setDiametreMin(Integer.parseInt(cursor.getString(2)));
champ.setDiametreMax(Integer.parseInt(cursor.getString(3)));
champ.setCouleurChapeau(cursor.getString(4));
champ.setFormeChapeau(cursor.getString(5));
champ.setSurfaceChapeau(cursor.getString(6));
champ.setTypeMarge(cursor.getString(7));
champ.setCouleurMarge(cursor.getString(8));
champ.setDessousChapeau(cursor.getString(9));
champ.setCouleurDessousChapeau(cursor.getString(10));
champ.setOxydationChapeau(cursor.getString(11));
champ.setCouleurOxydationChapeau(cursor.getString(12));
champ.setInsertionDessousPied(cursor.getString(13));
champ.setEspaceLamelles(cursor.getString(14));
champ.setTypeLamelles(cursor.getString(15));
champ.setCouleurPied(cursor.getString(16));
champ.setPiedCreuxPlein(cursor.getString(17));
champ.setFormePied(cursor.getString(18));
champ.setLongueurPied(cursor.getString(19));
champ.setSurfacePied(cursor.getString(20));
champ.setPositionPiedChapeau(cursor.getString(21));
champ.setPresenceAnneau(cursor.getString(22));
champ.setOrientationAnneau(cursor.getString(23));
champ.setMobiliteAnneau(cursor.getString(24));
champ.setCouleurAnneau(cursor.getString(25));
champ.setPousseTouffe(cursor.getString(26));
champ.setCouleurBasePied(cursor.getString(27));
champ.setCouleurChair(cursor.getString(28));
champ.setOxydationChair(cursor.getString(29));
champ.setCouleurOxydationChair(cursor.getString(30));
champ.setFermeteChair(cursor.getString(31));
champ.setOdeur(cursor.getString(32));
champ.setLatex(cursor.getString(33));
champ.setCouleurLatex(cursor.getString(34));
champ.setMoisPousseTot(cursor.getString(35));
champ.setMoisPousseTard(cursor.getString(36));
champ.setMilieu(cursor.getString(37));
champ.setPousseBois(cursor.getString(38));
champ.setNomVernaculaire(cursor.getString(39));
champ.setComestibilite(cursor.getString(40));
champ.setCommentaires(cursor.getString(41));
champ.setSynonymes(cursor.getString(42));
champignonsList.add(champ);
} while (cursor.moveToNext());
}
return champignonsList;
}
I Have Total 5 Table in SQLite database So if i create a all table in DatabaseHalper.class and perform all CRUD((Create, Read, Update and Delete)) Operation in this class then this is look like a Big Data
Table Is Like: Company, Contact, ToDo. etc
So 1st I Want to create a multiple table in DatabaseHalper.class
2nd Create a another class Like using Table Name ComapnyDB.class
In this Class i want to Perform CRUD operation for a Company Table also All query perform for Company table
3rd same for Contact table. Create table in DatabaseHalper.class
and create a new class like Contact.class in this class perform all CURD operation and perform other operation
So this way my code was Divided in different different class
For Example Below class is my DatabseHalper.class and in this class i'll create a Database Tables.
DatabaseHalper.class
public class DatabaseHelper extends SQLiteOpenHelper {
// Logcat tag
private static final String LOG = "DatabaseHelper";
// Database Version
private static final int DATABASE_VERSION = 1;
// Database Name
private static final String DATABASE_NAME = "contactsManager";
//Tables Name
private static final String COMPANY = "company";
private static final String CONTACTS = "contacts";
private static final String EVENT = "event";
private static final String TODO = "todo";
private static final String USER = "user";
// Common column names
private static final String KEY_ID = "id";
//Companies Table Column Name
private static final String KEY_COMPANY_ID = "CompanyId";
private static final String KEY_COMPANY_REFERENCE_ID = "ReferenceId";
private static final String KEY_COMPANY_NAME = "CompanyName";
private static final String KEY_COMPANY_WEBSITE = "CompanyWebsite";
private static final String KEY_COMPANY_EMAIL = "CompanyEmail";
private static final String KEY_COMPANY_PHONE_HOME = "CompanyPhoneHome";
private static final String KEY_COMPANY_PHONE_PRIMARY = "CompanyPhonePrimary";
private static final String KEY_COMPANY_ADDRESS1 = "CompanyAddress";
private static final String KEY_COMPANY_ADDRESS2 = "CompanyAddressSecondary";
private static final String KEY_COMPANY_CITY = "CompanyCity";
private static final String KEY_COMPANY_STATE = "CompanyState";
private static final String KEY_COMPANY_ZIP = "CompanyZip";
private static final String KEY_COMPANY_COUNTRY = "CompanyCountry";
public DatabaseHelper(Context context) {
super(context, DATABASE_NAME, null, DATABASE_VERSION);
}
// Table Create Statements
// Todo table create statement
private static final String CREATE_TABLE_COMPANY = "CREATE TABLE "
+ COMPANY + "(" + KEY_ID + " INTEGER PRIMARY KEY," + KEY_COMPANY_ID + " INTEGER,"
+ KEY_COMPANY_REFERENCE_ID + " INTEGER,"
+ KEY_COMPANY_NAME + " VARCHAR,"
+ KEY_COMPANY_WEBSITE + "VARCHAR,"
+ KEY_COMPANY_EMAIL + "VARCHAR,"
+ KEY_COMPANY_PHONE_HOME + "VARCHAR,"
+ KEY_COMPANY_PHONE_PRIMARY + "VARCHAR,"
+ KEY_COMPANY_ADDRESS1 + "VARCHAR,"
+ KEY_COMPANY_ADDRESS2 + "VARCHAR,"
+ KEY_COMPANY_CITY + "VARCHAR,"
+ KEY_COMPANY_STATE + "VARCHAR,"
+ KEY_COMPANY_ZIP + "INTEGER,"
+ KEY_COMPANY_COUNTRY + "VARCHAR" + ")";
#Override
public void onCreate(SQLiteDatabase db) {
db.execSQL(CREATE_TABLE_COMPANY);
}
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
db.execSQL("DROP TABLE IF EXISTS " + COMPANY);
}
}
Now I'll Create CompanyDB.class For a CURD Operation But How to i access DatabaseHelper.class In Company.class.
Thanks In Advance :)
The following is an example of splitting tables away from the DatabaseHelper :-
ContactDB.java
public class ContactDB {
public static final String TBNAME = "contact";
public static final String COL_ID = BaseColumns._ID;
public static final String COL_NAME = "contact_name";
public static final String COL_EMAIL = "contact_email";
public static String getTableCreatSQL() {
return "CREATE TABLE IF NOT EXISTS " + TBNAME + "(" +
COL_ID + " INTEGER PRIMARY KEY, " +
COL_NAME + " TEXT," +
COL_EMAIL + " TEXT" +
")";
}
public static long addContact(SQLiteDatabase db, String contact_name, String contact_email) {
ContentValues cv = new ContentValues();
cv.put(COL_NAME,contact_name);
cv.put(COL_EMAIL,contact_email);
return db.insert(TBNAME,null,cv);
}
public static Cursor getAllContacts(SQLiteDatabase db) {
return db.query(TBNAME,null,null,null,null,null,COL_NAME + " ASC," + COL_EMAIL + " ASC");
}
}
CompanyDB.java
public class CompanyDB {
public static final String TBNAME = "company";
public static final String COL_ID = BaseColumns._ID;
public static final String COL_NAME = "company_name";
public static String getTableCreateSQL() {
return "CREATE TABLE IF NOT EXISTS " + TBNAME + "(" +
COL_ID + " INTEGER PRIMARY KEY," +
COL_NAME + " TEXT" +
")";
}
public static long addCompany(SQLiteDatabase db, String company_name ) {
ContentValues cv = new ContentValues();
cv.put(COL_NAME,company_name);
return db.insert(TBNAME,null,cv);
}
public static Cursor getAllCompanies(SQLiteDatabase db) {
return db.query(TBNAME,null,null,null,null,null,COL_NAME + " ASC");
}
}
DBHelper.java (Database helper)
public class DBHelper extends SQLiteOpenHelper {
public static final String DBNAME = "mydatabase";
public static final int DBVERSION = 1;
private static SQLiteDatabase mDB;
public DBHelper(Context context) {
super(context, DBNAME, null, DBVERSION);
mDB = this.getWritableDatabase();
}
#Override
public void onCreate(SQLiteDatabase db) {
db.execSQL(CompanyDB.getTableCreateSQL());
db.execSQL(ContactDB.getTableCreatSQL());
}
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
}
}
MainActivity.java
public class MainActivity extends AppCompatActivity {
Cursor mAllContacts;
Cursor mAllCompanies;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
SQLiteDatabase mDB = new DBHelper(this).getWritableDatabase();
CompanyDB.addCompany(mDB,"mycompany");
ContactDB.addContact(mDB,"Fred","Fred#email.com");
ContactDB.addContact(mDB,"Bert","bertbloggins#bloggings.moc");
mAllCompanies = CompanyDB.getAllCompanies(mDB);
while (mAllCompanies.moveToNext()) {
Log.d("COMPANY",
"Company Name = " +
mAllCompanies.getString(
mAllCompanies.getColumnIndex(
CompanyDB.COL_NAME
)
)
);
}
Cursor mAllContacts = ContactDB.getAllContacts(mDB);
while (mAllContacts.moveToNext()) {
Log.d("CONTACT",
"Contact Name = " +
mAllContacts.getString(
mAllContacts.getColumnIndex(
ContactDB.COL_NAME
)
) +
" Email = " +
mAllContacts.getString(
mAllContacts.getColumnIndex(
ContactDB.COL_EMAIL
)
)
);
}
}
#Override
protected void onDestroy() {
super.onDestroy();
mAllCompanies.close();
mAllContacts.close();
}
}
This will add a company and 2 contacts (each time that it is run), retrieve the companies and contacts from the database and write the details to the log.
Output would be lime (first run) :-
04-02 09:09:42.556 1497-1497/so49607475_splittableclasses.so49607475_splittableclasses D/COMPANY: Company Name = mycompany
04-02 09:09:42.556 1497-1497/so49607475_splittableclasses.so49607475_splittableclasses D/CONTACT: Contact Name = Bert Email = bertbloggins#bloggings.moc
Contact Name = Fred Email = Fred#email.com
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
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)));