Android studio, I am using the following to parse a videoid from a json file on my server.
public View onCreateView(@NonNull LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_radio, container, false);
YTApiResult = view.findViewById(R.id.APIResult);
String url = "https://myserver.com/example.json";
JsonObjectRequest jsonObjectRequest = new JsonObjectRequest
(Request.Method.GET, url, null, new Response.Listener<JSONObject>() {
@Override
public void onResponse(JSONObject response) {
try {
JSONArray jsonArray = response.getJSONArray("items");
for (int i = 0; i < jsonArray.length(); i ) {
JSONObject jsonObject = jsonArray.optJSONObject(i);
JSONObject jsonArray1 = jsonObject.getJSONObject("id");
String videoid = jsonArray1.optString("videoId");
initYouTubePlayerView(videoid);
YTApiResult.setText("STATUS: " videoid);
livevideoid=videoid;
}
} catch (JSONException e) {
e.printStackTrace();
}
}
}, new Response.ErrorListener() {
@Override
public void one rrorResponse(VolleyError error) {
// TODO: Handle error
}
});
MySingleton.getInstance(getActivity()).addToRequestQueue(jsonObjectRequest);
This all seems to work correctly. On app launch, the videoid is corretly pulled from my server's json file.
The issue I seem to be having is that the videoid from the json file only updates once, when the app is installed. If I update the videoid in the json file on my server, and then open the app (after initial install) it does not update the videoid.
If I then uninstall and reinstall the app, it will update - but not on every launch of the app.
I thought because it was in the OnCreate it would auto update the json videoid from the url on every open of the fragment page, but it doesn't seem to.
I have also tried using all the previous code in an onResume, which I know is getting called each time with log.d, but it still won't update without an app uninstall/reinstall. I assume I am missing some kind of code to maybe refresh the data, but I am very new to this.
public void onResume(){
super.onResume();
Log.d("testTag", "OnResume started");
So, my question is: How can I get this to update the videoid every time the app or fragment is opened?
CodePudding user response:
onCreate called once during the life cycle. If you want to update or refresh the data when screen in is focus you can try this with onStart method. Onstart and onresume called every time when the screen is in focus.
CodePudding user response:
Ok so the problem was not the onCreate, onCreateView, or onResume. The problem was my server was caching the json file so when I updated the json file on the server, the app was still pulling the old cached one.
My solution was to implement
String url = "https://myserver.com/example.json?_cache_buster=" new Date().getTime();
To add a date/time parameter to force it not to cache.