Display SQLite data in Android tablelayout - java

Im trying to retrieve data from SQLite database table and display as tablelayout in android. However it only display the title and the textview. What is wrong with the codes?
Graf.java
public class Graf extends AppCompatActivity {
DatabaseHelper myDb;
TextView dt, water, inc;
TableLayout tableLayout;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_graf);
myDb=new DatabaseHelper(this);
dt=(TextView)findViewById(R.id.date);
water=(TextView)findViewById(R.id.water);
inc=(TextView)findViewById(R.id.inc);
tableLayout=(TableLayout)findViewById(R.id.tableLayout1);
setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
final String date=getDate();
Toast.makeText(getApplicationContext(),date, Toast.LENGTH_SHORT).show();
BuildTable(date);
}
private void BuildTable(String date){
Cursor c=myDb.readEntry(date);
int rows=c.getCount();
int cols=c.getColumnCount();
c.moveToFirst();
for (int i=0;i<rows;i++){
TableRow row=new TableRow(this);
row.setLayoutParams(new ViewGroup.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT));
for (int j=0;j<cols;j++){
TextView tv=new TextView(this);
tv.setLayoutParams(new ViewGroup.LayoutParams(ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT));
tv.setBackgroundResource(R.drawable.cell_shape);
tv.setGravity(Gravity.CENTER);
tv.setTextSize(18);
tv.setPadding(0,5,0,5);
tv.setText(c.getString(j));
row.addView(tv);
}
c.moveToNext();
tableLayout.addView(row);
}
}
/*public void getData(){
buttonA.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
Cursor res = myDb.getAllData();
if (res.getCount() == 0) {
showMessage("Ralat", "Tiada Rekod.");
}
StringBuffer buffer = new StringBuffer();
while (res.moveToNext()) {
buffer.append("Tarikh : " + res.getString(1) + "\n");
buffer.append("Air Diminum : " + res.getString(2) + "\n");
buffer.append("Pencapaian : " + res.getString(3) + "\n\n");
showMessage("Laporan", buffer.toString());
}
}
});
}
public void showMessage(String title, String message){
AlertDialog.Builder builder=new AlertDialog.Builder(this);
builder.setCancelable(true);
builder.setTitle(title);
builder.setMessage(message);
builder.show();
}*/
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.menu_graf, menu);
return true;
}
private String getDate() {
SimpleDateFormat dateFormat = new SimpleDateFormat(
"yyyy-MM-dd", Locale.getDefault());
Date date = new Date();
return dateFormat.format(date);
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
//noinspection SimplifiableIfStatement
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
}
activity_graf.xml
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
xmlns:tools="http://schemas.android.com/tools"
android:orientation="vertical"
tools:context="info.androidhive.materialdesign.activity.Graf">
<TextView
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:gravity="center_horizontal"
android:textSize="45dp"
android:textAppearance="?android:attr/textAppearanceLarge"
android:text="LAPORAN MINGGUAN ANDA"
android:id="#+id/textView7"
android:textStyle="bold"
android:layout_alignParentTop="true"
android:layout_alignParentLeft="true"
android:layout_alignParentStart="true" />
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="horizontal" >
<TextView
android:id="#+id/date"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Tarikh" />
<TextView
android:id="#+id/water"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:hint="Penambahan Air" />
<TextView
android:id="#+id/inc"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Peningkatan Peratus" />
</LinearLayout>
<ScrollView
android:layout_width="match_parent"
android:layout_height="match_parent" >
<TableLayout
android:id="#+id/tableLayout1"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:padding="10dp">
</TableLayout>
</ScrollView>
</LinearLayout>
DatabaseHelper.java
public class DatabaseHelper extends SQLiteOpenHelper {
DatabaseHelper myDb;
SQLiteDatabase db = this.getWritableDatabase();
public static final String DATABASE_NAME = "HU.db";
public static final String TABLE_NAME = "User_table";
public static final String COL_1 = "ID";
public static final String COL_2 = "NAME";
public static final String COL_4 = "GENDER";
public static final String COL_5 = "WEIGHT";
public static final String COL_6 = "HEIGHT";
public static final String COL_7 = "ACTIVENESS";
public static final String COL_8 = "TARGET";
public static final String TABLE2_NAME = "Drink_Table";
public static final String COL2_1 = "DRINK_ID";
public static final String COL2_2 = "DATE";
public static final String COL2_3 = "AMOUNT";
public static final String COL2_4 = "PERCENT";
public static final String COL2_5 = "ID";
public DatabaseHelper(Context context) {
super(context, DATABASE_NAME, null, 1);
}
#Override
public void onCreate(SQLiteDatabase db) {
db.execSQL("create table " + TABLE_NAME + "(ID INTEGER PRIMARY KEY AUTOINCREMENT, NAME TEXT, GENDER TEXT, WEIGHT DOUBLE, HEIGHT DOUBLE, ACTIVENESS INTEGER, TARGET DOUBLE)");
db.execSQL("create table " + TABLE2_NAME + " (DRINK_ID INTEGER PRIMARY KEY AUTOINCREMENT, DATE DATETIME DEFAULT CURRENT_DATE, AMOUNT DOUBLE, PERCENT DOUBLE, ID INTEGER, FOREIGN KEY(ID) REFERENCES " + TABLE_NAME + "(ID))");
db.execSQL("create table "+TABLE3_NAME+" (Entry_ID INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL , ID INTEGER, DATE DATETIME DEFAULT CURRENT_DATE, TOTALAMOUNT DOUBLE, TOTAL PERC DOUBLE, FOREIGN KEY(DATE) REFERENCES "+TABLE2_NAME+"(DATE), FOREIGN KEY(ID) REFERENCES "+TABLE_NAME+"(ID))");
}
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
db.execSQL("DROP TABLE IF EXIST " + TABLE_NAME);
onCreate(db);
}
public boolean insertData(String name, String gender, String weight, String height, String activeness, String target) {
SQLiteDatabase db = this.getWritableDatabase();
ContentValues contentValues = new ContentValues();
contentValues.put(COL_2, name);
contentValues.put(COL_4, gender);
contentValues.put(COL_5, weight);
contentValues.put(COL_6, height);
contentValues.put(COL_7, activeness);
contentValues.put(COL_8, target);
long result = db.insert(TABLE_NAME, null, contentValues);
if (result == -1)
return false;
else
return true;
}
public boolean updateData(String id, String name, String gender, String weight, String height, String activeness, String target) {
SQLiteDatabase db = this.getWritableDatabase();
ContentValues contentValues = new ContentValues();
contentValues.put(COL_1, id);
contentValues.put(COL_2, name);
contentValues.put(COL_4, gender);
contentValues.put(COL_5, weight);
contentValues.put(COL_6, height);
contentValues.put(COL_7, activeness);
contentValues.put(COL_8, target);
db.update(TABLE_NAME, contentValues, "ID = ?", new String[]{id});
return true;
}
public boolean addWater(String date, String id, double amount) {
SQLiteDatabase db = this.getWritableDatabase();
ContentValues contentValues = new ContentValues();
double target = getTargetu(id);
contentValues.put(COL2_2, date);
contentValues.put(COL2_3, amount);
contentValues.put(COL2_4, (amount / target) * 100);
contentValues.put(COL2_5, id);
long result = db.insert(TABLE2_NAME, null, contentValues);
if (result == -1)
return false;
else
return true;
}
public Cursor readEntry(String date) {
SQLiteDatabase db = this.getWritableDatabase();
String selectQuery = ("SELECT DATE, AMOUNT, PERCENT FROM "+TABLE2_NAME+"WHERE DATE= ?");
Cursor c = db.query(TABLE2_NAME,new String[]{COL2_2,COL2_3,COL2_4},COL2_2+"=?", new String[] { String.valueOf(date)}, null, null, null, null);
if (c != null) {
c.moveToFirst();
}
return c;
}
private String getDate() {
SimpleDateFormat dateFormat = new SimpleDateFormat(
"yyyy-MM-dd", Locale.getDefault());
Date date = new Date();
return dateFormat.format(date);
}
}

I think the problem is with picking wrong layout params. Should be:
row.setLayoutParams(new TableRow.LayoutParams(TableRow.LayoutParams.MATCH_PARENT,
TableRow.LayoutParams.WRAP_CONTENT));
tv.setLayoutParams(new TableRow.LayoutParams(TableRow.LayoutParams.WRAP_CONTENT,
TableRow.LayoutParams.WRAP_CONTENT));
Table layout requires table Layout params.

Related

I have a retention window, but the data is not saved. How to store the value of boolean in the database?

Hello everybody. I'm trying to make an application that works with the database. I have a retention window, but the data is not saved. How to save the value boolean from check-box into the database?
How to resole this problem?
This is code of Database
public class DataBase extends SQLiteOpenHelper{
public static final String DATABASE_NAME = "DataOfSchedule.db";
public static final String TABLE_NAME = "DataOfSchedule_table";
public static final String COL_1 = "ID";
public static final String COL_2 = "NAME";
public static final String COL_3 = "AGE";
public static final String COL_4 = "SEX_MALE";
public static final String COL_7 = "SEX_FEMALE";
public static final String COL_5 = "WEIGHT";
public static final String COL_6 = "HEIGHT";
public static final String COL_8 = "TRAUMA";
public DataBase(Context context){
super(context, DATABASE_NAME, null,1);
}
#Override
public void onCreate(SQLiteDatabase db){
db.execSQL("CREATE TABLE" + TABLE_NAME + "(ID INTEGER PRIMARY KEY," +
" NAME TEXT," +
" AGE INTEGER NOT NULL DEFAULT 0 , " +
"SEX_MALE TEXT NOT NULL \n" +
" CHECK( typeof(\"boolean\") = \"text\" AND\n" +
" \"boolean\" IN (\"TRUE\",\"FALSE\") ," +
"SEX_FEMALE TEXT NOT NULL \n" +
" CHECK( typeof(\"boolean\") = \"text\" AND\n" +
" \"boolean\" IN (\"TRUE\",\"FALSE\")," +
"TRAUMA NOT NULL TEXT NOT NULL \n" +
" CHECK( typeof(\"boolean\") = \"text\" AND\n" +
" \"boolean\" IN (\"TRUE\",\"FALSE\")," +
"WEIGHT INTEGER NOT NULL DEFAULT 0," +
"HEIGHT INTEGER NOT NULL DEFAULT 0)");
}
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion){
db.execSQL("DROP TABLE IF EXISTS" + TABLE_NAME);
}
public boolean insertData(String name, Integer age, String sex_male, String sex_female, Integer weight, Integer height, String trauma){
SQLiteDatabase db = this.getWritableDatabase();
ContentValues contentValues = new ContentValues();
contentValues.put(COL_2,name);
contentValues.put(COL_3,age);
contentValues.put(COL_4,sex_male);
contentValues.put(COL_5,weight);
contentValues.put(COL_6,height);
contentValues.put(COL_7,sex_female);
contentValues.put(COL_8,trauma);
long result = db.insert(TABLE_NAME,null,contentValues);
db.close();
//To Check Whether Data is Inserted in DataBase
if(result==-1){
return false;
}else{
return true;
}
}
public Cursor getALLData(){
SQLiteDatabase db = this.getWritableDatabase();
Cursor res = db.rawQuery("Select * from "+ TABLE_NAME,null);
return res;
}
}
It is code of Activity which inserts data
public class InsertData extends AppCompatActivity {
DataBase myDb;
EditText txtName, txtAge , txtWeight, txtHeight;
CheckBox boxSex_male,boxSex_female,boxTrauma;
Button btnClick;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_insert_data);
myDb = new DataBase(this);
txtName = (EditText) findViewById(R.id.name);
txtAge = (EditText) findViewById(R.id.age);
boxSex_male = (CheckBox) findViewById(R.id.sex_m);
boxTrauma = (CheckBox) findViewById(R.id.trauma);
boxSex_female = (CheckBox) findViewById(R.id.sex_f);
txtWeight = (EditText) findViewById(R.id.weight);
txtHeight = (EditText) findViewById(R.id.height);
btnClick = (Button) findViewById(R.id.InsertBtn);
btnClick.setOnClickListener(new View.OnClickListener(){
#Override
public void onClick(View v){
ClickMe();
}
});
if(boxTrauma.isChecked()){
boxTrauma.setChecked(true);
}else {
boxTrauma.setChecked(false);
}
if(boxSex_female.isChecked()){
boxSex_female.setChecked(true);
}else {
boxSex_female.setChecked(false);
}
if(boxSex_male.isChecked()){
boxSex_male.setChecked(true);
}else {
boxSex_male.setChecked(false);
}
}
private void ClickMe(){
String name = txtName.getText().toString();
String age = txtAge.getText().toString();
String sex_male = boxSex_male.getText().toString();
String trauma = boxTrauma.getText().toString();
String sex_female = boxSex_female.getText().toString();
String weight = txtName.getText().toString();
String height = txtName.getText().toString();
int weight_int = Integer.parseInt(weight);
int age_int = Integer.parseInt(age);
int height_int = Integer.parseInt(height);
Boolean result = myDb.insertData(name,age_int,sex_male,sex_female,weight_int,height_int,trauma);
if (result == true){
Toast.makeText(this, "Data Inserted Successfully",Toast.LENGTH_SHORT).show();
}else{
Toast.makeText(this, "Data Inserted Failed",Toast.LENGTH_SHORT).show();
}
Intent i = new Intent(this,ResultData.class);
startActivity(i);
}
}
It is my HTML
<ScrollView xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:padding="16dp"
tools:context="daniel_nikulshyn_and_andrew_rybka.myway.InsertData">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
android:layout_alignParentTop="true"
android:layout_alignParentLeft="true"
android:layout_alignParentStart="true">
<TextView
android:id="#+id/heading"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="#string/insert_heading"
android:layout_gravity="center"
android:textSize="16dp"
android:textColor="#021aee"/>
<EditText
android:id="#+id/name"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:hint="#string/insert_name"/>
<EditText
android:id="#+id/age"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:hint="#string/insert_age"
android:numeric="integer"/>
<EditText
android:id="#+id/weight"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:hint="#string/insert_weight"
android:numeric="integer"/>
<EditText
android:id="#+id/height"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:hint="#string/insert_height"
android:numeric="integer"/>
<TextView
android:padding="10dp"
android:text="#string/insert_sex"
android:layout_gravity="left"
android:layout_width="wrap_content"
android:layout_height="wrap_content" />
<CheckBox
android:id="#+id/sex_m"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="#string/male"/>
<CheckBox
android:id="#+id/sex_f"
android:text="#string/female"
android:layout_width="wrap_content"
android:layout_height="wrap_content" />
<TextView
android:padding="10dp"
android:text="#string/insert_trauma"
android:layout_gravity="left"
android:layout_width="wrap_content"
android:layout_height="wrap_content" />
<CheckBox
android:id="#+id/trauma"
android:text="#string/insert_trauma_subtitle"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginBottom="20dp"/>
<Button
android:id="#+id/InsertBtn"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:background="#color/colorPrimary"
android:text="#string/insert_button"
android:textColor="#f2fde4"
android:layout_gravity="center"/>
</LinearLayout>
</ScrollView>
Lets break this problem down into a couple of Posts. First we can deal with the SQLite part of the code then you can post a new question about inserting values--there is just to much code to cover and make this understandable.
Change your code in your DataBase class (BTW: Not a good name!)
Give the variable names for the columns an understandable name. Who can remember what COL_6 is? Also consider that these probably do not need to be public.
public static final String COL_ID = "ID";
public static final String COL_NAME = "NAME";
public static final String COL_AGE = "AGE";
public static final String COL_GENDER = "GENDER";
public static final String COL_WEIGHT = "WEIGHT";
public static final String COL_HEIGHT = "HEIGHT";
public static final String COL_TRAUMA = "TRAUMA";
You might not want to check if the table already exists, but I added the check anyway. I also made ID an AUTOINCREMENT column.
#Override
public void onCreate(SQLiteDatabase db){
db.execSQL("CREATE TABLE IF NOT EXISTS " + TABLE_NAME + " (" +
COL_ID + " INTEGER PRIMARY KEY AUTOINCREMENT, " +
COL_NAME + " TEXT," +
COL_AGE + " INTEGER NOT NULL DEFAULT 0, " +
COL_GENDER + " INTEGER NOT NULL DEFAULT 0, " +
COL_TRAUMA + " INTEGER NOT NULL DEFAULT 0, " +
COL_WEIGHT + " INTEGER NOT NULL DEFAULT 0, " +
COL_HEIGHT + " INTEGER NOT NULL DEFAULT 0);");
}
Change the insertData method to accommodate the changes to the static final variables for the columns and the type changes of the parameters:
public boolean insertData(String name, Integer age, Integer sex_male, Integer weight, Integer height, Integer trauma){
boolean success = false;
try{
SQLiteDatabase db = this.getWritableDatabase();
ContentValues contentValues = new ContentValues();
contentValues.put(COL_NAME, name);
contentValues.put(COL_AGE, age);
contentValues.put(COL_GENDER, sex_male);
contentValues.put(COL_WEIGHT, weight);
contentValues.put(COL_HEIGHT, height);
contentValues.put(COL_TRAUMA, trauma);
long result = db.insert(TABLE_NAME,null,contentValues);
db.close();
if(result != -1) success = true;
}
catch(Exception ex){
Log.e(TAG, ex.getMessage());
}
return success;
}
Also note, no need to get a Writeable database in your getALLData() method:
public Cursor getALLData(){
SQLiteDatabase db = this.getReadableDatabase();
Cursor res = db.rawQuery("Select * from "+ TABLE_NAME, null);
return res;
}
Now post a new question on how the populate the database from your Activity and we can go from there...

I cannot use boolean as Integer

Why it doesn't work? I have a problem with Database. How boolean use as int?
Maybe I wrote bad code.Did I used boolean as Integer right? How to do insert in database.How to save the value boolean from check-box into the database?
My code of database in Android
public class DataBase extends SQLiteOpenHelper{
public static final String DATABASE_NAME = "DataOfSchedule.db";
public static final String TABLE_NAME = "DataOfSchedule_table";
public static final String COL_ID = "ID";
public static final String COL_NAME = "NAME";
public static final String COL_AGE = "AGE";
public static final String COL_GENDER_M = "GENDER_M";
public static final String COL_GENDER_F = "GENDER_F";
public static final String COL_WEIGHT = "WEIGHT";
public static final String COL_HEIGHT = "HEIGHT";
public static final String COL_TRAUMA = "TRAUMA";
public DataBase(Context context){
super(context, DATABASE_NAME, null,1);
}
#Override
public void onCreate(SQLiteDatabase db){
db.execSQL("CREATE TABLE" + TABLE_NAME +
COL_ID + " INTEGER PRIMARY KEY AUTOINCREMENT, " +
COL_NAME + " TEXT," +
COL_AGE + " INTEGER NOT NULL DEFAULT 0, " +
COL_GENDER_M + " INTEGER NOT NULL DEFAULT 0, " +
COL_GENDER_F + " INTEGER NOT NULL DEFAULT 0, " +
COL_TRAUMA + " INTEGER NOT NULL DEFAULT 0, " +
COL_WEIGHT + " INTEGER NOT NULL DEFAULT 0, " +
COL_HEIGHT + " INTEGER NOT NULL DEFAULT 0);");
}
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion){
db.execSQL("DROP TABLE IF EXISTS" + TABLE_NAME);
}
// public boolean insertData(String name, Integer age, Integer sex_male, Integer sex_female, Integer weight, Integer height, Integer trauma){
// SQLiteDatabase db = this.getWritableDatabase();
// ContentValues contentValues = new ContentValues();
public boolean insertData(String name, Integer age, Integer gender_m, Integer gender_f, Integer weight, Integer height, Integer trauma){
boolean success = false;
try{
SQLiteDatabase db = this.getWritableDatabase();
ContentValues contentValues = new ContentValues();
contentValues.put(COL_NAME, name);
contentValues.put(COL_AGE, age);
contentValues.put(COL_GENDER_M, gender_m);
contentValues.put(COL_GENDER_F, gender_f);
contentValues.put(COL_WEIGHT, weight);
contentValues.put(COL_HEIGHT, height);
contentValues.put(COL_TRAUMA, trauma);
long result = db.insert(TABLE_NAME,null,contentValues);
db.close();
if(result != -1) success = true;
}
catch(Exception ex){
}
return success;
}
public Cursor getALLData(){
SQLiteDatabase db = this.getWritableDatabase();
Cursor res = db.rawQuery("Select * from "+ TABLE_NAME,null);
return res;
}
}
My main_activity
public class InsertData extends AppCompatActivity {
DataBase myDb;
EditText txtName, txtAge , txtWeight, txtHeight;
CheckBox boxGender_m,boxGender_f,boxTrauma;
Button btnClick;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_insert_data);
myDb = new DataBase(this);
txtName = (EditText) findViewById(R.id.name);
txtAge = (EditText) findViewById(R.id.age);
boxGender_m = (CheckBox) findViewById(R.id.gender_m);
boxGender_f = (CheckBox) findViewById(R.id.gender_f);
boxTrauma = (CheckBox) findViewById(R.id.trauma);
txtWeight = (EditText) findViewById(R.id.weight);
txtHeight = (EditText) findViewById(R.id.height);
btnClick = (Button) findViewById(R.id.InsertBtn);
btnClick.setOnClickListener(new View.OnClickListener(){
#Override
public void onClick(View v){
ClickMe();
}
});
}
private void ClickMe(){
String name = txtName.getText().toString();
String age = txtAge.getText().toString();
String gender_m = boxGender_m.getText().toString();
String gender_f = boxGender_f.getText().toString();
String trauma = boxTrauma.getText().toString();
String weight = txtName.getText().toString();
String height = txtName.getText().toString();
int gender_int_m = Integer.parseInt(gender_m);
int gender_int_f = Integer.parseInt(gender_f);
int trauma_int = Integer.parseInt(trauma);
int weight_int = Integer.parseInt(weight);
int age_int = Integer.parseInt(age);
int height_int = Integer.parseInt(height);
Boolean result = myDb.insertData( name, age_int, gender_int_m, gender_int_f, weight_int, height_int, trauma_int);
if (result == true){
Toast.makeText(this, "Data Inserted Successfully",Toast.LENGTH_SHORT).show();
}else{
Toast.makeText(this, "Data Inserted Failed",Toast.LENGTH_SHORT).show();
}
Intent i = new Intent(this,ResultData.class);
startActivity(i);
}
}
What the matter? My XML
<ScrollView xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:padding="16dp"
tools:context="daniel_nikulshyn_and_andrew_rybka.myway.InsertData">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
android:layout_alignParentTop="true"
android:layout_alignParentLeft="true"
android:layout_alignParentStart="true">
<TextView
android:id="#+id/heading"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="#string/insert_heading"
android:layout_gravity="center"
android:textSize="16dp"
android:textColor="#021aee"/>
<EditText
android:id="#+id/name"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:hint="#string/insert_name"/>
<EditText
android:id="#+id/age"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:hint="#string/insert_age"
android:numeric="integer"/>
<EditText
android:id="#+id/weight"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:hint="#string/insert_weight"
android:numeric="integer"/>
<EditText
android:id="#+id/height"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:hint="#string/insert_height"
android:numeric="integer"/>
<TextView
android:padding="10dp"
android:text="#string/insert_gender"
android:layout_gravity="left"
android:layout_width="wrap_content"
android:layout_height="wrap_content" />
<CheckBox
android:id="#+id/gender_m"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="#string/male"/>
<CheckBox
android:id="#+id/gender_f"
android:text="#string/female"
android:layout_width="wrap_content"
android:layout_height="wrap_content" />
<TextView
android:padding="10dp"
android:text="#string/insert_trauma"
android:layout_gravity="left"
android:layout_width="wrap_content"
android:layout_height="wrap_content" />
<CheckBox
android:id="#+id/trauma"
android:text="#string/insert_trauma_subtitle"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginBottom="20dp"/>
<Button
android:id="#+id/InsertBtn"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:background="#color/colorPrimary"
android:text="#string/insert_button"
android:textColor="#f2fde4"
android:layout_gravity="center"/>
</LinearLayout>
</ScrollView>
What the matter? App is closing when I click btn "Okay" with id InsertBtn
In short you should use the isChecked method to get whether or not the checkBox is checked which will be a boolean.
I'm unsure exactly what getText() will return but it would very likely not be a string that could be parsed to an int, so when the parse is attempted you will get an exception. An analogy would be to say to you pay me $rumplestiltskin. How much would you give me?
As such your code could be along the lines of :-
private void ClickMe(){
String name = txtName.getText().toString();
String age = txtAge.getText().toString();
//String gender_m = boxGender_m.getText().toString(); //<<<< WRONG
//String gender_f = boxGender_f.getText().toString(); //<<<< WRONG
String trauma = boxTrauma.getText().toString();
String weight = txtName.getText().toString();
String height = txtName.getText().toString();
//<<<<<<<<<< ADDED CODE >>>>>>>>>>
int gender_int_m = 0;
if (boxGender_m.isChecked()) {
gender_int_m = 1;
}
int gender_int_f = 0;
if (boxGender_f.isChecked()) {
gender_int_f = 1;
}
//int gender_int_m = Integer.parseInt(gender_m); //<<<< REDUNDANT
//int gender_int_f = Integer.parseInt(gender_f); //<<<< REDUNDANT
int trauma_int = Integer.parseInt(trauma);
int weight_int = Integer.parseInt(weight);
int age_int = Integer.parseInt(age);
int height_int = Integer.parseInt(height);
Boolean result = myDb.insertData( name, age_int, gender_int_m, gender_int_f, weight_int, height_int, trauma_int);
if (result == true){
Toast.makeText(this, "Data Inserted Successfully",Toast.LENGTH_SHORT).show();
}else{
Toast.makeText(this, "Data Inserted Failed",Toast.LENGTH_SHORT).show();
}
Intent i = new Intent(this,ResultData.class);
startActivity(i);
}}
You are setting these:
int gender_int_m = Integer.parseInt(gender_m);
int gender_int_f = Integer.parseInt(gender_f);
int trauma_int = Integer.parseInt(trauma);
int weight_int = Integer.parseInt(weight);
int age_int = Integer.parseInt(age);
int height_int = Integer.parseInt(height);
...as the primitive int but you method insertData takes the Integer object as arguments:
public boolean insertData(String name, Integer age, Integer gender_m, Integer gender_f,
Integer weight, Integer height, Integer trauma){...
In Java, int and Integer are NOT the same thing. I suggest you
update insertData to take the primitive int as arguments:
public boolean insertData(String name, int age, int gender_m, int gender_f,
int weight, int height, int trauma){...

RecyclerView only adds one item in the List instead of adding all the entries

I am trying to build an app using where entries are stored in a sqlitedatabase and the mainactivity contains recyclerview which displays the entries from the database. The problem is that the recyclerview displays only the first entry that has been entered.
For example if the first entry is "A" and the second entry is "B", the recyclerview only displays "A" and not "B"
The Code for the recyclerview adapter is given below :
RecyclerView Adapter
public class PasswordRecyclerViewAdapter extends RecyclerView.Adapter<PasswordRecyclerViewAdapter.ViewHolder> {
private Context context;
private List<String> accounts;
private int position;
public PasswordRecyclerViewAdapter() {
}
public PasswordRecyclerViewAdapter(Context context, List<String> accounts) {
this.context = context;
this.accounts = accounts;
}
#Override
public ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View itemView = LayoutInflater.from(context).inflate(R.layout.linear_layout_simple_text, parent, false);
return new ViewHolder(itemView);
}
#Override
public void onBindViewHolder(ViewHolder holder, final int position) {
holder.title.setText(accounts.get(position));
holder.title.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
String data = accounts.get(position);
Intent intent=new Intent(context, DetailsActivity.class);
intent.putExtra("Site",data);
context.startActivity(intent);
}
});
}
#Override
public int getItemCount() {
return accounts.size();
}
class ViewHolder extends RecyclerView.ViewHolder {
TextView title;
public ViewHolder(View itemView) {
super(itemView);
title = (TextView) itemView.findViewById(R.id.textview_title);
}
}
}
MainActivity
public class MainActivity extends AppCompatActivity {
private static final String SHARED_PREFS_NAME="MyPrefs";
private RecyclerView recyclerView;
TextView emptyText;
PasswordRecyclerViewAdapter adapter;
List<String> collection;
List<String> myList=new ArrayList<String>();
PasswordDatabase passwordDatabase;
AdapterView.AdapterContextMenuInfo info;
String s;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
Fabric.with(this, new Crashlytics());
setContentView(R.layout.activity_main);
passwordDatabase = new PasswordDatabase(getApplicationContext());
myList = getArray();
collection = new ArrayList<>();
recyclerView = (RecyclerView) findViewById(R.id.listViewID);
emptyText = (TextView)findViewById(R.id.text2);
adapter = new PasswordRecyclerViewAdapter(this, myList);
recyclerView.setLayoutManager(new LinearLayoutManager(this));
recyclerView.setAdapter(adapter);
registerForContextMenu(recyclerView);
}
public List<String> getArray(){
/*SharedPreferences sp=this.getSharedPreferences(SHARED_PREFS_NAME,Activity.MODE_PRIVATE);
Set<String> set=sp.getStringSet("list",new HashSet<String>());
return new ArrayList<String>(set);*/
List accounts=passwordDatabase.getAcc();
return accounts;
}
}
In the function getArray() in MainActivity, the passwordDatabase.getAcc() returns the list of items stored in the sqlitedatabase. The code for the sqlitedatabase helper class is given below :
public final class PasswordDatabase extends SQLiteOpenHelper {
String data1;
public static final int DATABASE_VERSION = 1;
public static final String DATABASE_NAME = "UserCredentials.db";
public static final String TABLE_NAME = "Credentials";
public static final String COLUMN_PASSWORD = "Password";
public static final String COLUMN_ACCOUNT = "Account";
public static final String SQL_DELETE_ENTRIES =
"DROP TABLE IF EXISTS " + TABLE_NAME;
private static final String TABLE_CREATE = "CREATE TABLE "
+ TABLE_NAME + " (" + COLUMN_ACCOUNT + " TEXT, " + COLUMN_PASSWORD
+ " TEXT,UNIQUE("+ COLUMN_ACCOUNT + "));";
public PasswordDatabase(Context context) {
super(context, DATABASE_NAME, null, DATABASE_VERSION);
}
#Override
public void onCreate(SQLiteDatabase db) {
db.execSQL(TABLE_CREATE);
}
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
db.execSQL(SQL_DELETE_ENTRIES);
onCreate(db);
}
public void onDowngrade(SQLiteDatabase db, int oldVersion, int newVersion){
onUpgrade(db, oldVersion, newVersion);
}
public void addCredentials(Context context,String account, String password){
SQLiteDatabase db = this.getWritableDatabase();
long newRowId=0;
Boolean flag=false;
ContentValues values = new ContentValues();
values.put(COLUMN_ACCOUNT, account);
values.put(COLUMN_PASSWORD, password);
newRowId = db.insert(TABLE_NAME, null, values);
}
public void deleteRow(String account){
SQLiteDatabase db=this.getWritableDatabase();
String whereClause=COLUMN_ACCOUNT+"=?";
String[] whereArgs=new String[] {account};
db.delete(TABLE_NAME,whereClause,whereArgs);
}
public void modify(String account,String pass){
SQLiteDatabase db=this.getWritableDatabase();
String sql="UPDATE "+ TABLE_NAME +" SET " +COLUMN_PASSWORD +" = " +pass + " WHERE "+ COLUMN_ACCOUNT +" = " + account;
db.execSQL(sql);
}
public int modifyCredentials(String account,String newPass){
SQLiteDatabase db=this.getWritableDatabase();
ContentValues contentValues=new ContentValues();
contentValues.put(COLUMN_PASSWORD,newPass);
String whereClause=COLUMN_ACCOUNT + " =?";
String[] whereArgs=new String[]{account};
int update=db.update(TABLE_NAME,contentValues,whereClause,whereArgs);
return update;
}
public void deleteAllCredentials(){
SQLiteDatabase db = this.getWritableDatabase();
db.delete(TABLE_NAME, null, null);
}
public boolean checkdb(){
SQLiteDatabase db;
db=this.getWritableDatabase();
Cursor cursor=db.rawQuery("SELECT * FROM"+TABLE_NAME,null);
Boolean rowExists;
if (cursor.moveToFirst()){
rowExists=false;
}
else {
rowExists=true;
}
return rowExists;
}
public List<String> getAcc(){
SQLiteDatabase db=this.getReadableDatabase();;
List<String> collection=new ArrayList<>();
String acc=null;
Cursor c=null;
try{
String query="SELECT " + COLUMN_ACCOUNT + " FROM " + TABLE_NAME;
c=db.rawQuery(query,null);
if(c!=null){
if(c.moveToFirst()){
do{
acc=c.getString(c.getColumnIndex(COLUMN_ACCOUNT));
collection.add(acc);
}
while (c.moveToNext());
}
}
}
finally {
if(c!=null){
c.close();
}
if(db!=null){
db.close();
}
}
return collection;
}
public String getData(String data){
SQLiteDatabase db=this.getReadableDatabase();
Cursor cursor = db.query(TABLE_NAME, new String[] { COLUMN_ACCOUNT,COLUMN_PASSWORD
}, COLUMN_ACCOUNT + " = ?", new String[] { data },
null, null, null, null);
if (cursor!=null && cursor.moveToFirst()){
do{
data1=cursor.getString(1);
}while (cursor.moveToNext());
}
return data1;
}
}
activity_main.xml
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
tools:context="com.nitsilchar.hp.passwordStorage.activity.MainActivity">
<android.support.v7.widget.RecyclerView
android:id="#+id/listViewID"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:divider="#9fece2"
android:dividerHeight="0.5dp">
</android.support.v7.widget.RecyclerView>
<RelativeLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_centerHorizontal="true">
<TextView
android:id="#+id/text2"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:gravity="center"
android:textSize="18sp"
android:text="#string/main_xml_empty_text"/>
</RelativeLayout>
Can anyone help me for displaying all the entries stored in the database rather than only one entry
make sure your linear_layout_simple_text layout height to android:layout_height="wrap_content"
like below code
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="wrap_content">

How to insert datepicker and timepicker in sqlite database in android

How to store Date with day and Time with Minutes ,I want to insert selected Date and selected Time in Database.
public class FutureSms extends AppCompatActivity {
DbHelper db;
EditText name,mob,msg;
DatePicker dp;
TimePicker tp;
Button b1;
Button b2;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_future_sms);
db = new DbHelper(this);
name = (EditText) findViewById(R.id.name);
dp = (DatePicker) findViewById(R.id.date);
tp = (TimePicker) findViewById(R.id.time);
mob = (EditText) findViewById( R.id.mobnumber);
msg = (EditText) findViewById(R.id.msg);
b1 = (Button) findViewById(R.id.save);
b2 = (Button) findViewById(R.id.view);
AddData();
}
public void AddData()
{
b1.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
boolean isInserted = db.insertData(
name.getText().toString(),
dp.getDayOfMonth();
tp.getCurrentHour();
mob.getText().toString(),
msg.getText().toString());
if(isInserted == true)
Toast.makeText(FutureSms.this,"Data Inserted",Toast.LENGTH_LONG).show();
else
Toast.makeText(FutureSms.this,"Data not Inserted",Toast.LENGTH_LONG).show();
}
});
}}
This is xml for layout of view.
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Select a time to send Message"
android:textColor="#3B5998"
android:textSize="20dp"
android:textStyle="bold"
android:layout_gravity="center_horizontal" />
<ScrollView
android:layout_width="match_parent"
android:layout_height="match_parent">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="vertical"
android:layout_marginTop="30dp">
<DatePicker
android:id="#+id/pickerdate"
android:layout_width="wrap_content"
android:layout_height="wrap_content" />
<TimePicker
android:id="#+id/pickertime"
android:layout_width="wrap_content"
android:layout_height="wrap_content"/>
<Button
android:id="#+id/setalarm"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="Set Alarm"/>
<TextView
android:id="#+id/info"
android:layout_width="match_parent"
android:layout_height="wrap_content"/>
</LinearLayout>
</ScrollView>
DbHealper(this code contain to store database for insertion , deletion ,updation and view )
public class DbHelper extends SQLiteOpenHelper {
public static final String DATABASE_NAME = "Alert.db";
public static final String TABLE_NAME = "MessageAlert";
public static final String COL = "ID" ;
public static final String COL_1 = "NAME";
public static final String COL_2 = "DATE";
public static final String COL_3 = "TIME";
public static final String COL_4= "MOBILE";
public static final String COL_5 = "MESSAGE";
public DbHelper(Context context) {
super(context, DATABASE_NAME , null, 1);
}
#Override
public void onCreate(SQLiteDatabase sqLiteDatabase) {
sqLiteDatabase.execSQL("create table" + TABLE_NAME + "( ID INTEGER PRIMERY KEY AUTOINCREMENT ,NAME TEXT,DATE TEXT,TIME TEXT,MOBILE TEXT,MESSAGE TEXT } " );
}
#Override
public void onUpgrade(SQLiteDatabase sqLiteDatabase, int i, int i1) {
sqLiteDatabase.execSQL("IF DROP TABLE EXISTS" + TABLE_NAME);
onCreate(sqLiteDatabase);
}
public boolean insertData(String name,String date,String time,String mobile,String message) {
SQLiteDatabase db = this.getWritableDatabase();
ContentValues contentValues = new ContentValues();
contentValues.put(COL_1,name);
contentValues.put(COL_2,date);
contentValues.put(COL_3,time);
contentValues.put(COL_4,mobile);
contentValues.put(COL_5,message);
long result = db.insert(TABLE_NAME,null ,contentValues);
if(result == -1)
return false;
else
return true;
}
public Integer deleteData (String id) {
SQLiteDatabase db = this.getWritableDatabase();
return db.delete(TABLE_NAME, "ID = ?",new String[] {id});
}
public Cursor getAllData() {
SQLiteDatabase db = this.getWritableDatabase();
Cursor res = db.rawQuery("select * from "+TABLE_NAME,null);
return res;
}
public boolean updateData(String id,String name,String date,String time,String mobile,String message) {
SQLiteDatabase db = this.getWritableDatabase();
ContentValues contentValues = new ContentValues();
contentValues.put(COL,id);
contentValues.put(COL_1,name);
contentValues.put(COL_2,date);
contentValues.put(COL_3,time);
contentValues.put(COL_4,mobile);
contentValues.put(COL_5,message);
db.update(TABLE_NAME, contentValues, "ID = ?",new String[] { id });
return true;
}}
Date in Java is just amount of milliseconds since January 1, 1970 00:00:00.000 GMT. So you can convert it back and forth to long variable.
Date.getTime() to get long value of date (It's UNIX TimeStamp in milliseconds). And use new Date(System.currentTimeMillis()) to create your Date object back. So in the end you simply need to store one long value in your database.

Can somebody help me solve the database?

Hello everybody i m building an android application which has timepicker. what i want is that i want to update the database when user clicks the save button twice. Please guide me how to do that. Now my application crashes because no updation of database takes place.
TimeTable.java
public class Monday extends FragmentActivity implements TimePickerFragment.TimePickerDialogListener {
EditText et1, et2, et3;
TextView tvm;
LinearLayout llm;
int fhour, fmin, thour, tmin, j;
private int cnt = 0;
View vi[] = new View[100];
TimeTableDbHelper db;
String txt,fmeridien,tmeridien,ftime,ttime;
private static final int START_TIME_PICKER_ID = 1;
private static final int END_TIME_PICKER_ID = 2;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
Intent intent = getIntent();
setContentView(R.layout.activity_monday);
tvm = (TextView) findViewById(R.id.tvm);
llm = (LinearLayout) findViewById(R.id.llm);
db = new TimeTableDbHelper(this);
cnt = db.check("timetableM");
if (cnt > 0) {
int i;
for (i = 0; i < cnt; i++) {
LinearLayout mn = (LinearLayout) findViewById(R.id.llm);
View view = getLayoutInflater().inflate(R.layout.activity_timepicker, mn, false);
vi[i] = view;
mn.addView(view);
et1 = (EditText) vi[i].findViewById(R.id.txtTime);
et1.setText(db.rd1(i,1));
//Log.i("Monday", "Database read" + db.read(2) + db.read(3));
et2 = (EditText) vi[i].findViewById(R.id.txtTime2);
et2.setText(db.rd1(i,2));
//Log.i("Monday", "Database read" + db.read(4) + db.read(5));
et3 = (EditText) vi[i].findViewById(R.id.txtSet);
et3.setText(db.rd1(i,3));
}
j = i;
} else {
j = 0;
}
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.menu_monday, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
//noinspection SimplifiableIfStatement
return super.onOptionsItemSelected(item);
}
public void setTime(View v) {
LinearLayout main = (LinearLayout) findViewById(R.id.llm);
View view = getLayoutInflater().inflate(R.layout.activity_timepicker, main, false);
view.setTag(j);
main.addView(view);
vi[j] = view;
}
public void setTime2(View v) {
DialogFragment newFragment = TimePickerFragment.newInstance(START_TIME_PICKER_ID);
newFragment.show(getFragmentManager(), "timePicker");
}
public void setTime3(View v) {
DialogFragment newFragment = TimePickerFragment.newInstance(END_TIME_PICKER_ID);
newFragment.show(getFragmentManager(), "timePicker");
}
#Override
public void onTimeSet(int id, TimePicker view, int hourOfDay, int minute) {
Log.i("TimePicker", "Time picker set from id " + id + "!");
if (id == START_TIME_PICKER_ID) {
et1 = (EditText) vi[j].findViewById(R.id.txtTime);
fmin = minute;
if(hourOfDay <= 12) {
fhour = hourOfDay;
fmeridien = "AM";
} else {
fhour = hourOfDay-12;
fmeridien = "PM";
}
ftime =fhour + ":" + fmin + fmeridien;
et1.setText(ftime);
} else {
et2 = (EditText) vi[j].findViewById(R.id.txtTime2);
tmin = minute;
if(hourOfDay < 12) {
thour = hourOfDay;
tmeridien = "AM";
} else {
thour = hourOfDay-12;
tmeridien = "PM";
}
ttime = thour + ":" + tmin +tmeridien;
et2.setText(ttime);
}
}
public void Save(View v)
{
int position = (int) v.getTag();
if(position<j);
else {
et3 = (EditText) vi[j].findViewById(R.id.txtSet);
txt = et3.getText().toString();
Log.i("Position", "Value is " + position);
db.write1(j, ftime, ttime, txt);
Toast.makeText(this, "Successfully saved", Toast.LENGTH_LONG).show();
AlarmManager alarmManager = (AlarmManager) getSystemService(ALARM_SERVICE);
Calendar c = Calendar.getInstance();
c.setFirstDayOfWeek(Calendar.MONDAY);
int day = c.get(Calendar.DAY_OF_WEEK);
int value;
if(fmeridien=="AM") value=0;
else value=1;
c.set(Calendar.DAY_OF_WEEK,day);
c.set(Calendar.AM_PM, value);
c.set(Calendar.HOUR, fhour);
c.set(Calendar.MINUTE, fmin);
c.set(Calendar.SECOND,0);
Intent i = new Intent("com.example.annu.sheduler.DisplayNotification");
//---assign an ID of 1---
i.putExtra("NotifID", j);
i.putExtra("text",txt);
PendingIntent displayIntent = PendingIntent.getActivity(
getBaseContext(), j, i, 0);
j++;
//---sets the alarm to trigger---
alarmManager.set(AlarmManager.RTC_WAKEUP,
c.getTimeInMillis(), displayIntent);}
}
}
activity_monday.xml
<LinearLayout android:id="#+id/llm"
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
tools:context="com.example.annu.sheduler.Monday"
android:background="#ffffa751"
android:label="Monday">
<TextView
android:id="#+id/tvm"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:onClick="setTime"
android:paddingLeft="16dp"
android:paddingRight="16dp"
android:paddingTop="16dp"
android:text="Create a schedule"
android:textStyle="bold"
android:textSize="24sp"/>
</LinearLayout>
activity_timepicker.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="horizontal"
android:weightSum="1">
<EditText
android:id="#+id/txtTime"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_weight=".30"
android:hint="From"
android:onClick="setTime2"/>
<EditText
android:id="#+id/txtTime2"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_weight=".30"
android:hint="To"
android:onClick="setTime3"/>
<EditText
android:id="#+id/txtSet"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_weight=".40"
android:hint="Description!!!"/>
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Save"
android:onClick="Save"
android:minHeight="0dp"
android:minWidth="20dp"/>
</LinearLayout>
TimeTableDbHelper.java
public class TimeTableDbHelper extends SQLiteOpenHelper {
public static final String TABLE_NAMEM = "timetableM";
public static final String COLUMN_NO1 = "c_no1";
public static final String COLUMN_FROM_TIME1 = "FTIME1";
public static final String COLUMN_TO_TIME1 = "TTIME1";
public static final String COLUMN_DESC1 = "Description1";
private static final int DATABASE_VERSION = 1;
static final String DATABASE_NAME = "TimeTable.db";
public TimeTableDbHelper(Context context) {
super(context, DATABASE_NAME, null, DATABASE_VERSION);
}
#Override
public void onCreate(SQLiteDatabase sqLiteDatabase) {
final String SQL_CREATE_TIME_TABLE1 = "CREATE TABLE " + TABLE_NAMEM + " (" +
COLUMN_NO1 + " INTEGER PRIMARY KEY, " +
COLUMN_FROM_TIME1 + " STRING NOT NULL," +
COLUMN_TO_TIME1 + " STRING NOT NULL," +
COLUMN_DESC1 + " TEXT NOT NULL" +
" );";
sqLiteDatabase.execSQL(SQL_CREATE_TIME_TABLE1);
}
#Override
public void onUpgrade(SQLiteDatabase sqLiteDatabase, int oldVersion, int newVersion) {
sqLiteDatabase.execSQL("DROP TABLE IF EXISTS " + TABLE_NAMEM);
onCreate(sqLiteDatabase);
}
public void write1(int column_no, String ftime, String ttime, String desc) {
SQLiteDatabase db = this.getWritableDatabase();
ContentValues values = new ContentValues();
values.put(COLUMN_NO1, column_no);
values.put(COLUMN_FROM_TIME1, ftime);
values.put(COLUMN_TO_TIME1, ttime);
values.put(COLUMN_DESC1, desc);
Boolean res = CheckIsDataAlreadyInDBorNot(TABLE_NAMEM, COLUMN_NO1, column_no);
if (res == false) db.insert(TABLE_NAMEM, null, values);
else db.update(TABLE_NAMEM, values, null, null);
db.close();
}
public int check(String tname) {
SQLiteDatabase db = this.getWritableDatabase();
String count = "SELECT count(*) FROM " + tname;
Cursor mcursor = db.rawQuery(count, null);
mcursor.moveToFirst();
int icount = mcursor.getInt(0);
return icount;
}
public String rd1(int c_no, int col) {
String selectQuery = "SELECT * FROM " + TABLE_NAMEM + " WHERE " + COLUMN_NO1 + " = " + c_no;
SQLiteDatabase db = this.getReadableDatabase();
Cursor cursor = db.rawQuery(selectQuery, null);
String data = "";
if (cursor.moveToFirst()) {
// get the data into array,or class variable
do {
data = cursor.getString(col);
//Log.i("TimeTableDbHelper", "Value read " + cursor.getString(6));
} while (cursor.moveToNext());
}
db.close();
return data;
}
public boolean CheckIsDataAlreadyInDBorNot(String TableName,
String dbfield, int fieldValue) {
SQLiteDatabase db = this.getReadableDatabase();
String Query = "Select * from " + TableName + " where " + dbfield + " = " + fieldValue;
Cursor cursor = db.rawQuery(Query, null);
if (cursor.getCount() <= 0) {
cursor.close();
return false;
}
cursor.close();
return true;
}
}
As stated here
https://developer.android.com/reference/android/database/sqlite/SQLiteDatabase.html#update(java.lang.String,%20android.content.ContentValues,%20java.lang.String,%20java.lang.String[]):
Returns:
the number of rows affected
So you can do just:
if (db.update(TABLE_NAMEM, values, null, null) == 0)
db.insert(TABLE_NAMEM, null, values);
db.close();

Categories