How to insert datepicker and timepicker in sqlite database in android - java

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.

Related

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">

Updating a certain value and saving it in offline database

I'm developing a tiny app that has a value in a textview set to 150,000 by default. Each month I reset the value back to the default. Every time I spend some of that amount, I open my app and enter the amount I spent and the details of what it was spent on.
What I did was create an offline database to store all the times I spent some of that amount, along with it's id and details. Each time I press the "spend" button, the total amount is reduced by the amount I have entered in the EditText.
I haven't implemented how I'll update the total amount yet, I believe I have to use something called sharedpreference number.
This is the main activity:
public class MainActivity extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Button spendMoney = (Button)this.findViewById(R.id.spendMoney);
Button test = (Button)this.findViewById(R.id.test);
TextView totalTxt = (TextView) this.findViewById(R.id.totalTxt);
final EditText spendAmount = (EditText)this.findViewById(R.id.spendAmount);
// int totalAmount = Integer.parseInt(totalTxt.getText().toString());
final Paid_DB db = new Paid_DB(this);
spendMoney.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
db.addPayment(new Payment(0, (Integer.parseInt(spendAmount.getText().toString())), "Test Details"));
}
});
//totalAmount = totalAmount - Integer.parseInt(spendAmount.getText().toString());
// totalTxt.setText(totalAmount);
test.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent i = new Intent(null, DetailsActivity.class);
startActivity(i);
}
});
XML file:
<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="match_parent"
tools:context="com.example.user.paid.MainActivity">
<TextView
android:id="#+id/textView3"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentLeft="true"
android:layout_alignParentStart="true"
android:layout_alignParentTop="true"
android:layout_marginLeft="13dp"
android:layout_marginStart="13dp"
android:layout_marginTop="53dp"
android:fontFamily="sans-serif"
android:text="Total:"
android:textSize="30sp"
tools:layout_editor_absoluteX="25dp"
tools:layout_editor_absoluteY="36dp" />
<EditText
android:id="#+id/spendAmount"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:ems="10"
android:inputType="number"
tools:layout_editor_absoluteX="72dp"
tools:layout_editor_absoluteY="143dp"
android:layout_marginBottom="38dp"
android:layout_above="#+id/spendMoney"
android:layout_centerHorizontal="true" />
<Button
android:id="#+id/spendMoney"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Spend Money"
tools:layout_editor_absoluteX="115dp"
tools:layout_editor_absoluteY="215dp"
android:layout_centerVertical="true"
android:layout_centerHorizontal="true" />
<TextView
android:id="#+id/totalTxt"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignBaseline="#+id/textView3"
android:layout_alignBottom="#+id/textView3"
android:layout_alignEnd="#+id/spendMoney"
android:layout_alignRight="#+id/spendMoney"
android:fontFamily="sans-serif"
android:text="150,000"
android:textSize="30sp"
tools:layout_editor_absoluteX="25dp"
tools:layout_editor_absoluteY="36dp" />
<Button
android:id="#+id/test"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Test"
tools:layout_editor_absoluteX="134dp"
tools:layout_editor_absoluteY="358dp"
android:layout_marginBottom="90dp"
android:layout_alignParentBottom="true"
android:layout_alignLeft="#+id/spendMoney"
android:layout_alignStart="#+id/spendMoney" />
This is the object I enter into the offline database, containing the id, the amount spent, and details of the payment:
public class Payment {
private int id;
private int amount;
private String details;
public Payment(){}
public Payment(int id, int amount, String details) {
this.id = id;
this.amount = amount;
this.details = details;
}
public Payment(int id, int amount) {
this.id = id;
this.amount = amount;
}
public Payment(int amount, String details) {
this.amount = amount;
this.details = details;
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public int getAmount() {
return amount;
}
public void setAmount(int amount) {
this.amount = amount;
}
public String getDetails() {
return details;
}
public void setDetails(String details) {
this.details = details;
} }
This is the offline database:
ublic class Paid_DB extends SQLiteOpenHelper {
// All Static variables
// Database Version
private static final int DATABASE_VERSION = 1;
// Database Name
private static final String DATABASE_NAME = "Payments_DB";
// Contacts table name
private static final String PAYMENT_TABLE = "PaymentTable";
// Contacts Table Columns names
private static final String PAY_ID = "id";
private static final String PAY_AMOUNT = "amount";
private static final String PAY_DETAILS = "details";
Paid_DB(Context context) {
super(context, DATABASE_NAME, null, DATABASE_VERSION);
}
#Override
public void onCreate(SQLiteDatabase db) {
String CREATE_CONTACTS_TABLE = "CREATE TABLE " + PAYMENT_TABLE + "("
+ PAY_ID + " INTEGER PRIMARY KEY," + PAY_AMOUNT + " INTEGER,"
+ PAY_DETAILS + " TEXT" + ")";
db.execSQL(CREATE_CONTACTS_TABLE);
}
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
db.execSQL("DROP TABLE IF EXISTS " + PAYMENT_TABLE);
onCreate(db);
}
public void addPayment(Payment payment){
SQLiteDatabase db = this.getWritableDatabase();
ContentValues values = new ContentValues();
values.put(PAY_AMOUNT, payment.getAmount());
values.put(PAY_DETAILS, payment.getDetails()); // Contact Phone Number
// Inserting Row
db.insert(PAYMENT_TABLE, null, values);
db.close();
}
void addListItem(ArrayList<String> listItem) {
SQLiteDatabase db = this.getWritableDatabase();
ContentValues values = new ContentValues();
for (int i = 0; i < listItem.size(); i++) {
Log.e("vlaue inserting==", "" + listItem.get(i));
values.put(PAY_AMOUNT, listItem.get(i));
db.insert(PAYMENT_TABLE, null, values);
}
db.close(); // Closing database connection
}
Cursor getListItem() {
String selectQuery = "SELECT * FROM " + PAYMENT_TABLE;
SQLiteDatabase db = this.getWritableDatabase();
Cursor cursor = db.rawQuery(selectQuery, null);
return cursor;
}}
And finally, this is the details activity, it contains a list view that stores and displays all the payments that have been made:
public class DetailsActivity extends AppCompatActivity {
ArrayList<String> detailsListArrayList;
private ListView lv;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_details);
lv = (ListView) findViewById(R.id.listView);
detailsListArrayList = new ArrayList<>();
detailsListArrayList.add("Item1");
detailsListArrayList.add("Item2");
detailsListArrayList.add("Item3");
detailsListArrayList.add("Item4");
detailsListArrayList.add("Item5");
Paid_DB db = new Paid_DB(this);
db.addListItem(detailsListArrayList);
Cursor cursor = db.getListItem();
Log.e("count", " " + cursor.getCount());
if (cursor != null) {
cursor.moveToNext();
do {
Log.e("value==", "" + cursor.getString(1));
} while (cursor.moveToNext());
}
ArrayAdapter<String> arrayAdapter = new ArrayAdapter<String>(
this,
android.R.layout.simple_list_item_1,
detailsListArrayList );
lv.setAdapter(arrayAdapter);
}
}
XML file:
<android.support.constraint.ConstraintLayout 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"
tools:context="com.example.user.paid.DetailsActivity">
<ListView
android:id="#+id/listView"
android:layout_width="368dp"
android:layout_height="495dp"
tools:layout_editor_absoluteX="8dp"
tools:layout_editor_absoluteY="8dp" />
Every time I click on the "test" button, the app crashes. And every time I try to add a new entry using the "spend" button, the app also crashes. What did I do wrong?
What I can tell from here (without the error log) is:
1) your app crashes when pressing the test-button because you are starting an activity there without passing a contextobject. Try this:
public void onClick(View v) {
Intent i = new Intent(getApplicationContext(), DetailsActivity.class);
startActivity(i);
}
2) The spend button tries to add a new payment entry to your database. But in your database schema , you declare the PAY_ID as a primary key. Later in your addPayment() you are just passing the PAY_AMOUNT and PAY_DETAILS, so you are missing the PAY_ID which seems to lead to a crash.
EDIT: something like this should return all the payments as an ArrayList (may Contain bugs, just wrote it in this editor).
public ArrayList<Payment> getAllPayments() {
ArrayList<Payment> result = new ArrayList<>();
Cursor c = db.query("PAYMENTS",new String[]{"PAY_ID","PAY_AMOUNT","PAY_DETAIL"},null,null,null,null,null); ;
c.moveToFirst();
while(! c.isAfterLast())
{
int s1=c.getInt(0);
int s2=c.getInt(1);
String s3=c.getString(2);
results.add(new Payment(s1,s2,s3));
c.moveToNext();
}
return results;
}
To update your ListView, you should have a closer look a this link, that explains how to work with ListViews and a custom ListView adapter Custom Adapter for List View

How to refresh ListView on data delete automaticaly

I want list view automatically update after deletion. I use adapter.notifyDataSetChanged() but it doesn't work for me
Here is my code
DatabaseHelper
public class DatabaseHelper extends SQLiteOpenHelper {
private static final String TAG = "DatabaseHelper";
private static final String TABLE_NAME = "people_table";
private static final String COL1 = "ID";
private static final String COL2 = "name";
public DatabaseHelper(Context context) {
super(context, TABLE_NAME, null, 1);
}
#Override
public void onCreate(SQLiteDatabase db) {
String createTable = "CREATE TABLE " + TABLE_NAME + " (ID INTEGER PRIMARY KEY AUTOINCREMENT, " +
COL2 +" TEXT)";
db.execSQL(createTable);
}
#Override
public void onUpgrade(SQLiteDatabase db, int i, int i1) {
db.execSQL("DROP IF TABLE EXISTS " + TABLE_NAME);
onCreate(db);
}
public boolean addData(String item) {
SQLiteDatabase db = this.getWritableDatabase();
ContentValues contentValues = new ContentValues();
contentValues.put(COL2, item);
Log.d(TAG, "addData: Adding " + item + " to " + TABLE_NAME);
long result = db.insert(TABLE_NAME, null, contentValues);
//if date as inserted incorrectly it will return -1
if (result == -1) {
return false;
} else {
return true;
}
}
/**
* Returns all the data from database
* #return
*/
public Cursor getData(){
SQLiteDatabase db = this.getWritableDatabase();
String query = "SELECT * FROM " + TABLE_NAME;
Cursor data = db.rawQuery(query, null);
return data;
}
public Cursor getItemID(String name){
SQLiteDatabase db = this.getWritableDatabase();
String query = "SELECT " + COL1 + " FROM " + TABLE_NAME +
" WHERE " + COL2 + " = '" + name + "'";
Cursor data = db.rawQuery(query, null);
return data;
}
/**
* Delete from database
*/
public void deleteName(int id, String name){
SQLiteDatabase db = this.getWritableDatabase();
String query = "DELETE FROM " + TABLE_NAME + " WHERE "
+ COL1 + " = '" + id + "'" +
" AND " + COL2 + " = '" + name + "'";
Log.d(TAG, "deleteName: query: " + query);
Log.d(TAG, "deleteName: Deleting " + name + " from database.");
db.execSQL(query);
}
}
EditData
public class EditDataActivity extends AppCompatActivity {
private static final String TAG = "EditDataActivity";
private Button btnDelete;
DatabaseHelper mDatabaseHelper;
private String selectedName;
private int selectedID;
#Override
public void onCreate( Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.edit_data_layout);
ActionBar actionBar=getSupportActionBar();
actionBar.hide();
DisplayMetrics dm = new DisplayMetrics();
getWindowManager().getDefaultDisplay().getMetrics(dm);
int width = dm.widthPixels;
int height = dm.heightPixels;
getWindow().setLayout((int)(width*.4),(int)(height*.2));
btnDelete = (Button) findViewById(R.id.btnDelete);
mDatabaseHelper = new DatabaseHelper(this);
//get the intent extra from the ListDataActivity
Intent receivedIntent = getIntent();
//now get the itemID we passed as an extra
selectedID = receivedIntent.getIntExtra("id",-1); //NOTE: -1 is just the default value
//now get the name we passed as an extra
selectedName = receivedIntent.getStringExtra("name");
btnDelete.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
mDatabaseHelper.deleteName(selectedID,selectedName);
toastMessage("removed from database");
adapter.notifyDataSetChanged();
}
});
}
/**
* customizable toast
*/
private void toastMessage(String message){
Toast.makeText(this,message, Toast.LENGTH_SHORT).show();
}
}
ListData
public class ListDataActivity extends AppCompatActivity {
private static final String TAG = "ListDataActivity";
static ArrayAdapter adapter;
DatabaseHelper mDatabaseHelper;
private ListView mListView;
#Override
protected void onCreate(#Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.list_layout);
mListView = (ListView) findViewById(R.id.listView);
mDatabaseHelper = new DatabaseHelper(this);
populateListView();
}
public void populateListView() {
Log.d(TAG, "populateListView: Displaying data in the ListView.");
//get the data and append to a list
Cursor data = mDatabaseHelper.getData();
ArrayList<String> listData = new ArrayList<>();
while(data.moveToNext()){
//get the value from the database in column 1
//then add it to the ArrayList
listData.add(data.getString(1));
}
//create the list adapter and set the adapter
adapter = new ArrayAdapter<>(this, android.R.layout.simple_list_item_1, listData);
mListView.setAdapter(adapter);
//set an onItemClickListener to the ListView
mListView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
String name = adapterView.getItemAtPosition(i).toString();
Log.d(TAG, "onItemClick: You Clicked on " + name);
Cursor data = mDatabaseHelper.getItemID(name); //get the id associated with that name
int itemID = -1;
while(data.moveToNext()){
itemID = data.getInt(0);
}
if(itemID > -1){
Log.d(TAG, "onItemClick: The ID is: " + itemID);
Intent editScreenIntent = new Intent(ListDataActivity.this, EditDataActivity.class);
editScreenIntent.putExtra("id",itemID);
editScreenIntent.putExtra("name",name);
startActivity(editScreenIntent);
}
else{
toastMessage("No ID associated with that name");
}
}
});
}
private void toastMessage(String message){
Toast.makeText(this,message, Toast.LENGTH_SHORT).show();
}
}
MainActivity
public class MainActivity extends AppCompatActivity {
DatabaseHelper mDatabaseHelper;
private Button btnAdd, btnViewData;
EditText editField;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
btnAdd = (Button) findViewById(R.id.btnAdd);
btnViewData = (Button) findViewById(R.id.btnView);
mDatabaseHelper = new DatabaseHelper(this);
editField = (EditText) findViewById(R.id.editText);
btnAdd.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (editField.getText().toString().length() == 0) {
Toast.makeText(MainActivity.this, "Please Enter!", Toast.LENGTH_SHORT).show();
return;
}
String editText = editField.getText().toString();
AddData(editText);
}
});
btnViewData.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent(MainActivity.this, ListDataActivity.class);
startActivity(intent);
}
});
}
public void AddData(String newEntry) {
boolean insertData = mDatabaseHelper.addData(newEntry);
if (insertData) {
toastMessage("Data Successfully Inserted!");
} else {
toastMessage("Something went wrong");
}
}
private void toastMessage(String message) {
Toast.makeText(this, message, Toast.LENGTH_SHORT).show();
}
}
And Layout are
activity_main
<RelativeLayout 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.tabian.saveanddisplaysql.MainActivity">
<EditText
android:id="#+id/editText"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:gravity="center"
android:hint="Enter any Thing"
android:layout_marginBottom="47dp"
android:layout_above="#+id/linearLayout"
android:layout_alignParentStart="true" />
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_alignParentBottom="true"
android:layout_alignParentStart="true"
android:layout_marginBottom="197dp"
android:orientation="horizontal"
android:id="#+id/linearLayout">
<Button
android:id="#+id/btnAdd"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginLeft="70dp"
android:text="Add" />
<Button
android:id="#+id/btnView"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginLeft="20dp"
android:layout_toRightOf="#+id/btnAdd"
android:text="View Data" />
</LinearLayout>
</RelativeLayout>
edit_data_layout
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_alignParentTop="true"
android:orientation="vertical">
<Button
android:id="#+id/btnDelete"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerHorizontal="true"
android:layout_centerVertical="true"
android:text="DELETE" />
</RelativeLayout>
list_layout
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="match_parent"
android:layout_height="match_parent">
<ListView
android:layout_width="match_parent"
android:layout_height="match_parent"
android:id="#+id/listView"/>
</LinearLayout>
After deletion instead of adapter.notifyDataSetChanged(); you can use the following code. It works fine for me:
adapter.remove(selectedName);

Display SQLite data in Android tablelayout

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.

Categories