How to view a data in table - android

I inserted EditText value in database, Please help me how to get all the data in table and show it in a next Activity, please help me. I use the following code for inserting:
private static final String DATABASE_CREATE = "create table pill (id integer primary key autoincrement, "
+ "med VARCHAR, " + "dose1 VARCHAR,"+"dose2 VARCHAR,"+"dose3 VARCHAR);";
// ---insert data into the database---
public long insertData(String med, String dose1,String dose2,String dose3) {
ContentValues initialValues = new ContentValues();
initialValues.put(Med, med);
initialValues.put(Dose1, dose1);
initialValues.put(Dose2, dose2);
initialValues.put(Dose3, dose3);
return db.insert(DATABASE_TABLE, null, initialValues);
}
med, dose1, dose2, dose3 are the values from the EditText which is in another class.

You have to use:
db.query()
See that
Query only the first data from a table

Related

How can i store columns dynamically in SQLite database in android?

I am new in Android development.Please help me How can i store columns name in Sqlite database dynamically.
Create database below here:
public void onCreate(SQLiteDatabase db) {
// TODO Auto-generated method stub
db.execSQL(
"create table contacts " +
"(id integer primary key, name text,phone text,email text, street text,place text)"
);
}
And insert query below here:
public boolean insertContact (String name, String phone, String email,String street,String place)
{
SQLiteDatabase db = this.getWritableDatabase();
ContentValues contentValues = new ContentValues();
contentValues.put("name", name);
contentValues.put("phone", phone);
contentValues.put("email", email);
contentValues.put("street", street);
contentValues.put("place", place);
db.insert("contacts", null, contentValues);
return true;
}
you can use ALTER TABLE function on your onUpgrade() method, like this :
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
// If you need to add a column
if (newVersion > oldVersion) {
db.execSQL("ALTER TABLE foo ADD COLUMN new_column INTEGER DEFAULT 0");
}
}
Obviously, the SQLite will differ depending on the column definition
You do not need to provide a value for every column in your table to insert a new row. You can just change the code in your method to:
public long insertContact(ContentValues contentValues) {
return db.insert("contacts", null, contentValues);
}
Let the calling function decide which values it wants to insert, which can be all, some or none of the available columns. Any values not specified will be null in the table. For example if calling function does:
EditText name, email;
// ...
ContentValues values = new ContentValues();
values.put("name", name.getText().toString());
values.put("email", email.getText().toString());
insertContact(values);
will insert a new row in the database with "name" and "email" filled in and the rest of the columns null.

Can't stop table from autoincrement id when insert unique field

I have a table with 2 columns, a numeric id and unique text. Created like this:
String CREATE_MY_TABLE = "CREATE TABLE " + TABLE_TEST + "("
+ KEY_ID + " INTEGER PRIMARY KEY AUTOINCREMENT,"
+ KEY_FOO + " TEXT UNIQUE"
+ ")";
db.execSQL(CREATE_MY_TABLE);
I want that when I insert KEY_FOO value and it's already in the db, nothing happens. But what I get is that the id is always incremented. No new row is inserted, that's good, but the id is autoincremented.
What I'm doing to insert is as follows:
db.insertWithOnConflict(TABLE_TEST , null, values, SQLiteDatabase.CONFLICT_NONE);
I tried CONFLICT_IGNORE, CONFLICT_ABORT, CONFLICT_ROLLBACK, all the same.
The reason I need this is because other table has a foreign key on this id, thus if the id is changed, the other table points nowhere.
How I just say to let the existing entry untouched?
Try this way. In your dbhelper class write the method like following to insert.
public int insertData(String desc) {
db = this.getWritableDatabase();
ContentValues cv = new ContentValues();
try {
db.beginTransaction();
cv.put(KEY_FOO, desc);
db.insertOrThrow(TABLE_TEST, null, cv);
db.setTransactionSuccessful();
} catch (Exception ex) {
return 1;
} finally {
db.endTransaction();
db.close();
}
return 0;
}
Then from your actvity you call this method with the parameter value of KEY_FOO. This method will return 1 if the exception is occurs (If you try insert a unique value) and it will return 0 if the transaction is successfull.
I hope this way will help you. Let me know if any problem.

How to skip the primary key when inserting ContentValues in SQLiteDatabase

I have a little Problem with an insert-Statement in my Android-App.
Here is the code:
public void addNote(Note noteItem, int modulNummer){
SQLiteDatabase db = getWritableDatabase();
ContentValues cv = new ContentValues();
cv.put(COLUMN_NOTE, noteItem.getNote());
cv.put(COLUMN_NOTEBESCHREIBUNG, noteItem.getBeschreibung());
cv.put(COLUMN_MODULID_FK, modulNummer);
db.insert(NOTETABLE, null, cv);
}
Now my problem. The first column in my table is an auto increment pk. And so i want to skip the first column and i want to begin the insert in the second column. How can i skip this first column?
Update
I've already deleted the .put for the first column. "COLUMN_NOTE" is my second column.
My table-structure looks like this:
id INTEGER AUTO INCREMENT
note double
beschreibung TEXT
modul_id INTEGER
UPDATE 2
I don't know why, but now it works. Thx for your help guys.
If you have a table like the following one:
private final String TAB_GROUP_ADD = "CREATE TABLE groups (id INTEGER PRIMARY KEY AUTOINCREMENT, title TEXT NOT NULL, description TEXT NOT NULL);";
And you use the following insert command:
ContentValues values = new ContentValues();
values.put(K_TITLE, title);
values.put(K_DESCRIPTION, description);
db.insert(TAB_GROUP, null, values);
Everything should go fine. The primary key field "id" will no be filled in by Java and the SQLite Database will do it for you.

data cant be inserted to the sqlit database tables

I am trying to insert data in my sqlit database but I got android SQLiteConstraintException: error code 19: constraint failed exception. I saw there are tons of question in this topic, I've read and tried a bunch of them, but the exception still , i wonder if this exception caused by the auto increment food_id value , since the insert statement return -1 , and i wonder that why this exception occur since the first insert id done correctly but all the later inserting are failed , why this error occur ,and how i can solve it? please help me..
the create statements in the DBAdapter class
private static final String Meal_TABLE_CREATE= "create table IF NOT EXISTS Meal (Date text not null , "+
"Time text not null,MealType text not null,"+ " primary key(Date,Time ,MealType) );" ;
private static final String FOOD_TABLE_CREATE= "create table IF NOT EXISTS Food (_id INTEGER primary key AUTOINCREMENT , "+
"Food_Name text not null,Calories integer not null,"+ "VB12 integer not null,Cholesterol integer not null,"+
"Protein integer not null,Iron integer not null,Sodium integer not null,Fat_Mono integer not null,Fat_Sat integer not null,carbohydrate integer not null);" ;
private static final String MealFOOD_TABLE_CREATE= "create table IF NOT EXISTS MealFood (Date text not null , "+
"Time text not null,MealType text not null,"+"Food_ID integer not null , primary key(Date,Time ,MealType,Food_ID) );" ;
inserting methods
// insert meal to the meal table
public long SaveMeal(String date , String time , String mealType)
{
ContentValues content = new ContentValues();
content.put(KEY_MDATE,date);
content.put(KEY_MTIME,time);
content.put(KEY_MEALTYPE,mealType);
return db.insert(MEAL_TABLE_NAME, null, content);
}
// insert Food to the Food table
public long SaveFood(String name,int calories,int Vit_B12,int cholesterol,int protein ,int iron ,int sodium,int Fat_Mono,int Fat_Sat,int carbohydrate)
{
ContentValues content = new ContentValues();
content.put(KEY_FOODNAME,name);
content.put(KEY_CALORIES,calories);
content.put(KEY_VB12,Vit_B12);
content.put(KEY_CHOLESTEROL,cholesterol);
content.put(KEY_PROTEIN,protein);
content.put(KEY_IRON,iron);
content.put(KEY_SODIUM,sodium);
content.put(KEY_FAT_MONO,Fat_Mono);
content.put(KEY_FAT_Sat,Fat_Sat);
content.put(KEY_CARBOHYDRATE,carbohydrate);
return db.insert(FOOD_TABLE_NAME, null, content);
}
// get food id by its name
public int getFoodIDByName(String name) throws SQLException
{ int id;
Cursor cursor = null;
try{
cursor=db.query(true,FOOD_TABLE_NAME, new String[]{KEY_FOODID}, KEY_FOODNAME+ " = '" + name + "'", null, null, null, null,null);
if (cursor != null) {
cursor.moveToFirst();
}
id=0;
while (cursor.moveToNext())
id=cursor.getInt(cursor.getColumnIndex(KEY_FOODID));
}
finally{
cursor.close();
cursor.deactivate();
}
return id;
}
// insert mealFood to mealFood table
public long SaveMealFood(String date , String time , String mealType, int Food_id)
{
ContentValues content = new ContentValues();
content.put(KEY_MFDATE,date);
content.put(KEY_MFTIME,time);
content.put(KEY_MFMEALTYPE,mealType);
content.put(KEY_MFFOODID,Food_id);
return db.insert(MEALFOOD_TABLE_NAME, null, content);
}
java code
DBAdapter dbAdapter=new DBAdapter(SaveMeal.this);
dbAdapter.open();
Food n;
String m;
int FoodIDByName;
for(int i = 0; i <MealActivity.array.size(); i++){
m=MealActivity.array.get(i).toString();
Log.e("tag", m);//selected food name
for (int j = 0; j < MealActivity.tempList.size(); j++){
n=MealActivity.tempList.get(j);
if(n.getFOOD_NAME().equals(m)){
//save food
long food_id = dbAdapter.SaveFood(n.getFOOD_NAME(),n.getCALORIES(),n.getFOOD_VITAMIN_B12(),n.getCHOLESTEROL(),n.getFOOD_PROTEIN(),n.getFOOD_IRON(),n.getFOOD_SODIUM(),
n.getFOOD_MONO_UNSATURATED_FAT(),n.getFOOD_SATURATED_FAT(),n.getFOOD_TOTAL_CARBOHYDRATE());
Log.e("tag", food_id+" food inserting done");
//save meal
long meal_id= dbAdapter.SaveMeal( meal_date,meal_time,Meal.MEAL_TYPE);
Log.e("tag",meal_id+" meal inserting done");
//save meal_food
FoodIDByName=dbAdapter.getFoodIDByName(n.FOOD_NAME);
Log.e("tag",FoodIDByName+" food_id");
long meal_food_id=dbAdapter.SaveMealFood(meal_date,meal_time,Meal.MEAL_TYPE,FoodIDByName);
Log.e("tag",meal_food_id+" meal_food inserting done");
dbAdapter.close();
this result of this line Log.e("tag", food_id+" food inserting done"); in my log is -1
mylog
Database(657):at android.database.sqlite.SQLiteStatement.native_execute(Native Method)
Database(657):at android.database.sqlite.SQLiteStatement.execute (SQLiteStatement.java:55)
Database(657):at android.database.sqlite.SQLiteDatabase.insert(SQLiteDatabase.java:1410)
-1 food inserting done
18 meal inserting done
0 food_id
13 meal_food inserting done
Try to remove all (Not NULL) constraints, and save the empty food.
If it is saved properly, try to add the constraint (NOT NULL) one by one.
I think one of the values is passed as NULL.
That error.means you are.violating a constraint (obviously). Most likely leave a "not null" column null.
You could also have violated your primary key by trying to save the same combination more than once.

SQLiteConstraintException: error code 19: constraint failed

I'm getting that exception when I do an insert in my SQLite database
The following code gives me the exception:
mDbHelper.createUser("pablo","a","a","a","a");
The code from mDbHelper (MyDbAdapter):
private static final String USER_TABLE_CREATE = "CREATE TABLE user ( email varchar, password varchar, fullName varchar, mobilePhone varchar, mobileOperatingSystem varchar, PRIMARY KEY (email))";
public long createUser(String email, String password, String fullName, String mobilePhone, String mobileOperatingSystem)
{
ContentValues initialValues = new ContentValues();
initialValues.put("email",email);
initialValues.put("password",password);
initialValues.put("fullName",fullName);
initialValues.put("mobilePhone",mobilePhone);
initialValues.put("mobileOperatingSystem",mobileOperatingSystem);
return mDb.insert("user", null, initialValues);
}
The exception is created on the last line: return mDb.insert("user", null, initialValues);
You are inserting a duplicate email.
Plus the recommended way is to have a _ID column as primary key, even if you don't use it. This way on future uses, like use in a Adapter or List, you won't have to workaround.

Categories

Resources