Stop Load data from .json if when data already load - android

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();

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?

notifyDataSetChanged on RecyclerView android

I have problem with my code in notifyDataSetChanged on Recyclerview. Here is my code, please help me to fix it.
public class FragmentListFilm extends BaseFragment {
private static final String TAG = FragmentListFilm.class.getSimpleName();
private static final String url "http://api.androidhive.info/json/movies.json";
private List<InforFilm> inforFilms = new ArrayList<InforFilm>();
private Fragment_Film_Adapter adapter;
private DialogActivity dialogActivity;
View root;
private ProgressDialog pDialog;
private RecyclerView rv;
#Override
public void onCreate(#Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
}
#Nullable
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
root = inflater.inflate(R.layout.fragment_film, container, false);
rv = (RecyclerView) root.findViewById(R.id._recycler_fragment_film);
setUpRecycleView(rv);
return root;
}
private void setUpRecycleView(RecyclerView recycleView) {
recycleView.setLayoutManager(new LinearLayoutManager(recycleView.getContext()));
recycleView.setAdapter(adapter);
pDialog = new ProgressDialog(getActivity());
// Showing progress dialog before making http request
pDialog.setMessage("Loading...");
pDialog.show();
// recycleView.
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 {
// Log.d(TAG, "try-cat");
JSONObject obj = response.getJSONObject(i);
InforFilm film = new InforFilm();
film.setTitle(obj.getString("title"));
film.setThumbail(obj.getString("image"));
film.setRating(((Number) obj.get("rating"))
.doubleValue());
film.setYear(obj.getInt("releaseYear"));
// 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));
}
film.setGender(genre);
// adding movie to movies array
inforFilms.add(film);
} catch (JSONException e) {
e.printStackTrace();
}
}
// notifying list adapter about data changes
// so that it renders the list view with updated data
Log.d(TAG, "notifydatasetchanged");
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);
}
private void hidePDialog() {
if (pDialog != null) {
pDialog.dismiss();
pDialog = null;
}
}
}
////// Adapter
public class Fragment_Film_Adapter extends RecyclerView.Adapter<Fragment_Film_Adapter.ViewHolder> {
private List<InforFilm> inforFilms;
ImageLoader imageLoader = AppController.getInstance().getmImageLoader();
public Fragment_Film_Adapter(List<InforFilm> inforFilms) {
this.inforFilms = inforFilms;
}
public class ViewHolder extends RecyclerView.ViewHolder {
#Bind(R.id.film_thumbnail)
NetworkImageView thumbNail;
#Bind(R.id.film_genre)
TextView gender;
#Bind(R.id.film_rating)
TextView rating;
#Bind(R.id.film_title)
TextView title;
#Bind(R.id.film_releaseYear)
TextView year;
public ViewHolder(View view) {
super(view);
}
}
#Override
public ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.fragment_film_item, parent, false);
return new ViewHolder(view);
}
#Override
public void onBindViewHolder(ViewHolder holder, int position) {
InforFilm infor = inforFilms.get(position);
holder.thumbNail.setImageUrl(infor.getThumbail(), imageLoader);
holder.title.setText(infor.getTitle());
holder.rating.setText(String.valueOf(infor.getRating()));
holder.year.setText(infor.getYear());
String genreStr = "";
for (String str : infor.getGender()) {
genreStr += str + ", ";
}
genreStr = genreStr.length() > 0 ? genreStr.substring(0,
genreStr.length() - 2) : genreStr;
holder.gender.setText(genreStr);
}
#Override
public int getItemCount() {
return inforFilms.size();
}
}
It throws the following exception:
Attempt to invoke virtual method 'void com.example.qtv.qtvmaterial.adapter.Fragment_Film_Adapter.notifyDataSetChanged()' on a null object reference
at com.example.qtv.qtvmaterial.fragment.FragmentListFilm$1.onResponse(FragmentListFilm.java:110)
at com.example.qtv.qtvmaterial.fragment.FragmentListFilm$1.onResponse(FragmentListFilm.java:71)
Before setting adapter to RecyclerView initialize it:
recycleView.setLayoutManager(new LinearLayoutManager(recycleView.getContext()));
adapter = new Fragment_Film_Adapter(inforFilms);
recycleView.setAdapter(adapter);

Listview items reloaded on fragment

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. :)

Android ListView keeps getting cut off

For some reason when the listview in my fragment is loaded it gets cut off at the first row however the same code is used in other listfragments in my app and those are fine ???...
Here is my xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
android:background="#eeeeee">
<ListView
android:id="#android:id/list"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:divider="#eeeeee"
android:dividerHeight="8dp"
android:listSelector="#drawable/list_row_selector"
/>
</LinearLayout>
and here is the fragment class .. I dont the fault lies with the adapter class as I am using that in the other fragments that are working.
public class TabTwoFragment extends ListFragment {
private static final String TAG = AccommodationFragment.class.getSimpleName();
// Movies json url
private static final String url = "http://api.mywebsite.com/json.php";
private ProgressDialog pDialog;
private List<Movie> movieList = new ArrayList<Movie>();
private ListView listView;
private CustomListAdapter adapter;
private View mheaderView;
//private TextView txtFragmentone;
public static TabTwoFragment newInstance() {
Bundle bundle = new Bundle();
TabTwoFragment fragment = new TabTwoFragment();
fragment.setArguments(bundle);
return fragment;
}
#TargetApi(Build.VERSION_CODES.HONEYCOMB)
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.accommodation_fragment, container, false);
rootView.setLayoutParams(new ViewGroup.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT ));
listView = (ListView) getActivity().findViewById(android.R.id.list);
adapter = new CustomListAdapter(getActivity(), movieList);
setListAdapter(adapter);
mheaderView = inflater.inflate(R.layout.list_header, null);
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"));
movie.seturl(obj.getString("url"));
/*movie.setRating(((Number) obj.get("rating"))
.doubleValue());*/
movie.setYear(obj.getString("releaseYear"));
// 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 onDestroy() {
super.onDestroy();
hidePDialog();
setListAdapter(null);
}
private void hidePDialog() {
if (pDialog != null) {
pDialog.dismiss();
pDialog = null;
}
}
#Override
public void onActivityCreated(Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
/* if (mheaderView != null) listView.addHeaderView(mheaderView);*/
// Don't forget to now call setListAdapter()
this.setListAdapter(adapter);
setHasOptionsMenu(true);
}
#Override
public void onListItemClick(ListView l, View v, int position, long id) {
Movie m= movieList.get(position);
String yourURL = m.geturl();
MyDetailFragment myDetailFragment = new MyDetailFragment();
Bundle args = new Bundle();
args.putString("YourKey", yourURL);
myDetailFragment.setArguments(args);
FragmentManager fragmentManager = getActivity().getSupportFragmentManager();
fragmentManager.beginTransaction().replace(R.id.content_frame, myDetailFragment).addToBackStack(null).commit();
}
I have no idea why it is cutting off my listview and I really can't find a solution on my own.... so any help would be great!

Categories

Resources