Getting data from json once and use it in 3 fragme

2019-07-18 02:56发布

问题:

I am getting the data from JSON using volley, there is 3 Fragment in Activity which I have to populate these fragments with the data that I have received from JSON in MainActivity. I would like to get data from JSON once and use it in Activity and in all those 3 Fragment. I put the received data in a List like this:

List<Display_Activity_Model> videoDetailList;

and I send this list from activity to other fragments using an Interface like:

In activity I have this method:

@Override
public List<Display_Activity_Model> getDataList() {
    return videoDetailList;
}

In one of fragments I have:

public interface GetDataInterface {
    List<Display_Activity_Model> getDataList();
}
@Override
public void onAttach(Context context) {
    super.onAttach(context);
    try {
        sGetDataInterface= (GetDataInterface) context;
    } catch (ClassCastException e) {
        throw new ClassCastException(context.toString() + "must implement GetDataInterface Interface");
    }
}

@Override
public void onResume() {
    super.onResume();
    if(sGetDataInterface != null){
        dataListFromDispAct = sGetDataInterface.getDataList();
    }
}

When I debug the code, I see that the method getDataList in MainActivity is called before the method for fetching json with volley. So all the time I receive empty list.

My question is that: What is the best way to fetch data with volley once and use it in other fragments?

Update1:

@Keita Junichiro:

I defined "update" method in fragment like:

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

    initComponents(view);

   if (dataListFromDispAct != null) {
        txt_view_count.setText(dataListFromDispAct.get(0).getView_count());
    }

    return view;
}

public void update(List<Display_Activity_Model> videoDetailList){

    dataListFromDispAct=videoDetailList;

}

and I am calling "update" method in activity after json loaded in "getItemMenuGson" method:

getItemMenuGson(new CallBack() {
        @Override
        public void onSuccess(List<Display_Activity_Model> itemMenuGsonList) {
            videoDetailList=itemMenuGsonList;
            new Video_Info().update(videoDetailList);

        }

        @Override
        public void onFail(String msg) {

        }
    });

The problem is method "onCreateView" in fragment is called before update method. When I declare update method static it is also the same and variable "dataListFromDispAct" is null all the time.

Update2:

Update 3: @Piyush

I implemented your respond, but it is not working in this problem. I am getting empty list because method onCreateView executing earlier than getItemMenuGson method in Activity. I declared :

SharedApplication mapp = SharedApplication.getInstance();
ArrayList<String> myList = mapp.getArrayListData();

in onActivityCreated in fragment but it is also running before getItemMenuGson method in Activity. The order in which methods are calling:

what should I do? How can I call getItemMenuGson method in Activity to fetch JSON and then load fragment layout to populate those loaded data to the fragment?

Solution: The key for the problem was Static method which runs first:

Define below codes in Fragment:

public class Video_Info extends Fragment {

static TextView txt_view_count;
List<Display_Activity_Model> dataListFromDispAct;


@Nullable
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) 
  {
    View view=inflater.inflate(R.layout.video_info,container,false);
    txt_view_count= (TextView) view.findViewById(R.id.txt_view_count);
    return view;
  }
public static void update(List<Display_Activity_Model> videoDetailList)
  {
    txt_view_count.setText(videoDetailList.get(0).getView_count());
  }
 }

In Activity after fetching data from JSON to list call update method:

 getItemMenuGson(new CallBack() {
    @Override
    public void onSuccess(List<Display_Activity_Model> itemMenuGsonList) {
        videoDetailList = itemMenuGsonList;

         //////////////////
        Video_Info.update(videoDetailList);
        ///////////////////

        Uri vidUri = Uri.parse(itemMenuGsonList.get(0).getMedia().getURL());
        vidView.setVideoURI(vidUri);

    }

回答1:

In order to send data from activity to fragment after call API, you can create a method update() in fragment to receive data and call fragment.update() in activity when loadData finish().

new Response.Listener<JSONObject>() {
    @Override
    public void onResponse(JSONObject response) {
        //Parse resonse to *videoDetailList*
        fragment.update(videoDetailList);
    }
}


回答2:

First make one singletone application class

public class SharedApplication extends Application{

ArrayList<String> arraylist;

public static SharedApplication instance=null;

@Override
public void onCreate() {
    // TODO Auto-generated method stub
    super.onCreate();
}

public static SharedApplication getInstance()
{
    if(instance==null)
    {
        instance=new SharedApplication();
    }
    return instance;
}

public void setArrayListData(ArrayList<String> setData)
{
    arraylist=setData;
}

public ArrayList<String> getArrayListData()
{
    return arraylist;

}

}

Now in your activity initialize your application class using

SharedApplication mApp; // declare global

initialize in onCreate() method

mApp = SharedApplication.getInstance();

Now after parse your data from server set data in arraylist

mApp.setArrayListData(yourArrayList);

Now whenever you want to get data any of fragment you should same initialize your application class in each fragment in which u want to get arraylist.

Like,

SharedApplication mapp = SharedApplication.getInstance();
ArrayList<String> myList = mapp.getArrayListData();

Note : You must add SharedApplication class in your manifest to application tag



回答3:

Make an interface with a method onDownloadComplete.

public interface DelegateClass {
    public static onDownloadComplete(String jsonData);
}

Now fetch data with Volley in Activity and call this method. Implement this interface in all your fragments and override onDownloadComplete. This method will be called when your Activity finishes fetching data. Like

public class YourFragment implements DelegateClass {
    ...
    ...
    @Override
    public static onDownloadComplete(String jsonData){
        //do what you want with data
    }
    ...
    ...
}

Hope it helps