Android 如何创建SQLite数据库来存储用户输入的与listview无关的输入?
我不知道如何创建一个数据库来存储我的用户信息。 我对如何创建数据库有一个粗略的想法,但这仅适用于listview中的项。我想存储我的用户信息,以便随时编辑信息。但每当我输入数值并设法获取卡路里时,一旦退出应用程序,我就必须再次输入所有信息 这是我的布局文件:Android 如何创建SQLite数据库来存储用户输入的与listview无关的输入?,android,sqlite,Android,Sqlite,我不知道如何创建一个数据库来存储我的用户信息。 我对如何创建数据库有一个粗略的想法,但这仅适用于listview中的项。我想存储我的用户信息,以便随时编辑信息。但每当我输入数值并设法获取卡路里时,一旦退出应用程序,我就必须再次输入所有信息 这是我的布局文件: 这是我的java代码: public class Calculator extends AppCompatActivity { EditText weight, height, age, name; double calculate
这是我的java代码:
public class Calculator extends AppCompatActivity {
EditText weight, height, age, name;
double calculate, result;
RadioButton radioGender;
int selectedId;
private Button button;
TextView calresult;
private Cursor model = null;
private CalculatorHelper helper2 = null;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.calories_calculator);
button = (Button) findViewById(R.id.calc);
button.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
weight = (EditText) findViewById(R.id.weight);
height = (EditText) findViewById(R.id.height);
age = (EditText) findViewById(R.id.age);
name = (EditText) findViewById(R.id.food);
helper2 = new CalculatorHelper(Calculator.this);
model = helper2.getAll();
int Gender;
RadioGroup rg = (RadioGroup) findViewById(R.id.radioGroup);
RadioButton male = (RadioButton) findViewById(R.id.Male);
RadioButton female = (RadioButton) findViewById(R.id.Female);
selectedId = rg.getCheckedRadioButtonId();
radioGender = (RadioButton) findViewById(selectedId);
if (male.isChecked()) {
Gender = 1;
} else {
Gender = 2;
}
if (TextUtils.isEmpty(name.getText().toString())) {
name.setError("Please enter your name");
Toast.makeText(Calculator.this, "Please enter your name",
Toast.LENGTH_LONG).show();
return;
}
if (TextUtils.isEmpty(weight.getText().toString())) {
weight.setError("Please enter your weight");
return;
}
if (TextUtils.isEmpty(height.getText().toString())) {
height.setError("Please enter your height");
return;
}
if (TextUtils.isEmpty(age.getText().toString())) {
age.setError("Please enter your age");
return;
}
String namevr = name.getText().toString();
double weightvr = Double.parseDouble(weight.getText().toString());
double heightvr = Double.parseDouble(height.getText().toString());
int agevr = Integer.parseInt(age.getText().toString());
Intent intent = new Intent(Calculator.this, DataCalculator.class);
intent.putExtra("NAME", namevr);
result = calculate + 0;
intent.putExtra("RESULT", result);
//a.putString("name", String.valueOf(namevr));
if ((weightvr <= 30) || (weightvr >= 200)) {
Toast.makeText(Calculator.this, "Please enter a valid weight",
Toast.LENGTH_SHORT).show();
return;
} else if ((heightvr <= 120) || (heightvr >= 220)) {
Toast.makeText(Calculator.this, "Please enter a valid height",
Toast.LENGTH_SHORT).show();
return;
} else if ((agevr <= 0) || (agevr >= 120)) {
Toast.makeText(Calculator.this, "Please enter a valid age",
Toast.LENGTH_SHORT).show();
return;
} else {
if (selectedId == R.id.Male) {
calculate = (((weightvr * 10) + (heightvr * 6.25)) - (5 * agevr)) + 5;
} else {
calculate = (((weightvr * 10) + (heightvr * 6.25)) - (5 * agevr)) - 161;
}
}
intent.putExtra("RESULT", String.valueOf(calculate));
startActivity(intent);
finish();
}
});
}
公共类计算器扩展AppCompatActivity{
编辑文本重量、身高、年龄、姓名;
双重计算,结果;
无线电按钮式放射装置;
int-selectedId;
私人按钮;
文本视图计算结果;
私有游标模型=null;
private calculatorhelper2=null;
@凌驾
创建时受保护的void(Bundle savedInstanceState){
super.onCreate(savedInstanceState);
setContentView(R.layout.carries\u计算器);
按钮=(按钮)findViewById(R.id.calc);
setOnClickListener(新视图.OnClickListener(){
公共void onClick(视图v){
权重=(EditText)findViewById(R.id.weight);
高度=(EditText)findViewById(R.id.height);
年龄=(EditText)findViewById(R.id.age);
name=(EditText)findViewById(R.id.food);
helper2=新计算器helper(Calculator.this);
model=helper2.getAll();
int性别;
放射组rg=(放射组)findViewById(R.id.RadioGroup);
RadioButton male=(RadioButton)findViewById(R.id.male);
RadioButton阴性=(RadioButton)findViewById(R.id.female);
selectedId=rg.getCheckedRadioButtonId();
RadioEnder=(单选按钮)findViewById(SelecteId);
if(male.isChecked()){
性别=1;
}否则{
性别=2;
}
if(TextUtils.isEmpty(name.getText().toString())){
name.setError(“请输入您的姓名”);
Toast.makeText(Calculator.this,“请输入您的姓名”,
Toast.LENGTH_LONG).show();
返回;
}
if(TextUtils.isEmpty(weight.getText().toString()){
设置错误(“请输入您的体重”);
返回;
}
if(TextUtils.isEmpty(height.getText().toString()){
高度。设置错误(“请输入您的高度”);
返回;
}
if(TextUtils.isEmpty(age.getText().toString()){
age.setError(“请输入您的年龄”);
返回;
}
字符串namevr=name.getText().toString();
double-weightvr=double.parseDouble(weight.getText().toString());
double-heightvr=double.parseDouble(height.getText().toString());
int agevr=Integer.parseInt(age.getText().toString());
Intent Intent=新的Intent(Calculator.this、DataCalculator.class);
意图。putExtra(“名称”,namevr);
结果=计算+0;
意向。额外(“结果”,结果);
//a、 putString(“name”,String.valueOf(namevr));
如果((权重Vr=200)){
Toast.makeText(Calculator.this,“请输入有效重量”,
吐司。长度(短)。show();
返回;
}否则如果((高度Vr=220)){
Toast.makeText(Calculator.this,“请输入有效高度”,
吐司。长度(短)。show();
返回;
}否则,如果((agevr=120)){
Toast.makeText(Calculator.this,“请输入有效年龄”,
吐司。长度(短)。show();
返回;
}否则{
if(selectedId==R.id.Male){
计算=((重量Vr*10)+(高度Vr*6.25))-(5*agevr))+5;
}否则{
计算=((重量Vr*10)+(高度Vr*6.25))-(5*agevr))-161;
}
}
intent.putExtra(“结果”,String.valueOf(计算));
星触觉(意向);
完成();
}
});
}
}假设CalculatorHelper将是您的数据库助手 步骤1-将CallculatorHelper创建/修改为
- 扩展SQLiteOpenHelper类
public类CalculatorHelper扩展SQLiteOpenHelper{……}
扩展SQLiteOpenHelper的类至少需要3个实体
- 此调用需要4个值
- 1) 一个有效的上下文
- 2) 数据库的名称(这将是文件的名称)
- 3) 游标工厂(null将被使用,因为不需要)
- 4) 整数版本号(1是第一个)
- 已创建的SQLiteDatabase对象。该方法不返回任何内容,因此使用void定义
- SQliteDatabase对象
- 存储在数据库中的版本号(旧版本)
- 已传递给SQLiteOpenHelper超级构造函数(新版本)的构造函数的版本号
public class Calculator extends AppCompatActivity {
EditText weight, height, age, name;
double calculate, result;
RadioButton radioGender;
int selectedId;
private Button button;
TextView calresult;
private Cursor model = null;
private CalculatorHelper helper2 = null;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.calories_calculator);
button = (Button) findViewById(R.id.calc);
button.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
weight = (EditText) findViewById(R.id.weight);
height = (EditText) findViewById(R.id.height);
age = (EditText) findViewById(R.id.age);
name = (EditText) findViewById(R.id.food);
helper2 = new CalculatorHelper(Calculator.this);
model = helper2.getAll();
int Gender;
RadioGroup rg = (RadioGroup) findViewById(R.id.radioGroup);
RadioButton male = (RadioButton) findViewById(R.id.Male);
RadioButton female = (RadioButton) findViewById(R.id.Female);
selectedId = rg.getCheckedRadioButtonId();
radioGender = (RadioButton) findViewById(selectedId);
if (male.isChecked()) {
Gender = 1;
} else {
Gender = 2;
}
if (TextUtils.isEmpty(name.getText().toString())) {
name.setError("Please enter your name");
Toast.makeText(Calculator.this, "Please enter your name",
Toast.LENGTH_LONG).show();
return;
}
if (TextUtils.isEmpty(weight.getText().toString())) {
weight.setError("Please enter your weight");
return;
}
if (TextUtils.isEmpty(height.getText().toString())) {
height.setError("Please enter your height");
return;
}
if (TextUtils.isEmpty(age.getText().toString())) {
age.setError("Please enter your age");
return;
}
String namevr = name.getText().toString();
double weightvr = Double.parseDouble(weight.getText().toString());
double heightvr = Double.parseDouble(height.getText().toString());
int agevr = Integer.parseInt(age.getText().toString());
Intent intent = new Intent(Calculator.this, DataCalculator.class);
intent.putExtra("NAME", namevr);
result = calculate + 0;
intent.putExtra("RESULT", result);
//a.putString("name", String.valueOf(namevr));
if ((weightvr <= 30) || (weightvr >= 200)) {
Toast.makeText(Calculator.this, "Please enter a valid weight",
Toast.LENGTH_SHORT).show();
return;
} else if ((heightvr <= 120) || (heightvr >= 220)) {
Toast.makeText(Calculator.this, "Please enter a valid height",
Toast.LENGTH_SHORT).show();
return;
} else if ((agevr <= 0) || (agevr >= 120)) {
Toast.makeText(Calculator.this, "Please enter a valid age",
Toast.LENGTH_SHORT).show();
return;
} else {
if (selectedId == R.id.Male) {
calculate = (((weightvr * 10) + (heightvr * 6.25)) - (5 * agevr)) + 5;
} else {
calculate = (((weightvr * 10) + (heightvr * 6.25)) - (5 * agevr)) - 161;
}
}
intent.putExtra("RESULT", String.valueOf(calculate));
startActivity(intent);
finish();
}
});
}
public class CalculatorHelper extends SQLiteOpenHelper {
public static final String DBNAME = "calculator.db";
public static final int DBVERSION = 1;
public static final String PERSONDATA_TABLENAME = "person_data";
public static final String COL_PERSONDATA_ID = BaseColumns._ID;
public static final String COL_PERSONDATA_NAME = "_name";
public static final String COL_PERSONDATA_WEIGHT = "_weight";
public static final String COL_PERSONDATA_HEIGHT = "_height";
public static final String COL_PERSONDATA_AGE = "_age";
public static final String COL_PERSONDATA_GENDER = "_gender";
public static final String PERSONDATA_TABLESQL = "CREATE TABLE IF NOT EXISTS " +
PERSONDATA_TABLENAME + "(" +
COL_PERSONDATA_ID + " INTEGER PRIMARY KEY," +
COL_PERSONDATA_NAME + " TEXT," +
COL_PERSONDATA_WEIGHT + " INTEGER," +
COL_PERSONDATA_HEIGHT + " INTEGER, " +
COL_PERSONDATA_AGE + " INTEGER, " +
COL_PERSONDATA_GENDER + " INTEGER " +
")";
public CalculatorHelper(Context context) {
super(context, DBNAME, null, DBVERSION);
}
@Override
public void onCreate(SQLiteDatabase db) {
db.execSQL(PERSONDATA_TABLESQL); //<< when the database is created create the table
}
@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
}
public long insertPersonData(String name, int weight, int heigh, int age, boolean gender) {
SQLiteDatabase db = this.getWritableDatabase(); //<< gets the SQLiteDatabase object for this instance
ContentValues cv = new ContentValues(); //<< ContentValues are key (column name) value
cv.put(COL_PERSONDATA_NAME,name);
cv.put(COL_PERSONDATA_WEIGHT,weight);
cv.put(COL_PERSONDATA_HEIGHT,heigh);
cv.put(COL_PERSONDATA_AGE,age);
cv.put(COL_PERSONDATA_GENDER,gender);
//<< NOTE id isn't specified SQLite will generate an id (the value returned)
return db.insert(PERSONDATA_TABLENAME,null,cv);
// Writes and executes the SQL () assuming insertPersonData:-
// INSERT INTO person_data (_name,_weight,_height,_age,_gender) VALUES('Fred',75,160,21,0)
}
/**
*
* @param id The id of the row to be updated
* @param newName The new name to apply ("" or null if not to change)
* @param newWeight The new weight to apply (null or less than 1 to not change)
* @param newHeight as per weight for height
* @param newAge as per weight for age
* @param newGender true or false or null if to not be changed
* @return the number of rows update (should be 1 or 0, o if nothing changed)
*/
public int updatePersonData(long id, String newName, Integer newWeight, Integer newHeight, Integer newAge, Boolean newGender) {
int rv = 0;
ContentValues cv = new ContentValues();
if (newName != null && newName.length() > 0 ) {
cv.put(COL_PERSONDATA_NAME,newName);
}
if (newWeight != null && newWeight > 0) {
cv.put(COL_PERSONDATA_WEIGHT,newWeight);
}
if (newHeight != null && newHeight > 0) {
cv.put(COL_PERSONDATA_HEIGHT,newHeight);
}
if (newAge != null && newAge > 0) {
cv.put(COL_PERSONDATA_AGE,newAge);
}
if (newGender != null) {
cv.put(COL_PERSONDATA_GENDER,newGender);
}
if (cv.size() > 0) {
SQLiteDatabase db = this.getWritableDatabase();
rv = db.update(PERSONDATA_TABLENAME,cv,COL_PERSONDATA_ID + "=?",new String[]{String.valueOf(id)});
}
return rv;
}
public int deletePersonData(long id) {
SQLiteDatabase db = this.getWritableDatabase();
return db.delete(PERSONDATA_TABLENAME,COL_PERSONDATA_ID+"=?",new String[]{String.valueOf(id)});
}
/**
* Returns ALL persondata as a Cursor object
* @return
*/
public Cursor getAllPersonDataRows() {
SQLiteDatabase db = this.getWritableDatabase();
return db.query(
PERSONDATA_TABLENAME,
null,
null,
null,
null,
null,
null
);
}
public Cursor getPersonByID(long id) {
SQLiteDatabase db = this.getWritableDatabase();
return db.query(
PERSONDATA_TABLENAME,
null,
COL_PERSONDATA_ID+"=?",
null,
null,
null,
null
);
}
}
setContentView(R.layout.calories_calculator); //<<<<<<<<<< existing code
helper2 = new CalculatorHelper(this);
button = (Button) findViewById(R.id.calc); //<<<<<<<<<< existing code
save = (Button) findViewById(R.id.save);
save.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Boolean gender = true;
if (((RadioButton)Calculator.this.findViewById(R.id.Male)).isChecked()) {
gender = false;
}
long newid = helper2.insertPersonData(
(((EditText)Calculator.this.findViewById(R.id.food)).getText().toString()),
Integer.parseInt(((EditText)Calculator.this.findViewById(R.id.weight)).getText().toString()),
Integer.parseInt(((EditText)Calculator.this.findViewById(R.id.height)).getText().toString()),
Integer.parseInt(((EditText)Calculator.this.findViewById(R.id.age)).getText().toString()),
gender
);
String msg = "Not Inserted into the database.";
if (newid > 0) {
msg = "Successfully Inserted into the database.";
}
Toast.makeText(Calculator.this,msg,Toast.LENGTH_SHORT).show();
//Example getting data and traversing a Cursor
Cursor csr = helper2.getAllPersonDataRows();
while (csr.moveToNext()) {
String gendertype = "M";
if (csr.getInt(csr.getColumnIndex(CalculatorHelper.COL_PERSONDATA_GENDER)) > 0) {
gendertype = "F";
}
Log.d("PERSONDATA",
"Name is " + csr.getString(csr.getColumnIndex(CalculatorHelper.COL_PERSONDATA_NAME)) +
"\nWeight is " + String.valueOf(
csr.getInt(
csr.getColumnIndex(CalculatorHelper.COL_PERSONDATA_WEIGHT)
)
) + "kg" +
"\nHeight is " + String.valueOf(csr.getInt(csr.getColumnIndex(CalculatorHelper.COL_PERSONDATA_HEIGHT))) + " cm" +
"\nAge is " + csr.getString(csr.getColumnIndex(CalculatorHelper.COL_PERSONDATA_AGE)) + " years" +
"\nGender is " + gendertype +
"\nUnique Row Identifier is " + String.valueOf(csr.getLong(csr.getColumnIndex(CalculatorHelper.COL_PERSONDATA_ID)))
);
}
csr.close(); //<< IMPORTANT to close Cursors when done with them
}
});
//........... rest of your code here ...........
07-14 10:15:28.462 25100-25100/s.e.so57021686calculator D/PERSONDATA: Name is Fred
Weight is 75kg
Height is 166 cm
Age is 61 years
Gender is M
Unique Row Identifier is 1
07-14 10:15:28.462 25100-25100/s.e.so57021686calculator D/PERSONDATA: Name is Mary
Weight is 68kg
Height is 34 cm
Age is 159 years
Gender is F
Unique Row Identifier is 2