0

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

}
}
Raza Ellahi
  • 379
  • 2
  • 7
  • 20

1 Answers1

1

Create interface and add them to a list and while posting data send to all instance of interface. While as this is an IOT/M2M app you should focus on logic rather than passing data to views.there are awesome libraries(Otto,Eventbus) which makes it very easy to manage.

Below example is of Otto .In your fragment subscribe for event and in your Activity post your event .

public class BedRoomFanFragment extends Fragment {
    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
        Bundle savedInstanceState) {
        // Inflate the layout for this fragment
        return inflater.inflate(R.layout.article_view, container, false);
bus.register(getActivity());
    }


//this method will get called when you post an event from activity 
@Subscribe public void homeApplianceEvent(int event) {
    // TODO: React to the event somehow!
         if(event == 0){
           Log.d(“OFF”)
           }
         if(event == 1){
          Log.d(“ON”)
           }
      }


Public class MainActivity extends Activity{
//this is an example but create a singleton
Bus bus = new Bus();
final int OFF =0;
final int ON = 1;

/** Called when the activity is first created. */
   @Override
   public void onCreate(Bundle savedInstanceState) {
      super.onCreate(savedInstanceState);
      setContentView(R.layout.activity_main);
      Log.d(msg, "The onCreate() event");
      //post event like this
      //this is to switch OFF
     bus.post(OFF);
   }
}

Also applicable if you want to post event from fragment and subscribe them in Activity.

Godfather
  • 833
  • 9
  • 14
  • Sir i appreciate your idea of using Otto library, now i add my code to question please guide me that how the main activity knows that it have to send data to a specific fragment. – Raza Ellahi Jun 19 '18 at 09:52
  • its publisher and subscriber model using annotation.This was just an example ,Instead of sending event integer you can create a POJO with other property which tells you source and destination as well .In addition to this also keep in mind you can subscribe and unsubscribe according to your need . – Godfather Jun 19 '18 at 18:40