Thursday, March 3, 2016

Fragment communications with no Activty to bother u around in Android



I must say the task of interface implementations is no walking in a park, or perhaps walking that same park in middle of the night, with fear of irrevocable beaten up possibilities only to be garbage collected in the morning by a hobo. That being said it is very simple, once u understand the core procedures to make one (so is nuclear  rocket science, dah!).
 
follow these steps We have two fragments called AddFragmentand ListFragment, and upon adding an item on first fragment you want the updated list be shown on list fragment (what sort of sorcery is this!!!).
Step 1 create the listener interface on class level of AddFragment with a method that is going to be implemented by the other guy (ListFragment ) and create Interface type variable

public class AddFragment extends Fragment{
 //listener varriable

 //listener
  public interface OnCategoryAddedListener{
    public void refreshList();
}
 private static OnCategoryAddedListener meAddListener;
}
Step 2 create register method on class level of the same AddFragment class and set listenter variable
public class AddFragment extends Fragment{


public void registerListener(OnCategoryAddedListener listener)
{
    meAddListener = listener;
}
}
Step 3 upon any event cud be button click or yelling at ur application(that is considered rude event in android :-) ) check for listener object meAddListener variable and call the interface, in a Shakespeare’s nutshell it means “for thou who implement ye interface and brought the method within ur class shelter, I shall give u my utmost privilege and blessing to …. ”
Step 4 On ListFragment implement the AddFragment’s interface,no turning back just go implement its method. Within that method u just call abracadabra to repopulate ur list or any sort of updatable android view object… and ur done
public class ListFragment extends Fragment implements AddFragment.OnCattegoryAddedListener{
//refer to AddFragment
AddFragment addFragment;
ArrayAdapter<String>   catArrayAdapter;
//once the fragment is within the memory scope u instantiate AddFragment
//and register listener with AddFragment context which inherently implement OnCategoryAddedListener

@Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        categoryAddFragment = new CategoryAddFragment();
        categoryAddFragment.registerListener(this);

    }

@Override
public void onActivityCreated(Bundle savedInstanceState) {
    super.onActivityCreated(savedInstanceState);
    fillList();

}

public void fillList() {

    catArrayAdapter = new ArrayAdapter<>(context,android.R.layout.simple_list_item_1,getItems());
    setListAdapter(catArrayAdapter);

}
//le interface method u can count on to refresh ur list content
public void refreshList(){ 
catArrayAdapter.clear;
catArrayAdapter.addAll(getItems);
catArrayAdapter.notifyDataSetChanged();   
}