60565

How to stop GridView from loading again when I press back button?

I created an Android application with Two Fragment, <strong>MainFragment</strong> --> <strong>WebviewFragment</strong>. The MainFragment is GridView which fetch the Grid Item from <strong>Json</strong> link. When I navigate back from <strong>WebviewFragment</strong> to <strong>MainFragment</strong> by pressing the back button, the Gridview fetches the data again. Is there any solution for this?

MainFragment

public class MainFragment extends Fragment { // Log tag private static final String TAG = MainActivity.class.getSimpleName(); // Movies json url private static final String url = "http://api...."; private ProgressDialog pDialog; private List<Movie> movieList; private GridView gridView; private TextView scrollingtext; private AppController appController; @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { movieList = new ArrayList<Movie>(); View view = inflater.inflate(R.layout.main_fragment, container, false); scrollingtext = (TextView) view.findViewById(R.id.scroll_annouc); scrollingtext.setSelected(true); gridView = (GridView) view.findViewById(R.id.Grid_view); final CustomListAdapter adapter = new CustomListAdapter(getActivity(), movieList); gridView.setAdapter(adapter); gridView.setOnItemClickListener(new AdapterView.OnItemClickListener() { @Override public void onItemClick(AdapterView<?> parent, View view, int position, long id) { Bundle bundle = new Bundle(); bundle.putString("LINK","http://www.kalerkantho.com/"); Fragment newFragment = new WebviewFragment(); FragmentTransaction transaction = getFragmentManager().beginTransaction(); newFragment.setArguments(bundle); transaction.replace(R.id.main_fragment_container, newFragment); transaction.addToBackStack(null); transaction.commit(); } }); pDialog = new ProgressDialog(getActivity()); // Showing progress dialog before making http request pDialog.setMessage(" Loading ..."); pDialog.show(); // Creating volley request obj JsonArrayRequest movieReq = new JsonArrayRequest(url, new Response.Listener<JSONArray>() { @Override public void onResponse(JSONArray response) { Log.d(TAG, response.toString()); hidePDialog(); // Parsing json for (int i = 0; i < response.length(); i++) { try { JSONObject obj = response.getJSONObject(i); Movie movie = new Movie(); movie.setTitle(obj.getString("title")); movie.setThumbnailUrl(obj.getString("image")); // adding movie to movies array movieList.add(movie); } catch (JSONException e) { e.printStackTrace(); } } // notifying list adapter about data changes // so that it renders the list view with updated data adapter.notifyDataSetChanged(); } }, new Response.ErrorListener() { @Override public void onErrorResponse(VolleyError error) { VolleyLog.d(TAG, "Error: " + error.getMessage()); hidePDialog(); } }); // Adding request to request queue appController.getInstance().addToRequestQueue(movieReq); return view; } @Override public void onDestroy() { super.onDestroy(); hidePDialog(); } private void hidePDialog() { if (pDialog != null) { pDialog.dismiss(); pDialog = null; } }

WebviewFragment

public class WebviewFragment extends Fragment { WebView webView; String newslink; @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { View view = inflater.inflate(R.layout.fragment_webview,container,false); newslink = getArguments().getString("LINK"); webView = (WebView) view.findViewById(R.id.webView); webView.loadUrl(newslink); webView.getSettings().setJavaScriptEnabled(true); return view; } } }

Answer1:

You can use SharedPreferences to keep a flag of whether or not you already loaded the data and then check this flag whenever you switch between fragments.

You should also keep the data in either SharedPreferences as well if your flag is active or maintain an internal database and load that instead of transforming your JSON again.

Answer2:

You can done this by using Fragment. Making your main content parent layout as Framelayout and inflate the Webview when pressing a button or what you want by using the command fragment.add and when backpress just use fragment.remove.

Answer3:

inflated view wouldn't be null when you popback. so just inflate view when you replace Fragment

@Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { if (view ==null){//null means fragment replaced and not null means popbacked View view = inflater.inflate(R.layout.main_fragment, container, false); init(); } return view; } private void init() { scrollingtext = (TextView) view.findViewById(R.id.scroll_annouc); scrollingtext.setSelected(true); gridView = (GridView) view.findViewById(R.id.Grid_view); final CustomListAdapter adapter = new CustomListAdapter(getActivity(), movieList); gridView.setAdapter(adapter); gridView.setOnItemClickListener(new AdapterView.OnItemClickListener() { @Override public void onItemClick(AdapterView<?> parent, View view, int position, long id) { Bundle bundle = new Bundle(); bundle.putString("LINK", "http://www.kalerkantho.com/"); Fragment newFragment = new WebviewFragment(); FragmentTransaction transaction = getFragmentManager().beginTransaction(); newFragment.setArguments(bundle); transaction.replace(R.id.main_fragment_container, newFragment); transaction.addToBackStack(null); transaction.commit(); } }); pDialog = new ProgressDialog(getActivity()); // Showing progress dialog before making http request pDialog.setMessage(" Loading ..."); pDialog.show(); // Creating volley request obj JsonArrayRequest movieReq = new JsonArrayRequest(url, new Response.Listener<JSONArray>() { @Override public void onResponse(JSONArray response) { Log.d(TAG, response.toString()); hidePDialog(); // Parsing json for (int i = 0; i < response.length(); i++) { try { JSONObject obj = response.getJSONObject(i); Movie movie = new Movie(); movie.setTitle(obj.getString("title")); movie.setThumbnailUrl(obj.getString("image")); // adding movie to movies array movieList.add(movie); } catch (JSONException e) { e.printStackTrace(); } } // notifying list adapter about data changes // so that it renders the list view with updated data adapter.notifyDataSetChanged(); } }, new Response.ErrorListener() { @Override public void onErrorResponse(VolleyError error) { VolleyLog.d(TAG, "Error: " + error.getMessage()); hidePDialog(); } }); // Adding request to request queue appController.getInstance().addToRequestQueue(movieReq); }

Answer4:

You can also use setRetainInstance(true); in MainFragment which will keep the instance state.

Hope this helps.

Recommend

  • Keeping MasterTableView row selected in SplitViewController
  • can't set JPanel color and JRadioButton invisibility
  • Android View setActive, setSelected and RecyclerView States
  • UICollectionView Enable deselecting cells while allowsMultipleSelection is disabled
  • from sqlite onListItemClick NullPointerException
  • how can i correctly parse a text file delimited by white space
  • ListView with the fixed number of items to display
  • Highlight ListView item at creation time via code
  • Setting spinner text color programmatically lags, is slow, is wrong color for split second
  • C++ equivalent of Java's andThen() function to composite new function
  • Accessing static field in annotation
  • Android: Attempt to invoke virtual method 'void android.widget.ListView.setAdapter(android.widg
  • How can i attach an listener to listview?
  • How can we trace push notifications being sent to the Apple APNS server from IBM MobileFirst 7.0?
  • How to paginate a Firebase Recyclerview
  • Android - dlopen failed: file offset for the library
  • How to know when data is loaded inside custom RecyclerView?
  • Using @Before aspect on @Controller methods with Spring doesn't work
  • RecyclerView Dynamic Header
  • Android ListFragment update/refresh and onItemClick
  • How to use getFilter form Listadapter
  • PXAction seemingly does nothing
  • How Can I Prevent Activation For Some ListView Items When The Selection Mode Is MultiChoiceModal?
  • BizTalk Party not being resolved for incoming HL7v2 message
  • How to Handle Click on Imageview in Custom Listview with image and Textview?
  • Android: How do you create an EditText field in java class
  • Unicorn and Rails eat up 2x MySQL connections
  • CloseOptionsMenu doesn't work?
  • Unable to resolve Static method?
  • Should I or shouldn't I use the CachingConnectionFactory with hornetq 2.4.1
  • Can I have the cursor start on a particular column by default in jqgrid's edit mode?
  • jquery mobile loadPage not working
  • How to delete a row from a dynamic generate table using jquery?
  • json Serialization in asp
  • Rails 2: use form_for to build a form covering multiple objects of the same class
  • How to stop GridView from loading again when I press back button?
  • Bitwise OR returns boolean when one of operands is nil
  • sending mail using smtp is too slow
  • costura.fody for a dll that references another dll
  • Binding checkboxes to object values in AngularJs