Search code examples
androidandroid-fragmentsandroid-activitymodel

get Multiple data from model using fragment


How am I going to retrieve multiple data at once from Activity to Fragment?

I'm using a model, Currently I only have 1 textview and what i've done to transfer data is to use the function from MainActivity in my Fragment with a return value, and that won't allow me to gather multiple data at once.

How can I set and use a function on my fragment that will get multiple data on my model.

I don't have database right now too . but I will build it later.

codes below, Hope you understand :D T.I.A.

Codes:

// Main Activity
protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        infoFrag = new InformationFragment();
        bldgInformation = new BldgInformation();
        bldgName = getIntent().getStringExtra("BLDG");
        bldgInformationSet();

//Function 

    public void bldgInformationSet(){
        bldgInformation.setBldgName(bldgName);

    }

    public String bldgInformationGet(){
        bldgInformation.getBldgName();
        return bldgName;
    }


// Model
public class BldgInformation {

    private int bldgID; // Planning to use ID after I create database,
    private String bldgName;

    public int getBldgID() {
        return bldgID;
    }

    public void setBldgID(int bldgID) {
        this.bldgID = bldgID;
    }

    public String getBldgName() {
        return bldgName;
    }

    public void setBldgName(String bldgName) {
        this.bldgName = bldgName;
    }
}



// Fragment

public class InformationFragment extends Fragment {
    private static final String TAG = "InformationFragment";

    private TextInputEditText bi_name;
    private MainActivity mainActivity;

 public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.information_fragment,container,false);

        bi_name = (TextInputEditText)view.findViewById(R.id.info_bldg_name);
        mainActivity = (MainActivity) getActivity();
        bi_name.setText(mainActivity.bldgInformationGet());

        return view;

Solution

  • Try something like this instead :

    On fragment:

    mainActivity.bldgInformationFill(bi_name,bi_id);
    

    On Activity :

     public void bldgInformationFill(TextView bi_name,TextView bi_id){
           bi_name.setText(bldgInformation.getBldgName());
           bi_id.setText(String.valueOf(bldgInformation.getBldgID()));
        }