Webservices with Retained Fragments - android

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.

Related

pull refresh error keep adding every time i pull

I trying to create a pull refresh.
every time I pull it.
Here's my code:
public class LatestGradeFragment extends Fragment implements SwipeRefreshLayout.OnRefreshListener{
List<ListGradeData> sectionList;
RecyclerView recyclerView;
SwipeRefreshLayout mSwipeRefreshLayout;
public static LatestGradeFragment newInstance() {
return new LatestGradeFragment();
}
#Nullable
#Override
public View onCreateView(LayoutInflater inflater, #Nullable ViewGroup container, #Nullable Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment_latest_grade, container, false);
//RecyclerView+CardView for section
recyclerView = (RecyclerView) rootView.findViewById(R.id.display_recyclerView);
recyclerView.setHasFixedSize(true);
recyclerView.setLayoutManager(new LinearLayoutManager(getActivity()));
sectionList = new ArrayList<>();
mSwipeRefreshLayout = (SwipeRefreshLayout) rootView.findViewById(R.id.swipeRefreshSection);
mSwipeRefreshLayout.setOnRefreshListener(this);
mSwipeRefreshLayout.setColorSchemeResources(R.color.colorPrimary,
android.R.color.holo_green_dark,
android.R.color.holo_orange_dark,
android.R.color.holo_blue_dark);
mSwipeRefreshLayout.post(new Runnable() {
#Override
public void run() {
mSwipeRefreshLayout.setRefreshing(true);
// Fetching data from server
loadSection();
}
});
return rootView;
}
#Override
public void onRefresh() {
loadSection();
}
private void loadSection() {
mSwipeRefreshLayout.setRefreshing(true);
StringRequest stringRequest = new StringRequest(Request.Method.GET, Constants.USER_GRADE,
new Response.Listener<String>() {
#Override
public void onResponse(String response) {
try {
//converting the string to json array object
JSONArray array = new JSONArray(response);
//traversing through all the object
for (int i = 0; i < array.length(); i++) {
//getting product object from json array
JSONObject sections = array.getJSONObject(i);
//adding the product to product list
sectionList.add(new ListGradeData(
sections.getInt("id"),
sections.getString("section"),
sections.getString("level"),
sections.getString("schoolyear")
));
}
//creating adapter object and setting it to recyclerview
LatestGradeAdapter adapter = new LatestGradeAdapter(getActivity(), sectionList);
recyclerView.setAdapter(adapter);
} catch (JSONException e) {
e.printStackTrace();
}
// Stopping swipe refresh
mSwipeRefreshLayout.setRefreshing(false);
}
},
new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
// Stopping swipe refresh
mSwipeRefreshLayout.setRefreshing(false);
}
});
//adding our stringrequest to queue
Volley.newRequestQueue(getActivity().getApplicationContext()).add(stringRequest);
}
#Override
public String toString() {
return "LatestGradeFragment ";
}
}
I'm new in android/java could anyone help me.
Inside respone of api you have to clear list first, so it will never repeat data. Your code inside response inside try block should be:
if(sectionList!=null) {
sectionlist.clear();
}
remove this part, its unnecessary
mSwipeRefreshLayout.post(new Runnable() {
#Override
public void run() {
mSwipeRefreshLayout.setRefreshing(true);
// Fetching data from server
loadSection();
}
});
and you should create LatestGradeAdapter as globe variable, just notify data change whenever you get new data from server

I have fetched data in Android by using PHP Web services it fetched but when new data is added it can't fetched?

By using below code I am fetching data. When I run it the first time it will show all data. When I insert new data it will be inserted successfully but on going to report page and clicking on that it shows previous data and not the new or updated data.
public class Fragment_Emp_Report extends Fragment {
List<Get_EmpNameAdapter> get_empNameAdapter1;
RecyclerView recyclerView;
ProgressBar progressBar;
RecyclerView.LayoutManager recyclerViewlayoutManager;
RecyclerView.Adapter recyclerViewadapter;
String url = "http://ghawadediilip.000webhostapp.com/Services/jsonFetchName.php";
String JSON_NAME = "emp_name";
JsonArrayRequest jsonArrayRequest;
RequestQueue requestQueue;
#Nullable
#Override
public View onCreateView(LayoutInflater inflater, #Nullable ViewGroup container, #Nullable Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_emp_report,container,false);
fetchEmpName();
return view;
}
#Override
public void onViewCreated(View view, #Nullable Bundle savedInstanceState) {
super.onViewCreated(view, savedInstanceState);
get_empNameAdapter1 = new ArrayList<>();
recyclerView = (RecyclerView)view.findViewById(R.id.report_recyclerview);
recyclerView.setHasFixedSize(true);
recyclerViewlayoutManager = new LinearLayoutManager(getActivity().getApplicationContext());
recyclerView.setLayoutManager(recyclerViewlayoutManager);
}
public void fetchEmpName()
{
jsonArrayRequest = new JsonArrayRequest(url, new Response.Listener<JSONArray>() {
#Override
public void onResponse(JSONArray response) {
jsonFetch(response);
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
}
});
requestQueue = Volley.newRequestQueue(getActivity().getApplicationContext());
requestQueue.add(jsonArrayRequest);
RequestQueue.RequestFinishedListener listener = new RequestQueue.RequestFinishedListener() {
#Override
public void onRequestFinished(Request request) {
recyclerViewadapter.notifyDataSetChanged();
}
};
requestQueue.addRequestFinishedListener(listener);
}
public void jsonFetch(JSONArray array)
{
for (int i=0;i<array.length();i++)
{
Get_EmpNameAdapter get_empNameAdapter2 = new Get_EmpNameAdapter();
JSONObject json=null;
try {
json = array.getJSONObject(i);
get_empNameAdapter2.setEmpname(json.getString(JSON_NAME));
} catch (JSONException e) {
e.printStackTrace();
}
recyclerView.setAdapter(recyclerViewadapter);
get_empNameAdapter1.add(get_empNameAdapter2);
}
recyclerViewadapter = new Report_Recyclerview_Adapter(get_empNameAdapter1,getContext());
recyclerView.setAdapter(recyclerViewadapter);
}
}
Your fetchEmpName(); called only one time when onCreateView is called if you want to refetch the date when back from another fragment then you have to call your method again you can achieve that by calling it in onResume.

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.

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

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

Categories

Resources