简体   繁体   中英

How to fetch data to fragment?

In main activity a menu leads to fragments BMICaclulator and History . BMICalculator fragment has 3 EditText, a radio button and a submit button.

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

Insert into database works. Passed data is fetched from editText and radioButton*.

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();
        }

How to fetch data and print as list in fragment_history? RecyclerView and custom adapter crashed my app.

First of all, I think that is better to define a class let's say Data, in this way:

public class Data{
    private String weight;
    private String height;
    private String age;
    private String gender;
    private String bmi;
    
    // Constructor, getter and setters ...
}

Let's define now the function that returns all the data in the SQLite database:

public List<Data> fetchData(){
    SQLiteDatabase db = this.getWritableDatabase();
    Cursor cursor = db.rawQuery("SELECT (weight, height, age, gender, bmi) FROM " + TABLE_NAME, null);
    List<Data> data = new ArrayList<Data>();
    if(cursor.moveToFirst()){
        do {
            data.add(new Data(cursor.getString(1), cursor.getString(2), cursor.getString(3), cursor.getString(4), cursor.getString(5)))
        }while(cursor.moveToNext())
    }
    cursor.close()
    return data;
}

Now, to insert data insiede you ListView, defined in the layout of fragment_history , let's suppose that the ListView in the xml file, has the id list_view , and that you defined a custom layout for each item, named list_item (used to show an instance of Data). The last step is to create an adapter , and link data from the database and the adapter, for example in this way:

// onViewCreated of fragment_history
@Override
public void onViewCreated(@NonNull View view, Bundle savedInstanceState) {
    ListView lw = view.findViewById(R.id.list_view);
    MyDatabaseHelper myDB = new MyDatabaseHelper(getActivity());
    List<Data> data = myDB.fetchData();
    ArrayAdapter<Data> adapter = new ArrayAdapter<>(getActivity(), R.layout.list_item, data);
    lw.setAdapter(adapter);
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM