在主活动中,菜单指向片段BMICaclulator
和History
。BMICalculator
片段有3个EditText、一个单选按钮和一个提交按钮。
Fragment_bmicalculator.xml:
<EditText
android:id="@+id/height"/>
<EditText
android:id="@+id/weight" />
<EditText
android:id="@+id/age"/>
<RadioGroup xmlns:android="http://schemas.android.com/apk/res/android"
android:id="@+id/gender">
<RadioButton
android:id="@+id/gender_male"/>
<RadioButton
android:id="@+id/gender_female"/>
</RadioGroup>
<Button
android:id="@+id/calculate"/>
插入到数据库工作。传递的数据是从editText和RadiButton*获取的。
BmiCalculator.java:
MyDatabaseHelper myDB = new MyDatabaseHelper(getActivity());
myDB.addData(height, weight, age, gender, bmiInterpretation);
MyDataBaseHelper.java:
private Context context;
private static final String DATABASE_NAME = "bmi.db";
private static final int DATABASE_VERSION = 1;
private static final String TABLE_NAME = "bmiData";
private static final String COLUMN_ID = "id";
private static final String COLUMN_WEIGHT = "weight";
private static final String COLUMN_HEIGHT = "height";
private static final String COLUMN_AGE = "age";
private static final String COLUMN_GENDER = "gender";
private static final String COLUMN_BMI = "bmi";
public void onCreate(SQLiteDatabase db) {
String query = "CREATE TABLE " + TABLE_NAME +
" (" + COLUMN_ID + " INTEGER PRIMARY KEY AUTOINCREMENT, " +
COLUMN_WEIGHT + " TEXT, " +
COLUMN_HEIGHT + " TEXT, " +
COLUMN_AGE + " TEXT, " +
COLUMN_GENDER + " TEXT, " +
COLUMN_BMI + " TEXT);";
db.execSQL(query);
}
void addData(String weight, String height, String age, String gender, String bmi){
SQLiteDatabase db = this.getWritableDatabase();
ContentValues cv = new ContentValues();
cv.put(COLUMN_WEIGHT, weight);
cv.put(COLUMN_HEIGHT, height);
cv.put(COLUMN_AGE, age);
cv.put(COLUMN_GENDER, gender);
cv.put(COLUMN_BMI, bmi);
long result = db.insert(TABLE_NAME,null, cv);
if(result == -1){
Toast.makeText(context, "Failed", Toast.LENGTH_SHORT).show();
}else {
Toast.makeText(context, "Added Successfully!", Toast.LENGTH_SHORT).show();
}
如何在Fragment_HISTORY中获取数据并以列表的形式打印?回收视图和定制适配器使我的应用程序崩溃。
1条答案
按热度按时间kxkpmulp1#
首先,我认为更好的方式是定义一个类,比方说数据:
现在让我们定义一个返回SQLite数据库中所有数据的函数:
现在,为了在您的ListView内部插入数据(在Fragment_HISTORY的布局中定义),让我们假设XML文件中的ListView具有idlist_view,并且您为每个项定义了一个定制布局List_Item(用于显示数据的一个示例)。最后一步是创建一个适配器,并链接来自数据库和适配器的数据,例如: