I cannot use boolean as Integer - java

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){...

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

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

When I scroll my ListView my application crashes

I need a serious help, my app is working fine until now. I am doing a project using sqLite database and displaying the search result. I used TextView to display search result and it worked fine but when i use ListView to display it crashes when i scroll it. Need help.......
My code in
SearchCustomer.java
public class SearchCustomer extends Activity {
Button searchCustomer;
String errormsg = "No Result Found";
String[] nameCus;
ListView Cusinfo;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_search_customer);
searchCustomer = (Button) findViewById(R.id.Bsearch);
Cusinfo = (ListView) findViewById(R.id.cusinfoList);
final AutoCompleteTextView CustomerName = (AutoCompleteTextView) findViewById(R.id.CustomerName);
final Customer name = new Customer(this);
searchCustomer.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
String CustomerNam = CustomerName.getText().toString().trim();
name.open();
nameCus = name.getDetails(CustomerNam);
name.close();
ListAdapter cus = new ArrayAdapter<>(SearchCustomer.this, android.R.layout.simple_list_item_1, nameCus);
Cusinfo.setAdapter(cus);
Cusinfo.setOnItemClickListener(
new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
String det = String.valueOf(parent.getItemAtPosition(position));
Toast.makeText(SearchCustomer.this, det, Toast.LENGTH_LONG).show();
}
});
}else{
Toast.makeText(SearchCustomer.this, errormsg, Toast.LENGTH_LONG).show();
}
});
}
}
My code in Customer.java
public class Customer {
public static final String KEY_ROWID = "_id";
public static final String KEY_NAME = "cus_name";
public static final String KEY_PHONE = "cus_phone";
public static final String KEY_ADDRESS = "cus_address";
public static final String KEY_DATE = "cus_date";
public static final String KEY_DETAILS = "cus_details";
public static final String KEY_AMOUNT = "cus_amount";
public static final String KEY_SRI = "cus_sri";
private static final String DATABASE_NAME = "Customerdb";
private static final String DATABASE_TABLE = "customerTable";
private static final int DATABASE_VERSION = 1;
private final Context ourContext;
private DbHelper ourHelper;
private SQLiteDatabase ourDatabase;
public String[] getDetails(String customerNam) {
String[] columns = new String[]{KEY_ROWID, KEY_NAME, KEY_PHONE, KEY_ADDRESS, KEY_DATE, KEY_DETAILS, KEY_AMOUNT, KEY_SRI};
Cursor c = ourDatabase.query(DATABASE_TABLE, columns, KEY_PHONE + "=?",
new String[]{customerNam}, null, null, null, null);
String[] result = new String[100];
int i = 0;
int iRow = c.getColumnIndex(KEY_ROWID);
int iName = c.getColumnIndex(KEY_NAME);
int iPhone = c.getColumnIndex(KEY_PHONE);
int iAddress = c.getColumnIndex(KEY_ADDRESS);
int iDate = c.getColumnIndex(KEY_DATE);
int iDetails = c.getColumnIndex(KEY_DETAILS);
int iAmount = c.getColumnIndex(KEY_AMOUNT);
int iSri = c.getColumnIndex(KEY_SRI);
for (c.moveToFirst(); !c.isAfterLast(); c.moveToNext()) {
result[i] = c.getString(iRow) + "\n" + "Name: " + c.getString(iName) + "\n" +
"PhoneNo.: " + c.getString(iPhone) + "\n" + "Address: " + c.getString(iAddress) + "\n" +
"Date: " + c.getString(iDate) + "\n" + "Details: " + c.getString(iDetails) + "\n" +
"Amount: Rs." + c.getString(iAmount) + "\n" + "Type : " + c.getString(iSri) + "\n" + "____________________________________" + "\n";
i++;
}
return result;
}
}
My code in activity_search_customer.xml
<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="match_parent"
android:layout_margin="8dp"
android:orientation="vertical"
tools:context="com.innovation.fae.camerawork.SearchCustomer">
<TextView
android:id="#+id/textView"
style="#style/AlertDialog.AppCompat"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:paddingBottom="5dp"
android:text="#string/enter_the_customer_name"
android:textSize="18dp" />
<AutoCompleteTextView
android:id="#+id/CustomerName"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:hint="Customer Phone No."
android:inputType="phone"
android:paddingTop="20dp" />
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginTop="15dp">
<Button
android:id="#+id/Bsearch"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_weight="1"
android:text="#string/search"
android:textSize="18sp"
android:textStyle="italic" />
</LinearLayout>
<ListView
android:id="#+id/cusinfoList"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:background="#c3deff"
android:textColor="#001e71"
android:textSize="20sp" />
</LinearLayout>
My **Logcat**
07-15 22:38:19.825 29729-29729/com.innovation.fae.camerawork E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.innovation.fae.camerawork, PID: 29729
java.lang.NullPointerException: Attempt to invoke virtual method 'java.lang.String java.lang.Object.toString()' on a null object reference
at android.widget.ArrayAdapter.createViewFromResource(ArrayAdapter.java:394)
at android.widget.ArrayAdapter.getView(ArrayAdapter.java:362)
at android.widget.AbsListView.obtainView(AbsListView.java:2349)
at android.widget.ListView.makeAndAddView(ListView.java:1864)
at android.widget.ListView.fillDown(ListView.java:698)
at android.widget.ListView.fillGap(ListView.java:662)
at android.widget.AbsListView.trackMotionScroll(AbsListView.java:5007)
at android.widget.AbsListView.scrollIfNeeded(AbsListView.java:3424)
at android.widget.AbsListView.startScrollIfNeeded(AbsListView.java:3352)
at android.widget.AbsListView.onTouchMove(AbsListView.java:3780)
at android.widget.AbsListView.onTouchEvent(AbsListView.java:3638)
at android.view.View.dispatchTouchEvent(View.java:8480)
at android.view.ViewGroup.dispatchTransformedTouchEvent(ViewGroup.java:2400)
at android.view.ViewGroup.dispatchTouchEvent(ViewGroup.java:2093)
at android.view.ViewGroup.dispatchTransformedTouchEvent(ViewGroup.java:2406)
at android.view.ViewGroup.dispatchTouchEvent(ViewGroup.java:2107)
at android.view.ViewGroup.dispatchTransformedTouchEvent(ViewGroup.java:2406)
at android.view.ViewGroup.dispatchTouchEvent(ViewGroup.java:2107)
at android.view.ViewGroup.dispatchTransformedTouchEvent(ViewGroup.java:2406)
at android.view.ViewGroup.dispatchTouchEvent(ViewGroup.java:2107)
at android.view.ViewGroup.dispatchTransformedTouchEvent(ViewGroup.java:2406)
at android.view.ViewGroup.dispatchTouchEvent(ViewGroup.java:2107)
at android.view.ViewGroup.dispatchTransformedTouchEvent(ViewGroup.java:2406)
at android.view.ViewGroup.dispatchTouchEvent(ViewGroup.java:2107)
at android.view.ViewGroup.dispatchTransformedTouchEvent(ViewGroup.java:2406)
at android.view.ViewGroup.dispatchTouchEvent(ViewGroup.java:2107)
at com.android.internal.policy.impl.PhoneWindow$DecorView.superDispatchTouchEvent(PhoneWindow.java:2625)
at com.android.internal.policy.impl.PhoneWindow.superDispatchTouchEvent(PhoneWindow.java:1770)
at android.app.Activity.dispatchTouchEvent(Activity.java:2742)
at com.android.internal.policy.impl.PhoneWindow$DecorView.dispatchTouchEvent(PhoneWindow.java:2586)
at android.view.View.dispatchPointerEvent(View.java:8675)
at android.view.ViewRootImpl$ViewPostImeInputStage.processPointerEvent(ViewRootImpl.java:4129)
at android.view.ViewRootImpl$ViewPostImeInputStage.onProcess(ViewRootImpl.java:3995)
at android.view.ViewRootImpl$InputStage.deliver(ViewRootImpl.java:3550)
at android.view.ViewRootImpl$InputStage.onDeliverToNext(ViewRootImpl.java:3603)
at android.view.ViewRootImpl$InputStage.forward(ViewRootImpl.java:3569)
at android.view.ViewRootImpl$AsyncInputStage.forward(ViewRootImpl.java:3686)
at android.view.ViewRootImpl$InputStage.apply(ViewRootImpl.java:3577)
at android.view.ViewRootImpl$AsyncInputStage.apply(ViewRootImpl.java:3743)
at android.view.ViewRootImpl$InputStage.deliver(ViewRootImpl.java:3550)
at android.view.ViewRootImpl$InputStage.onDeliverToNext(ViewRootImpl.java:3603)
at android.view.ViewRootImpl$InputStage.forward(ViewRootImpl.java:3569)
at android.view.ViewRootImpl$InputStage.apply(ViewRootImpl.java:3577)
at android.view.ViewRootImpl$InputStage.deliver(ViewRootImpl.java:3550)
at android.view.ViewRootImpl.deliverInputEvent(ViewRootImpl.java:5813)
at android.view.ViewRootImpl.doProcessInputEvents(ViewRootImpl.java:5787)
at android.view.ViewRootImpl.enqueueInputEvent(ViewRootImpl.java:5758)
at android.view.ViewRootImpl$WindowInputEventReceiver.onInputEvent(ViewRootImpl.java:5903)
at android.view.InputEventReceiver.dispatchInputEvent(InputEventReceiver.java:185)
at android.view.InputEventReceiver.nativeConsumeBatchedInputEvents(Native Method)
at android.view.InputEventReceiver.consumeBatchedInputEvents(InputEventReceiver.java:176)
at android.view.ViewRootImpl.doConsumeBatchedI
A list view should not be in a scrollview.
Post your logs lets see where the error is coming from.
Edit 1
I checked your getDetails method, you defined an array of 100 indexes, what if the result if more than 100, You should use an ArrayList for that or define the array with the count from your cursor
String[] result = new String[c.getCount()];
Edit 2
Error seems to be coming from
String CustomerNam = CustomerName.getText().toString().trim();
Check to see if CustomerName is not null
in my experience with ListView, I've never had it inside of a ScrollView.
it should scroll on it's own.

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.

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