我正在尝试使用sqlite
更新execSQL
表。但是,执行后它清除(清空)我的整个表数据而不是更新某些字段。我的代码是
private void updatedata(String name,String spingender,String cWeight,String spinunit,String htInString,String spingoal,String spinactivity,String spinexercise,String scalorie,String sprotein,String carbohydrate,String sfat) {
DatabaseHandler helper = new DatabaseHandler(getApplicationContext());
SQLiteDatabase db = helper.getReadableDatabase();
System.out.println("in update data "+name + spingender + cWeight);
String Query = "SELECT * FROM login WHERE name ='"+name+"'";
Cursor QueryCursor = db.rawQuery(Query,null);
// there is some record available in the cursor
if (QueryCursor.moveToFirst()) {
db.execSQL("UPDATE login SET gender='"+spingender+"',weight='"+cWeight+"',userunit='"+spinunit+"',height='"+htInString+"',goal='"+spingoal+"',activeness='"+spinactivity+"',exercise='"+spinexercise+"',calorie='"+scalorie+"',fat='"+sfat+"',carbohydrate='"+carbohydrate+"',protein='"+sprotein+"'");
}
QueryCursor.close();
db.close();
}
完整代码
package com.bharatwellness.mainactivities;
import java.io.ByteArrayOutputStream;
import org.json.JSONObject;
import com.bharatwellness.libraries.DatabaseHandler;
import com.bharatwellness.libraries.UserFunctions;
import com.project.homepagedemo.R;
import android.app.Activity;
import android.content.Intent;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.graphics.Bitmap;
import android.os.Bundle;
import android.util.Base64;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.Spinner;
import android.widget.TextView;
public class ProfilePageActivity extends Activity{
private String gender;
private String weight;
private String height;
private EditText etWeight;
private EditText etHeightFirst;
private EditText etHeighttwo;
private Button takePhoto;
private ImageView imageView;
Bitmap thumbnail;
private static final int CAM_REQUEST = 1313;
private String image_str;
private String goal;
private String activeness;
private String exercise;
private double double_height;
private TextView updateButton;
private String name;
private String htInString ;
private Spinner spinnergender;
private Spinner spinnergoal;
private Spinner spinneractiveness;
private Spinner spinnerexercise;
private String userunit;
private Spinner spinnerunit;
private String spinunit;
private String spingender;
private String spingoal;
private String spinactivity;
private String spinexercise;
private String[] KUnits = { "Kgs", "Pounds" };
private String[] PUnits = { "Pounds","Kgs" };
private String[] MGenders = { "Male", "Female" };
private String[] FGenders = { "Female", "Male" };
private String[] RGoals = {"Reduce Weight","Maintain Weight","Gain Weight"};
private String[] MGoals = {"Maintain Weight","Reduce Weight","Gain Weight"};
private String[] GGoals = {"Gain Weight","Maintain Weight","Reduce Weight"};
private String[] HActiveness = {"Highly Active","Moderate Activity","Low Active"};
private String[] MActiveness = {"Moderate Activity","Highly Active","Low Active"};
private String[] LActiveness = {"Low Active","Moderate Activity","Highly Active"};
private String[] LExerciseLevel = {"Less than 30 Mins","30 - 60 Mins","More than 60 Mins"};
private String[] RExerciseLevel = {"30 - 60 Mins","Less than 30 Mins","More than 60 Mins"};
private String[] MExerciseLevel = {"More than 60 Mins","30 - 60 Mins","Less than 30 Mins"};
private String age;
private double valueaftergoal;
private double recxa;
private double recxb;
private double finalcalorie;
private double protein;
private double carbs;
private double fat;
private String scalorie;
private String sprotein;
private String sfat;
private String carbohydrate;
private String cWeight;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_profile);
Bundle bundle = getIntent().getExtras();
if(bundle != null) {
name = bundle.getString("name");
System.out.println("in profile" + name);
}
etWeight = (EditText)findViewById(R.id.etWeight);
etHeightFirst = (EditText)findViewById(R.id.etHeightFeet);
etHeighttwo = (EditText)findViewById(R.id.etHeightInches);
spinnerunit = (Spinner) findViewById(R.id.spinnerweight);
spinnergender = (Spinner) findViewById(R.id.spinnergender);
spinnergoal = (Spinner) findViewById(R.id.spinnergoal);
spinneractiveness = (Spinner) findViewById(R.id.spinneractiveness);
spinnerexercise = (Spinner) findViewById(R.id.spinnerexercise);
takePhoto = (Button)findViewById(R.id.picbutton);
updateButton = (TextView)findViewById(R.id.updateButton);
takePhoto.setOnClickListener(new btnTakePhotoClicker());
selectData();
genderselected();
unitselected();
goalselected();
activityselected();
exerciseselected();
//height
double doubleHeightValue = Double.parseDouble(height);
System.out.println("dble ht value " + doubleHeightValue);
double doubleHeightInCM = doubleHeightValue * 2.54;
System.out.println("ht in CM " + doubleHeightInCM);
double_height = doubleHeightInCM * 0.3937008;
System.out.println("ht to feet " + double_height);
int height_in_feet = (int) (double_height / 12);
System.out.println("height_in_feet " + height_in_feet);
int height_in_inch = (int) (double_height % 12);
System.out.println("height_in_inch " + height_in_inch);
etWeight.setText("" + weight);
etHeightFirst.setText("" + height_in_feet);
etHeighttwo.setText("" + height_in_inch );
updateButton.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
String f = etHeightFirst.getText().toString();
String i = etHeighttwo.getText().toString();
cWeight = etWeight.getText().toString();
int feet = Integer.parseInt(f);
int ifeet = Integer.parseInt(i);
int newHeight = (feet * 12) + ifeet;
htInString = String.valueOf(newHeight);
System.out.println("name" + name + htInString);
spinunit = (String) spinnerunit.getSelectedItem();
spingender = (String) spinnergender.getSelectedItem();
spingoal = (String) spinnergoal.getSelectedItem();
spinactivity = (String) spinneractiveness.getSelectedItem();
spinexercise = (String) spinnerexercise.getSelectedItem();
calculations();
scalorie = Double.toString(finalcalorie);
sfat = Double.toString(fat);
sprotein = Double.toString(protein);
carbohydrate = Double.toString(carbs);
System.out.println("Gender on item selected" + spingender);
System.out.println("Exercise on item selected" + spinexercise);
System.out.println("Goal on item selected" + spingoal);
System.out.println("Exercise on item selected" + spinexercise);
System.out.println("Activity on item selected" + spinactivity);
updatedata(name,spingender,cWeight,spinunit,htInString,spingoal,spinactivity,spinexercise,scalorie,sprotein,carbohydrate,sfat);
UserFunctions userFunction = new UserFunctions();
JSONObject json = userFunction.updateUser(name,spingender,cWeight,spinunit,htInString,spingoal,spinactivity,spinexercise,scalorie,sprotein,carbohydrate,sfat);
userFunction.logoutUser(getApplicationContext());
Intent intent = new Intent(getApplicationContext(), CalorieMainActivity.class);
intent.putExtra("name", name);
startActivity(intent);
finish();
}
});
}
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if(requestCode == CAM_REQUEST) {
Bitmap thumbnail = (Bitmap)data.getExtras().get("data");
ByteArrayOutputStream stream = new ByteArrayOutputStream();
thumbnail.compress(Bitmap.CompressFormat.PNG, 90, stream); //compress to which format you want.
byte [] byte_arr = stream.toByteArray();
image_str = Base64.encodeToString(byte_arr, Base64.DEFAULT);
imageView.setImageBitmap(thumbnail);
}
}
class btnTakePhotoClicker implements Button.OnClickListener {
@Override
public void onClick(View v) {
Intent camintent = new Intent(android.provider.MediaStore.ACTION_IMAGE_CAPTURE);
startActivityForResult(camintent,CAM_REQUEST);
}
}
private void selectData() {
DatabaseHandler helper = new DatabaseHandler(this);
SQLiteDatabase db = helper.getReadableDatabase();
String query = "SELECT gender,weight,height,goal,activeness,exercise,userunit,userage FROM login";
Cursor cursor = db.rawQuery(query,null);
// there is some record available in the cursor
if (!cursor.isAfterLast()) {
cursor.moveToFirst();
while (!cursor.isAfterLast()) {
gender = cursor.getString(0);
weight = cursor.getString(1);
height = cursor.getString(2);
goal = cursor.getString(3);
activeness = cursor.getString(4);
exercise = cursor.getString(5);
userunit = cursor.getString(6);
age = cursor.getString(7);
Log.e("calorie info", "gender:" + gender + ", weight:" + weight+ ",unit:" + userunit + ", height:" + height + ", goal:" + goal+ ", activeness:" + activeness+ ", exercise:" + exercise + ", age :" + age);
cursor.moveToNext();
}
}
cursor.close();
db.close();
}
public void gotoCalorieHomeActivity(View v) {
Intent intent = new Intent(this,CalorieMainActivity.class);
startActivity(intent);
}
public void genderselected(){
if(gender.equals("Male")){
//gender
ArrayAdapter<String> adapter_gender = new ArrayAdapter<String>(this,
android.R.layout.simple_spinner_item, MGenders);
adapter_gender
.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
spinnergender.setAdapter(adapter_gender);
//spinnergender.setOnItemSelectedListener(this);
}
else{
//gender
ArrayAdapter<String> adapter_gender = new ArrayAdapter<String>(this,
android.R.layout.simple_spinner_item, FGenders);
adapter_gender
.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
spinnergender.setAdapter(adapter_gender);
//spinnergender.setOnItemSelectedListener(this);
}
}
public void unitselected(){
//for units
if(userunit.equals("Kgs")){
ArrayAdapter<String> adapter_unit = new ArrayAdapter<String>(this,
android.R.layout.simple_spinner_item, KUnits);
adapter_unit
.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
spinnerunit.setAdapter(adapter_unit);
//spinnerunit.setOnItemSelectedListener(this);
}
else{
ArrayAdapter<String> adapter_unit = new ArrayAdapter<String>(this,
android.R.layout.simple_spinner_item, PUnits);
adapter_unit
.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
spinnerunit.setAdapter(adapter_unit);
//spinnerunit.setOnItemSelectedListener(this);
}
}
public void goalselected(){
if(goal.equals("Reduce Weight")){
//goal
ArrayAdapter<String> adapter_goal = new ArrayAdapter<String>(this,
android.R.layout.simple_spinner_item, RGoals);
adapter_goal
.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
spinnergoal.setAdapter(adapter_goal);
//spinnergoal.setOnItemSelectedListener(this);
}
else if(goal.equals("Maintain Weight")){
//goal
ArrayAdapter<String> adapter_goal = new ArrayAdapter<String>(this,
android.R.layout.simple_spinner_item, MGoals);
adapter_goal
.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
spinnergoal.setAdapter(adapter_goal);
//spinnergoal.setOnItemSelectedListener(this);
}
else{
//goal
ArrayAdapter<String> adapter_goal = new ArrayAdapter<String>(this,
android.R.layout.simple_spinner_item, GGoals);
adapter_goal
.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
spinnergoal.setAdapter(adapter_goal);
//spinnergoal.setOnItemSelectedListener(this);
}
}
public void activityselected()
{
if(activeness.equals("Highly Active")){
//activeness
ArrayAdapter<String> adapter_activeness = new ArrayAdapter<String>(this,
android.R.layout.simple_spinner_item, HActiveness);
adapter_activeness
.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
spinneractiveness.setAdapter(adapter_activeness);
// spinneractiveness.setOnItemSelectedListener(this);
}
else if(activeness.equals("Moderate Activity")){
//activeness
ArrayAdapter<String> adapter_activeness = new ArrayAdapter<String>(this,
android.R.layout.simple_spinner_item, MActiveness);
adapter_activeness
.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
spinneractiveness.setAdapter(adapter_activeness);
//spinneractiveness.setOnItemSelectedListener(this);
}
else{
//activeness
ArrayAdapter<String> adapter_activeness = new ArrayAdapter<String>(this,
android.R.layout.simple_spinner_item, LActiveness);
adapter_activeness
.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
spinneractiveness.setAdapter(adapter_activeness);
//spinneractiveness.setOnItemSelectedListener(this);
}
}
public void exerciseselected(){
if (exercise.equals("Less than 30 Mins")){
//exercise
ArrayAdapter<String> adapter_exercise = new ArrayAdapter<String>(this,
android.R.layout.simple_spinner_item, LExerciseLevel);
adapter_exercise
.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
spinnerexercise.setAdapter(adapter_exercise);
//spinnerexercise.setOnItemSelectedListener(this);
}
else if(exercise.equals("30 - 60 Mins")){
//exercise
ArrayAdapter<String> adapter_exercise = new ArrayAdapter<String>(this,
android.R.layout.simple_spinner_item, RExerciseLevel);
adapter_exercise
.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
spinnerexercise.setAdapter(adapter_exercise);
// spinnerexercise.setOnItemSelectedListener(this);
}
else{
//exercise
ArrayAdapter<String> adapter_exercise = new ArrayAdapter<String>(this,
android.R.layout.simple_spinner_item, MExerciseLevel);
adapter_exercise
.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
spinnerexercise.setAdapter(adapter_exercise);
// spinnerexercise.setOnItemSelectedListener(this);
}
}
public void calculations() {
//weight conversion
Double dweight = Double.parseDouble(weight);
System.out.println("weight in calculations"+weight);
if(spinunit.equals("Kgs") ){
dweight = dweight * 2.20462;
}
else {
}
//height conversion
int iheight = Integer.parseInt(htInString);
System.out.println("height in calculations"+htInString);
System.out.println("this is the part of calculation in disease activity height" + iheight);
//age conversion
int iage = Integer.parseInt(age);
System.out.println("age in calculations"+age);
System.out.println("this is the part of calculation in disease activity age" + iage);
//calculating goal
if(spingender.equals("Female")){
valueaftergoal = 655 + (4.3 * dweight) + (4.7 * iheight) - (4.7 * iage);
System.out.println("this is the part of calculation in disease activity valueaftergoal" + valueaftergoal);
}
else {
valueaftergoal = 66 + (6.3 * dweight) + (12.9 * iheight) - (6.8 * iage);
System.out.println("this is the part of calculation in disease activity valueaftergoal" + valueaftergoal);
}
if(spingoal.equals("Reduce Weight") || spingoal.equals("Maintain Weight") || spingoal.equals("Gain Weight") ){
if(spinactivity.equals("Highly Active") && spinexercise.equals("Less than 30 Mins") ){
recxa = (1.10 * valueaftergoal);
System.out.println("this is the part of calculation in disease activity recxa" +recxa);
recxb = (1.00 * recxa);
System.out.println("this is the part of calculation in disease activity recxb" +recxb);
}
else if(spinactivity.equals("Highly Active") && spinexercise.equals("30 - 60 Mins")){
recxa = (1.10 * valueaftergoal);
System.out.println("this is the part of calculation in disease activity recxa" +recxa);
recxb = (1.05 * recxa);
System.out.println("this is the part of calculation in disease activity recxb" +recxb);
}
else if(spinactivity.equals("Highly Active") && spinexercise.equals("More than 60 Mins")){
recxa = (1.10 * valueaftergoal);
System.out.println("this is the part of calculation in disease activity recxa" +recxa);
recxb = (1.10 * recxa);
System.out.println("this is the part of calculation in disease activity recxb" +recxb);
}
else if(spinactivity.equals("Moderate Activity") && spinexercise.equals("Less than 30 Mins")){
recxa = (1.05 * valueaftergoal);
System.out.println("this is the part of calculation in disease activity recxa" +recxa);
recxb = (1.00 * recxa);
System.out.println("this is the part of calculation in disease activity recxb" +recxb);
}
else if(spinactivity.equals("Moderate Activity") && spinexercise.equals("30 - 60 Mins")){
recxa = (1.05 * valueaftergoal);
System.out.println("this is the part of calculation in disease activity recxa" +recxa);
recxb = (1.05 * recxa);
System.out.println("this is the part of calculation in disease activity recxb" +recxb);
}
else if(spinactivity.equals("Moderate Activity") && spinexercise.equals("More than 60 Mins")){
recxa = (1.05 * valueaftergoal);
System.out.println("this is the part of calculation in disease activity recxa" +recxa);
recxb = (1.10 * recxa);
System.out.println("this is the part of calculation in disease activity recxb" +recxb);
}
else if(spinactivity.equals("Low Active") && spinexercise.equals("Less than 30 Mins")){
recxa = (1.00 * valueaftergoal);
System.out.println("this is the part of calculation in disease activity recxa" +recxa);
recxb = (1.00 * recxa);
System.out.println("this is the part of calculation in disease activity recxb" +recxb);
}
else if(spinactivity.equals("Low Active") && spinexercise.equals("30 - 60 Mins")){
recxa = (1.00 * valueaftergoal);
System.out.println("this is the part of calculation in disease activity recxa" +recxa);
recxb = (1.05 * recxa);
System.out.println("this is the part of calculation in disease activity recxb" +recxb);
}
else if(spinactivity.equals("Low Active") && spinexercise.equals("More than 60 Mins")){
recxa = (1.00 * valueaftergoal);
System.out.println("this is the part of calculation in disease activity recxa" +recxa);
recxb = (1.10 * recxa);
System.out.println("this is the part of calculation in disease activity recxb" +recxb);
}
else{
System.out.println("None");
}
}
else{
System.out.println("None weight or goal");
}
if(spingoal.equals("Reduce Weight")){
finalcalorie = recxb * 0.9;
System.out.println("Final" + finalcalorie);
}
else if(spingoal.equals("Maintain Weight")){
finalcalorie = recxb;
System.out.println("Final" + finalcalorie);
}
else if(spingoal.equals("Gain Weight")){
finalcalorie = 1.2 * recxb;
System.out.println("Final" + finalcalorie);
}
else {
System.out.println("None found");
}
protein = ((finalcalorie * 50) / 100 ) / 4 ;
System.out.println("this is the part of calculation in disease activity protein" + protein);
carbs = ((finalcalorie * 30) / 100 ) / 4 ;
System.out.println("this is the part of calculation in disease activity carbs" + carbs);
fat = ((finalcalorie * 20) / 100 ) / 9 ;
System.out.println("this is the part of calculation in disease activity fat" + fat);
finalcalorie = Math.round(finalcalorie * 100);
finalcalorie = finalcalorie/100;
System.out.println("this is the part of calculation in disease activity finalcalorie" + finalcalorie);
protein = Math.round(protein * 100);
protein = protein/100;
System.out.println("This is the value of " + protein);
carbs = Math.round(carbs * 100);
carbs = carbs/100;
System.out.println("This is the value of " + carbs);
fat = Math.round(fat * 100);
fat = fat/100;
System.out.println("This is the value of " + fat);
}
private void updatedata(String name,String spingender,String cWeight,String spinunit,String htInString,String spingoal,String spinactivity,String spinexercise,String scalorie,String sprotein,String carbohydrate,String sfat) {
DatabaseHandler helper = new DatabaseHandler(getApplicationContext());
SQLiteDatabase db = helper.getWritableDatabase();
System.out.println("in update data "+name + spingender + cWeight);
String Query = "SELECT * FROM login WHERE name ='"+name+"'";
Cursor QueryCursor = db.rawQuery(Query,null);
// there is some record available in the cursor
if (QueryCursor.moveToFirst()) {
db.execSQL("UPDATE login SET gender='"+spingender+"',weight='"+cWeight+"',userunit='"+spinunit+"',height='"+htInString+"',goal='"+spingoal+"',activeness='"+spinactivity+"',exercise='"+spinexercise+"',calorie='"+scalorie+"',fat='"+sfat+"',carbohydrate='"+carbohydrate+"',protein='"+sprotein+"' WHERE name ='"+name+"'");
}
QueryCursor.close();
db.close();
}
}
答案 0 :(得分:5)
要进行更新,您需要使用db.update(table, values, whereClause, whereArgs)
但你正在使用
db.execSQL("UPDATE login SET gender='"+spingender+"',weight='"+cWeight+"',userunit='"+spinunit+"',height='"+htInString+"',goal='"+spingoal+"',activeness='"+spinactivity+"',exercise='"+spinexercise+"',calorie='"+scalorie+"',fat='"+sfat+"',carbohydrate='"+carbohydrate+"',protein='"+sprotein+"'");
所以它不是updating
你的桌子而是executing
新的..
所以你应该照顾这个
检查代码:
//有3个参数......你可以根据需要添加
public void updatedata(String name ,String spingender ,String cWeight)
{
ContentValues updatedValues = new ContentValues();
// Assign values for each row.
// USERNAME is COLUMN NAME of you table ,
// name is your value you are passing
updatedValues.put("USERNAME", name);
updatedValues.put("GENDER", spingender);
updatedValues.put("wEIGHT", cWeight);
String where="USERNAME = ?";
db.update("yor tablename " , updatedValues, where, new String[]{name});
}
现在,您可以update
使用新的spingender
和cWeight
作为username
来{{1}}。{/ p>
答案 1 :(得分:3)
首先,您应该使用getWritableDatabase()
代替getReadableDatabase()
来更改表记录,并在查询中使用“WHERE”语句。
为什么不使用db.update()
?
答案 2 :(得分:2)
尝试使用name
updatedata(...)
更新特定记录
SQLiteDatabase db = helper.getWritableDatabase();
ContentValues values = new ContentValues();
values.put("gender", spingender);
values.put("Weight", cWeight);
values.put("userunit", spinunit);
values.put("height", htInString);
values.put("goal", spingoal);
values.put("activeness", spinactivity);
values.put("exercise", spinexercise);
values.put("calorie", scalorie);
values.put("fat", sfat);
values.put("carbohydrate", carbohydrate);
values.put("protein", sprotein);
String whereClause =" name=? ";
String[] whereArgs = new String[]{name};
int rows = db.update("login", values, whereClause, whereArgs);
if(rows > 0){
//Update successfully
}
答案 3 :(得分:2)
您正在尝试更新表格的行,但您没有指定要尝试更新的行。使用&#34; WHERE&#34;指定要更新的行。子句。