I have different activities and each activity have some fragments except main activity. All these fragments contains some switch buttons that operates some electrical appliances, this is an IOT based home automation App. The main activity has a speech recognition module that listens voice command through which a user can ON/OFF the switch buttons using voice commands and I want that from the main activity I can control all the switch buttons located on the fragments of different activities. How can I do this, can I pass a data from main activity to the fragment of other activity so that I can operates the switch buttons from main activity? Can anyone please do me a favor and write a code so that I can pass a data from main activity to the fragment named “BedRoomFanFragment” that is a fragment of activity named “BedRoomActivity”. Please help me thanks.
This is my Main activity from where i want to post data
switch (requestCode) {
case 10:
if (resultCode == RESULT_OK && data != null) {
ArrayList<String> result = data.getStringArrayListExtra(RecognizerIntent.EXTRA_RESULTS);
txvResult.setText(result.get(0));
String dat;
dat = txvResult.getText().toString();
if(dat.equals("on")){
T.setText("ON");
// when user says "on" it posts data to BedRoomFanFragment
}
else if(dat.equals("off")){
T.setText("OFF");
}
else{}
}
break;
}
}
And this is my fragment from where i want to receive data to turn the BedFan1 switch button ON
public class BedRoomFanFragment extends Fragment {
SwitchCompat BedFan1;
public static final String SHARED_PREFS = "sharedprefs";
public static final String BEDFAN1 = "bedfan1";
private boolean switchChange;
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment_bed_room_fan, container, false);
BedFan1=(SwitchCompat) rootView.findViewById(R.id.bedFan1);
loadData();
updateViews();
BedFan1.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
@Override
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
SharedPreferences sharedPreferences = getActivity().getSharedPreferences(SHARED_PREFS, MODE_PRIVATE);
SharedPreferences.Editor editor = sharedPreferences.edit();
editor.putBoolean(BEDFAN1,BedFan1.isChecked());
editor.apply();
if(!isChecked){
((BedRoomActivity)getActivity()).sendData("x");
}else if(isChecked){
((BedRoomActivity)getActivity()).sendData("y");
}
}
});
return rootView;
}
public void loadData(){
SharedPreferences sharedPreferences = getActivity().getSharedPreferences(SHARED_PREFS, MODE_PRIVATE);
switchChange = sharedPreferences.getBoolean(BEDFAN1, false);
}
public void updateViews(){
BedFan1.setChecked(switchChange);
}
}