Listview items reloaded on fragment - android

In my app there is a fragment class (TabFragmentComerTiposRestaurante). It has also two tab fragments in it (Case 0: PrimaryFragmentComerTiposRestaurante, Case 1: SocialFragmentComerTiposRestaurante).
On both fragment classes there is a listview. When clicking on an item from this list, another fragment class is shown (PrimaryFragmentComer.
Shorty this the schema:
TabFragmentComerTiposRestaurante(#F1)
-[PrimaryFragmenComerTiposRestaurante](#F11)--[PrimaryFragmentComer](#F111)
-[SocialFragmentComerTiposRestaurante](#F12)--[SocialFragmentComer](#F121)
The issue I need to solve is the following:
If at (#F111) or at (#F121) the users click on the back button, then the listview items from #F11 and #F12 are loaded again. That means, if on the first #F11 call there is an item called "Cocina americana", then going back from #F111 to #F11 or going back from #F121 to #F12, there are now two equal items: First row=Cocina americana, Second row=Cocina americana. And that happens every time the user goes from #F11 or #F12 to #F111 or #F112.
Here you can find the code for
F1:
public class TabFragmentComerTiposRestaurante extends Fragment {
public static TabLayout tabLayout;
public static ViewPager viewPager;
public static int int_items = 2 ;
#Nullable
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
/**
*Inflate tab_layout and setup Views.
*/
View x = inflater.inflate(R.layout.tab_layout_tipo_rte,null);
tabLayout = (TabLayout) x.findViewById(R.id.tabs);
viewPager = (ViewPager) x.findViewById(R.id.viewpager);
/**
*Set an Apater for the View Pager
*/
viewPager.setAdapter(new MyAdapter(getChildFragmentManager()));
/**
* Now , this is a workaround ,
* The setupWithViewPager dose't works without the runnable .
* Maybe a Support Library Bug .
*/
tabLayout.post(new Runnable() {
#Override
public void run() {
tabLayout.setupWithViewPager(viewPager);
}
});
return x;
}
class MyAdapter extends FragmentPagerAdapter{
public MyAdapter(FragmentManager fm) {
super(fm);
}
/**
* Return fragment with respect to Position .
*/
#Override
public Fragment getItem(int position)
{
switch (position){
case 0 : return new PrimaryFragmentComerTiposRestaurante();
case 1 : return new SocialFragmentComerTiposRestaurante();
}
return null;
}
#Override
public int getCount() {
return int_items;
}
/**
* This method returns the title of the tab according to the position.
*/
#Override
public CharSequence getPageTitle(int position) {
switch (position){
case 0 :
return "CIUDAD JUAREZ";
case 1 :
return "EL PASO";
}
return null;
}
}
}
Code for #F11
public class PrimaryFragmentComerTiposRestaurante extends Fragment implements AdapterView.OnItemClickListener {
private OnFragmentInteractionListener mListener;
// Log tag
private static final String TAG = MainActivity.class.getSimpleName();
// Movies json url
private static final String url = "..hiddene here";
private ProgressDialog pDialog;
private List<TipoRestaurante> tipoRestauranteList = new ArrayList<TipoRestaurante>();
private ListView listView;
private CustomListAdapterTipoRte adapter;
#Nullable
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
return inflater.inflate(R.layout.primary_layout_tiporte, null);
}
#Override
public void onActivityCreated(Bundle state) {
super.onActivityCreated(state);
listView = (ListView) getView().findViewById(R.id.list);
adapter = new CustomListAdapterTipoRte (getActivity(), tipoRestauranteList);
listView.setAdapter(adapter);
listView.setOnItemClickListener(this);
pDialog = new ProgressDialog(getActivity());
// Showing progress dialog before making http request
pDialog.setMessage("Procesando tipos..");
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();
Log.d("estoy aqui","estoy");
// Parsing json
for (int i = 0; i < response.length(); i++) {
try {
JSONObject obj = response.getJSONObject(i);
TipoRestaurante restaurante = new TipoRestaurante();
restaurante.setId_tipo(obj.getInt("id_tipo"));
restaurante.setNombre_tipo(obj.getString("nombre_tipo"));
restaurante.setFoto_tipo(obj.getString("foto_tipo"));
Log.d(TAG, response.toString());
// adding movie to movies array
tipoRestauranteList.add(restaurante);
pDialog = new ProgressDialog(getActivity());
pDialog.setMessage(obj.optString("id_tipo"));
// pDialog.show();
} 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);
}
#Override
public void onDestroy() {
super.onDestroy();
hidePDialog();
}
private void hidePDialog() {
if (pDialog != null) {
pDialog.dismiss();
pDialog = null;
}
}
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
TipoRestaurante rteActual = (TipoRestaurante) adapter.getItem(position);
String msg = "Has elegido el tipo " + rteActual.getNombre_tipo();
Toast.makeText(getActivity(), msg, Toast.LENGTH_LONG).show();
Fragment newFragment = new PrimaryFragmentComer();
Bundle args = new Bundle();
args.putInt("myIntLabel", 2);
args.putString("myStringLabel", rteActual.getNombre_tipo());
//and you can add all you want to that bundle like this
newFragment.setArguments(args);
if (mListener != null) {
mListener.onFragmentInteraction(newFragment);
}
}
#Override
public void onAttach(Activity activity) {
super.onAttach(activity);
try {
mListener = (OnFragmentInteractionListener) activity;
} catch (ClassCastException e) {
throw new ClassCastException(activity.toString()
+ " must implement OnFragmentInteractionListener");
}
}
#Override
public void onDetach() {
super.onDetach();
mListener = null;
}
public interface OnFragmentInteractionListener {
void onFragmentInteraction(Fragment fragment);
}
}
And now code for #F111:
public class PrimaryFragmentComer extends Fragment implements AdapterView.OnItemClickListener {
// Log tag
private static final String TAG = MainActivity.class.getSimpleName();
// Movies json url
private static final String url = "...hidden here";
private ProgressDialog pDialog;
private List<Restaurante> restauranteList = new ArrayList<Restaurante>();
private ListView listView;
private CustomListAdapterRte adapter;
#Nullable
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
return inflater.inflate(R.layout.primary_layout_comer, null);
}
#Override
public void onActivityCreated(Bundle state) {
super.onActivityCreated(state);
Bundle args = getArguments();
String hola = args.getString("myStringLabel");
Log.d("TIPO RTE", hola);
listView = (ListView) getView().findViewById(R.id.list);
adapter = new CustomListAdapterRte (getActivity(), restauranteList);
listView.setAdapter(adapter);
listView.setOnItemClickListener(this);
pDialog = new ProgressDialog(getActivity());
// Showing progress dialog before making http request
pDialog.setMessage("Procesando restaurantes...");
pDialog.show();
// Creating volley request obj
JsonArrayRequest movieReq = new JsonArrayRequest(url+hola,
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);
Restaurante restaurante = new Restaurante();
restaurante.setId_rte(obj.getInt("id_rte"));
restaurante.setNombre(obj.getString("nombre_rte"));
restaurante.setDescripcion(obj.getString("descripcion_rte"));
restaurante.setLatitud(obj.getDouble("latitud_rte"));
restaurante.setLongitud(obj.getDouble("longitud_rte"));
restaurante.setDireccion(obj.getString("direccion_rte"));
restaurante.setWeb(obj.getString("web_rte"));
restaurante.setTel_rte(obj.getString("tel_rte"));
restaurante.setTel_reservas(obj.getString("tel_reservas"));
restaurante.setFoto(obj.getString("foto_rte"));
restaurante.setCalificacion(obj.getDouble("calificacion_rte"));
restaurante.setTipo_rte(obj.getString("tipo_rte"));
restaurante.setFacebook(obj.getString("facebook_rte"));
restaurante.setTwitter(obj.getString("google_rte"));
restaurante.setZona(obj.getString("zona_rte"));
restaurante.setCiudad(obj.getInt("ciudad"));
restaurante.setPoi(obj.getInt("poi"));
// adding movie to movies array
restauranteList.add(restaurante);
pDialog = new ProgressDialog(getActivity());
pDialog.setMessage(obj.optString("id_rte"));
// pDialog.show();
} 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);
}
#Override
public void onDestroy() {
super.onDestroy();
hidePDialog();
}
private void hidePDialog() {
if (pDialog != null) {
pDialog.dismiss();
pDialog = null;
}
}
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
Restaurante rteActual = (Restaurante) adapter.getItem(position);
String msg = "Elegiste el restaurante " + rteActual.getNombre();
Toast.makeText(getActivity(), msg, Toast.LENGTH_LONG).show();
Intent intent = new Intent(getActivity(), Detalle_Restaurante.class);
intent.putExtra("id_rte", rteActual.getId_rte());
intent.putExtra("nombre_rte", rteActual.getNombre());
intent.putExtra("descripcion_rte", rteActual.getDescripcion());
intent.putExtra("latitud_rte", rteActual.getLatitud());
intent.putExtra("longitud_rte", rteActual.getLongitud());
intent.putExtra("direccion_rte", rteActual.getDireccion());
intent.putExtra("web_rte", rteActual.getWeb());
intent.putExtra("tel_rte", rteActual.getTel_rte());
intent.putExtra("tel_reservas", rteActual.getTel_reservas());
intent.putExtra("foto_rte", rteActual.getFoto());
intent.putExtra("calificacion_rte", rteActual.getCalificacion());
intent.putExtra("tipo_rte", rteActual.getTipo_rte());
intent.putExtra("facebook_rte", rteActual.getFacebook());
intent.putExtra("google_rte", rteActual.getTwitter());
intent.putExtra("zona_rte", rteActual.getZona());
intent.putExtra("ciudad_rte", rteActual.getCiudad());
intent.putExtra("poi_rte", rteActual.getPoi());
startActivity(intent);
}
}

As mentioned in the comment,
Data is being readded to tipoRestauranteList in your onResponse() method so to avoid that write tipoRestauranteList.clear() after hidePDialog().
Same will be happening in your #F12. Doing this you can rectify the same. :)

Related

Empty Bundle in the onSaveInstanceState method

I display pictures from moviesdb using volley in a gridview. The next step is have that gridview in the landscape mode too. So my logic behind this,is to store the list that contains the data as key value pair inside the onSaveInstantState method as:
#Override
public void onSaveInstanceState(Bundle outState) {
super.onSaveInstanceState(outState);
outState.putParcelableArrayList("movies", moviesList);
outState.putStringArrayList("images", images);
Log.v("TAG","list size:" + moviesList.size());
}
The log output gives me a size of 20 which is correct. However when I am using the debugger, the line
outState.putParcelableArrayList("movies", moviesList);
gives me an empty bundle. That's very strange! The images list works fine,and can see what's in there. Any ideas what is wrong?
Here is my code.
public class MainFragment extends Fragment {
String BASE_URL = "http://api.themoviedb.org/3/discover/movie?api_key=my_key";
static public ArrayList<Movie> moviesList;
static public ArrayList<String> images;
static public MovieAdapter movieAdapter;
public static String imageIcon;
ImageView imageView;
static public String lastSortOrder;
static GridView gridview;
public MainFragment() {
// Required empty public constructor
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
if(savedInstanceState != null) {
moviesList = savedInstanceState.getParcelableArrayList("movies");
images = savedInstanceState.getStringArrayList("images");
}else{
moviesList = new ArrayList<>();
images = new ArrayList<>();
movieAdapter = new MovieAdapter(getActivity());
updateMovies();
}
super.onCreate(savedInstanceState);
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
View rootView = inflater.inflate(R.layout.fragment_main, container, false);
setHasOptionsMenu(true);
moviesList = new ArrayList<>();
images = new ArrayList<>();
gridview = (GridView) rootView.findViewById(R.id.gridview);
int ot = getResources().getConfiguration().orientation;
gridview.setNumColumns(ot == Configuration.ORIENTATION_LANDSCAPE ? 3 : 2);
gridview.setAdapter(movieAdapter);
return rootView;
}
private void updateMovies(){
JsonObjectRequest jsonObjReq = new JsonObjectRequest(Method.GET,
BASE_URL,
new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject response) {
Log.d("TAG", response.toString());
try {
JSONArray moviesArray = response.getJSONArray("results");
for (int i = 0; i < moviesArray.length(); i++) {
JSONObject movie = moviesArray.getJSONObject(i);
Movie movieItem = new Movie();
movieItem.setTitle(movie.getString("title"));
movieItem.setId(movie.getInt("id"));
movieItem.setBackdrop_path(movie.getString("backdrop_path"));
movieItem.setOriginal_title(movie.getString("original_title"));
movieItem.setOriginal_language(movie.getString("original_language"));
if (movie.getString("overview") == "null") {
movieItem.setOverview("No Overview was Found");
} else {
movieItem.setOverview(movie.getString("overview"));
}
if (movie.getString("release_date") == "null") {
movieItem.setRelease_date("Unknown Release Date");
} else {
movieItem.setRelease_date(movie.getString("release_date"));
}
movieItem.setPopularity(movie.getString("popularity"));
movieItem.setVote_average(movie.getString("vote_average"));
movieItem.setPoster_path(movie.getString("poster_path"));
if (movie.getString("poster_path") == "null") {
movieItem.setPoster_path(API.IMAGE_NOT_FOUND);
} else {
images.add(API.IMAGE_URL + API.IMAGE_SIZE_185 + movie.getString("poster_path"));
}
moviesList.add(movieItem);
Log.v("TAG","list size:" + moviesList.size());
movieAdapter.notifyDataSetChanged();
}
} catch (JSONException e) {
e.printStackTrace();
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
}
});
// Adding request to request queue
AppController.getInstance().addToRequestQueue(jsonObjReq);
}
#Override
public void onSaveInstanceState(Bundle outState) {
super.onSaveInstanceState(outState);
outState.putParcelableArrayList("movies", moviesList);
outState.putStringArrayList("images", images);
//Log.v("TAG","list size:" + moviesList.size());
}
}
Thanks,
Theo.

how to use both Swipe List Adapter and Scroll List Adapter at the listview

I'm developing an android application that have the Swipe List function found Here and now i have add a fast scroll function to the list view that found here
Here is my code :
public class HomeList extends Fragment implements
SwipeRefreshLayout.OnRefreshListener {
private String TAG = HomeList.class.getSimpleName();
private String URL_TOP_250 = "http://api.androidhive.info/json/imdb_top_250.php?offset=";
private SwipeRefreshLayout swipeRefreshLayout;
private ListView listView;
private SwipeListAdapter adapter;
private List<Movie> movieList;
// initially offset will be 0, later will be updated while parsing the json
private int offSet = 0;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
View rootView = inflater.inflate(R.layout.activity_home_list,
container, false);
listView = (ListView) rootView.findViewById(R.id.listView);
listView.setFastScrollEnabled(true);
swipeRefreshLayout = (SwipeRefreshLayout) rootView
.findViewById(R.id.swipe_refresh_layout);
movieList = new ArrayList<>();
adapter = new SwipeListAdapter(getActivity(), movieList);
listView.setAdapter(adapter);
swipeRefreshLayout.setOnRefreshListener(this);
/**
* Showing Swipe Refresh animation on activity create As animation won't
* start on onCreate, post runnable is used
*/
swipeRefreshLayout.post(new Runnable() {
#Override
public void run() {
swipeRefreshLayout.setRefreshing(true);
fetchMovies();
}
});
listView.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
Intent i = new Intent(getActivity(), AddMain.class);
startActivity(i);
}
});
FrameLayout footerLayout = (FrameLayout) getActivity()
.getLayoutInflater().inflate(R.layout.footerview, null);
Button btnPostYourEnquiry = (Button) footerLayout
.findViewById(R.id.btnGetMoreResults);
btnPostYourEnquiry.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
Intent i = new Intent(getActivity(), AddMain.class);
startActivity(i);
}
});
listView.addFooterView(footerLayout);
return rootView;
}
/**
* This method is called when swipe refresh is pulled down
*/
#Override
public void onRefresh() {
fetchMovies();
}
/**
* Fetching movies json by making http call
*/
private void fetchMovies() {
// showing refresh animation before making http call
swipeRefreshLayout.setRefreshing(true);
// appending offset to url
String url = URL_TOP_250 + offSet;
// Volley's json array request object
JsonArrayRequest req = new JsonArrayRequest(url,
new Response.Listener<JSONArray>() {
#Override
public void onResponse(JSONArray response) {
Log.d(TAG, response.toString());
if (response.length() > 0) {
// looping through json and adding to movies list
for (int i = 0; i < response.length(); i++) {
try {
JSONObject movieObj = response
.getJSONObject(i);
int rank = movieObj.getInt("rank");
String title = movieObj.getString("title");
Movie m = new Movie(rank, title);
movieList.add(0, m);
// updating offset value to highest value
if (rank >= offSet)
offSet = rank;
} catch (JSONException e) {
Log.e(TAG,
"JSON Parsing error: "
+ e.getMessage());
}
}
adapter.notifyDataSetChanged();
}
// stopping swipe refresh
swipeRefreshLayout.setRefreshing(false);
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Log.e(TAG, "Server Error: " + error.getMessage());
Toast.makeText(getActivity(), error.getMessage(),
Toast.LENGTH_LONG).show();
// stopping swipe refresh
swipeRefreshLayout.setRefreshing(false);
}
});
// Adding request to request queue
MyApplication.getInstance().addToRequestQueue(req);
}
class MyListAdaptor extends ArrayAdapter<String> implements SectionIndexer {
HashMap<String, Integer> alphaIndexer;
String[] sections;
public MyListAdaptor(Context context, LinkedList<String> items) {
super(context, R.layout.scrol, items);
alphaIndexer = new HashMap<String, Integer>();
int size = items.size();
for (int x = 0; x < size; x++) {
String s = items.get(x);
// get the first letter of the store
String ch = s.substring(0, 1);
// convert to uppercase otherwise lowercase a -z will be sorted
// after upper A-Z
ch = ch.toUpperCase();
if (!alphaIndexer.containsKey(ch))
alphaIndexer.put(ch, x);
}
Set<String> sectionLetters = alphaIndexer.keySet();
// create a list from the set to sort
ArrayList<String> sectionList = new ArrayList<String>(
sectionLetters);
Collections.sort(sectionList);
sections = new String[sectionList.size()];
sectionList.toArray(sections);
}
public int getPositionForSection(int section) {
return alphaIndexer.get(sections[section]);
}
public int getSectionForPosition(int position) {
return 0;
}
public Object[] getSections() {
return sections;
}
}
}
I doesn't know how to combine both adapter, can someone help me?

ListView not shown when trying to go back

I have tested my app with the emulator and everything works as expected. now im debugging the app via usb debugging. This is when i get this issue. I have a ListView in my app. When the user press a List Item it starts a new activity. My issue is, after the user press the back button, the ListView is not generated again. I just a blank activity.Even if i restart the app, when i go to the activity that contains the ListView, it wont generate the ListView. The only way to fix this is to clear the data of my application via my phone settings. What is causing this issue? Why is it working well with the emulator and not with my phone? (Im using a Xiaomi Mi4) any help would be much appreciated.
CustomListAdapter
public class CustomListAdapter extends BaseAdapter {
private Activity activity;
private LayoutInflater inflater;
private List<Guide> guideItems;
public CustomListAdapter(Activity activity, List<Guide> guideItems) {
this.activity = activity;
this.guideItems = guideItems;
}
#Override
public int getCount() {
return guideItems.size();
}
#Override
public Object getItem(int location) {
return guideItems.get(location);
}
#Override
public long getItemId(int position) {
return position;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
inflater = (LayoutInflater) activity.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
convertView = inflater.inflate(R.layout.customrow, parent, false);
TextView ngno = (TextView) convertView.findViewById(R.id.txt_ListNgno);
TextView name = (TextView) convertView.findViewById(R.id.txt_ListName);
TextView email = (TextView) convertView.findViewById(R.id.txt_ListEmail);
// getting movie data for the row
Guide g = guideItems.get(position);
ngno.setText(g.getNgno());
name.setText(g.getName());
email.setText(g.getEmail());
return convertView;
}
}
This is the activity that implements the ListView.
public class ViewGuidesActivity extends AppCompatActivity {
private static final String TAG = ViewGuidesActivity.class.getSimpleName();
private ProgressDialog pDialog;
private List<Guide> guideList = new ArrayList<Guide>();
private ListView listView;
private CustomListAdapter adapter;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_view_guides);
listView = (ListView) findViewById(R.id.list);
adapter = new CustomListAdapter(this, guideList);
listView.setAdapter(adapter);
pDialog = new ProgressDialog(this);
// Showing progress dialog before making http request
pDialog.setMessage("Loading...");
pDialog.show();
// Creating volley request obj
JsonArrayRequest movieReq = new JsonArrayRequest(AppConfig.URL_GET_GUIDE_LIST,
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);
Guide guide = new Guide();
guide.setNgno(obj.getString("ngno"));
guide.setEmail(obj.getString("email"));
guide.setName(obj.getString("name"));
// adding movie to movies array
guideList.add(guide);
} 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) {
Log.d(TAG, error.toString());
VolleyLog.d(TAG, "Error: " + error.getMessage());
hidePDialog();
}
});
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
this.getSupportActionBar().setDisplayHomeAsUpEnabled(true);
// Adding request to request queue
AppController.getInstance().addToRequestQueue(movieReq);
listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> adapter, View view, int position, long id) {
Guide newGuide = guideList.get(position);
String email = newGuide.getEmail();
String ngno = newGuide.getNgno();
//System.out.println(email);
Intent i = new Intent(getApplicationContext(), GuideDetails.class);
i.putExtra("email", email);
i.putExtra("ngno", ngno);
startActivity(i);
}
});
}
#Override
public void onDestroy() {
super.onDestroy();
hidePDialog();
}
private void hidePDialog() {
if (pDialog != null) {
pDialog.dismiss();
pDialog = null;
}
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.menu_main, menu);
menu.getItem(1).setVisible(false);
menu.getItem(2).setVisible(false);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
switch(item.getItemId()){
case android.R.id.home:
NavUtils.navigateUpFromSameTask(this);
return true;
}
return super.onOptionsItemSelected(item);
}
}

Stop Load data from .json if when data already load

I have 2 fragment( Fragment A and fragment B) with functions to load data using .json.
When I click fragment A, the data will load, and when I click fragment B the data will load too.
When I click fragment A another time, the data is reloaded and duplicated (appended with the data from the first click).
How to stop loading data if data is already loaded?
example image
here my fragment code
fragment_a.java
public class fragment_a extends Fragment {
// Log tag
private static final String TAG = MovieFragment1.class.getSimpleName();
// Movies json url
private static final String url = "http://.......";
private ProgressDialog pDialog;
private List<Movie> movieList = new ArrayList<Movie>();
private ListView listView;
private CustomListAdapter adapter;
public MovieFragment1() {
// Required empty public constructor
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
}
#Override
public void onDestroy() {
super.onDestroy();
hidePDialog();
}
private void hidePDialog() {
if (pDialog != null) {
pDialog.dismiss();
pDialog = null;
}
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.activity_list, container, false);
// Inflate the layout for this fragment
final ListView listView = (ListView) rootView.findViewById(R.id.list);
adapter = new CustomListAdapter(getActivity(), movieList);
listView.setAdapter(adapter);
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();
if (obj.getString("tipe").equals("chest")){
movie.setTitle(obj.getString("name"));
movie.setThumbnailUrl(obj.getString("images1"));
//movie.setDescribe(obj.getString("describe"));
//movie.setRating(((Number) obj.get("rating"))
// .doubleValue());
movie.setYear(obj.getInt("id"));
movie.setTipe(obj.getString("tipe"));
/*// Genre is json array
JSONArray genreArry = obj.getJSONArray("genre");
ArrayList<String> genre = new ArrayList<String>();
for (int j = 0; j < genreArry.length(); j++) {
genre.add((String) genreArry.get(j));
}
movie.setGenre(genre);*/
// 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 rootView;
}
#Override
public void onAttach(Activity activity) {
super.onAttach(activity);
}
#Override
public void onDetach() {
super.onDetach();
}
}
fragment_b.java
public class fragment_b extends Fragment {
// Log tag
private static final String TAG = MovieFragment1.class.getSimpleName();
// Movies json url
private static final String url = "http://......";
private ProgressDialog pDialog;
private List<Movie> movieList = new ArrayList<Movie>();
private ListView listView;
private CustomListAdapter adapter;
public MovieFragment1() {
// Required empty public constructor
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
}
#Override
public void onDestroy() {
super.onDestroy();
hidePDialog();
}
private void hidePDialog() {
if (pDialog != null) {
pDialog.dismiss();
pDialog = null;
}
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.activity_list, container, false);
// Inflate the layout for this fragment
final ListView listView = (ListView) rootView.findViewById(R.id.list);
adapter = new CustomListAdapter(getActivity(), movieList);
listView.setAdapter(adapter);
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();
if (obj.getString("tipe").equals("forearm")){
movie.setTitle(obj.getString("name"));
movie.setThumbnailUrl(obj.getString("images1"));
//movie.setDescribe(obj.getString("describe"));
//movie.setRating(((Number) obj.get("rating"))
// .doubleValue());
movie.setYear(obj.getInt("id"));
movie.setTipe(obj.getString("tipe"));
/*// Genre is json array
JSONArray genreArry = obj.getJSONArray("genre");
ArrayList<String> genre = new ArrayList<String>();
for (int j = 0; j < genreArry.length(); j++) {
genre.add((String) genreArry.get(j));
}
movie.setGenre(genre);*/
// 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 rootView;
}
#Override
public void onAttach(Activity activity) {
super.onAttach(activity);
}
#Override
public void onDetach() {
super.onDetach();
}
}
tabfragment.java (fragment adapter)
public class TabFragment extends Fragment {
public static TabLayout tabLayout;
public static ViewPager viewPager;
public static int int_items = 3 ;
#Nullable
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
/**
*Inflate tab_layout and setup Views.
*/
View x = inflater.inflate(R.layout.tab_layout,null);
tabLayout = (TabLayout) x.findViewById(R.id.tabs);
viewPager = (ViewPager) x.findViewById(R.id.viewpager);
/**
*Set an Apater for the View Pager
*/
viewPager.setAdapter(new MyAdapter(getChildFragmentManager()));
/**
* Now , this is a workaround ,
* The setupWithViewPager dose't works without the runnable .
* Maybe a Support Library Bug .
*/
tabLayout.post(new Runnable() {
#Override
public void run() {
tabLayout.setupWithViewPager(viewPager);
}
});
return x;
}
class MyAdapter extends FragmentPagerAdapter{
public MyAdapter(FragmentManager fm) {
super(fm);
}
/**
* Return fragment with respect to Position .
*/
#Override
public Fragment getItem(int position)
{
switch (position){
case 0 : return new fragment_a();
case 1 : return new HomeFragment();
case 2 : return new fragment_b();
}
return null;
}
#Override
public int getCount() {
return int_items;
}
/**
* This method returns the title of the tab according to the position.
*/
#Override
public CharSequence getPageTitle(int position) {
switch (position){
case 0 :
return "Chest";
case 1 :
return "Movie";
case 2 :
return "Forearm";
}
return null;
}
}
}
Just wrap your movieRequest with
if(movieList.isEmpty()){
JsonArrayRequest movieReq = new JsonArrayRequest(url, ... ETC...
// etc
}
But remember that with this approach your data will not update if it is changed on server, to make it updatable you must clear movieList before filling it every time instead:
movieList.clear();

Webservices with Retained Fragments

I have a Fragment that is used to retrieve some data from my CMS with the help of the Volley lib. I am using RecyclerViews to do that. It works. However when I am rotating the screen,the webservice is run again. How can I stop that? I tried to use **setRetainInstance(true); but at no vail. From what I have read,this method bypasses the onDestroy() fragment's method,and hence the onCreate() fragment's method is not called when you rotate the screen. If I am wrong with that please correct me. Here is my code.
FeaturesActivity
public class FeaturesActivity extends AppCompatActivity {
private static final String FEATURES_FRAGMENT = "Features_fragment";
FeaturesFragment ff;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_features);
FragmentManager fragmentManager = getSupportFragmentManager();
ff = (FeaturesFragment) fragmentManager.findFragmentByTag(FEATURES_FRAGMENT);
if(ff == null) {
ff = new FeaturesFragment();
FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction();
fragmentTransaction.add(android.R.id.content, ff);
fragmentTransaction.commit();
}
}
}
And the actual fragment itself.
public class FeaturesFragment extends Fragment {
public static final String TAG = "ManuApp";
private static final String IMAGE_URL = "http://xxx/xxx/features_images/" ;
private List<FeaturesObject> listItemsList;
private RecyclerView mRecyclerView;
private FeaturesAdapter adapter;
public FeaturesFragment() {
// Required empty public constructor
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setRetainInstance(true);
Log.v("retained","oncreate called");
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View v = inflater.inflate(R.layout.fragment_features, container, false);
// Inflate the layout for this fragment
listItemsList = new ArrayList<>();
mRecyclerView = (RecyclerView)v.findViewById(R.id.features_recycler_view);
//mRecyclerView.addItemDecoration(new HorizontalDividerItemDecoration.Builder(getActivity()).color(Color.BLACK).build());
final LinearLayoutManager linearLayoutManager = new LinearLayoutManager(getActivity());
mRecyclerView.setHasFixedSize(true);
mRecyclerView.setLayoutManager(linearLayoutManager);
return v;
}
#Override
public void onActivityCreated(Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
updateFeaturesList();
}
public void updateFeaturesList() {
//declare the adapter and attach it to the recyclerview
adapter = new FeaturesAdapter(getActivity(), listItemsList);
mRecyclerView.setAdapter(adapter);
// Instantiate the RequestQueue.
RequestQueue queue = Volley.newRequestQueue(getActivity());
// Request a string response from the provided URL.
JsonArrayRequest jsObjRequest = new JsonArrayRequest(Request.Method.GET, Config.URL_FEATURES, new Response.Listener<JSONArray>() {
#Override
public void onResponse(JSONArray response) {
Log.d(TAG, response.toString());
//hidePD();
// Parse json data.
// Declare the json objects that we need and then for loop through the children array.
// Do the json parse in a try catch block to catch the exceptions
try {
for (int i = 0; i < response.length(); i++) {
JSONObject post = response.getJSONObject(i);
FeaturesObject item = new FeaturesObject();
item.setTitle(post.getString("title"));
item.setImage(IMAGE_URL + post.getString("features_image"));
item.setArticle(post.getString("article"));
listItemsList.add(item);
}
} catch (JSONException e) {
e.printStackTrace();
}
// Update list by notifying the adapter of changes
adapter.notifyDataSetChanged();
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
VolleyLog.d(TAG, "Error: " + error.getMessage());
//hidePD();
}
});
queue.add(jsObjRequest);
}
}
I logged out a message inside the onCreate(...),but it is called even if I rotate the screen. How can I fix that?
Thanks.
I fixed it using the following code inside the manifest.xml file
android:configChanges="screenSize|orientation"
Google though states that we should use that as a resourse.

Categories

Resources