I'm passing a value from MainActivity.class to this fragment ResultFrag.class. In this class, it's supposed to display the places that is within the requested value from the user's current location.
The json return is correct.
I also tried to debug and display the item in the myList through Logcat and it is fine. So meaning that the json is parsed correctly and it's being added to the myList.
myAdapter = new MyAdapter(getActivity(), getTheList());
This particular line that pass the list to the custom adapter; I don't think it's getting the list from the getTheList() method. Because I tried debugging using below codes by putting it in onCreateView but it's not logging anything:
for (int b = 0; b < getTheList().size(); b++) {
Log.d("list: ", Integer.toString(b) + " : " + getTheList().get(b).getPlace());
}
Can anyone help? I've been working on this since yesterday.
import android.location.Location;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Toast;
import com.android.volley.AuthFailureError;
import com.android.volley.Request;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.VolleyLog;
import com.android.volley.toolbox.StringRequest;
import com.android.volley.toolbox.Volley;
import com.google.android.gms.common.ConnectionResult;
import com.google.android.gms.common.GooglePlayServicesUtil;
import com.google.android.gms.common.api.GoogleApiClient;
import com.google.android.gms.location.LocationServices;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
public class ResultFrag extends Fragment implements GoogleApiClient.ConnectionCallbacks, GoogleApiClient.OnConnectionFailedListener {
double latitude, longitude;
String lat, lng;
private Bundle bundle;
private String data;
private static final String TAG_URL_DISTANCE = "///remove link///";
private static final String LOG_DISTANCE = ResultFrag.class.getSimpleName();
private MyAdapter myAdapter;
private RecyclerView recyclerView;
List<GetterSetter> myList = new ArrayList<>();
private static final String TAG = ResultFrag.class.getSimpleName();
private static final int REQUEST_CODE = 1000;
Location location;
GoogleApiClient googleClient;
public ResultFrag() {
}
public void searchPlace(final String dist, final String latitude, final String longitude) {
StringRequest stringRequest = new StringRequest(Request.Method.POST, TAG_URL_DISTANCE, new Response.Listener<String>() {
#Override
public void onResponse(String response) {
Log.e(LOG_DISTANCE, response.toString());
try {
JSONArray arr = new JSONArray(response);
for (int i = 0; i < arr.length(); i++) {
JSONObject obj = arr.getJSONObject(i);
GetterSetter getterSetter = new GetterSetter();
getterSetter.setId(obj.getString("id"));
getterSetter.setPlace(obj.getString("name"));
getterSetter.setDistance(obj.getInt("distance"));
myList.add(getterSetter);
}
for (int b = 0; b < getTheList().size(); b++) {
Log.d("list: ", Integer.toString(b) + " : " + getTheList().get(b).getPlace());
}
} catch (JSONException e) {
e.printStackTrace();
Toast.makeText(getContext(), "JSONException: " + e.getMessage(), Toast.LENGTH_LONG).show();
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
VolleyLog.d(LOG_DISTANCE, "Volley Error: " + error.getMessage());
Toast.makeText(getContext(), error.getMessage(), Toast.LENGTH_LONG).show();
}
}) {
#Override
protected Map<String, String> getParams() throws AuthFailureError {
Map<String, String> params = new HashMap<String, String>();
params.put("dist", dist);
params.put("latitude", latitude);
params.put("longitude", longitude);
return params;
}
};
Volley.newRequestQueue(getContext()).add(stringRequest);
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
final View rootView = inflater.inflate(R.layout.result_frag, container, false);
bundle = this.getArguments();
data = bundle.getString(MainActivity.option);
if (checkGooglePlayServices()) {
buildGoogleClient();
}
lat = getLatitude();
lng = getLongitude();
Log.d("radius", data);
Log.d("latitude", lat);
Log.d("longitude", lng);
recyclerView = (RecyclerView) rootView.findViewById(R.id.recyclerView);
myAdapter = new MyAdapter(getActivity(), getTheList());
recyclerView.setAdapter(myAdapter);
recyclerView.setLayoutManager(new LinearLayoutManager(getActivity()));
/* recyclerView.addOnItemTouchListener(
new RecyclerItemClickListener(this, new RecyclerItemClickListener.OnItemClickListener() {
#Override
public void onItemClick(View view, int position) {
}
})
);*/
return rootView;
}
private boolean checkGooglePlayServices() {
int resultCode = GooglePlayServicesUtil.isGooglePlayServicesAvailable(getContext());
if (resultCode != ConnectionResult.SUCCESS) {
if (GooglePlayServicesUtil.isUserRecoverableError(resultCode)) {
// Show error
GooglePlayServicesUtil.getErrorDialog(resultCode, getActivity(), REQUEST_CODE).show();
} else {
Toast.makeText(getContext(),
"No GPS",
Toast.LENGTH_LONG).show();
}
return false;
}
return true;
}
protected synchronized void buildGoogleClient() {
googleClient = new GoogleApiClient.Builder(getActivity())
.addConnectionCallbacks(this)
.addOnConnectionFailedListener(this)
.addApi(LocationServices.API)
.build();
}
#Override
public void onStart() {
super.onStart();
if (googleClient != null) {
googleClient.connect();
}
}
#Override
public void onResume() {
super.onResume();
checkGooglePlayServices();
}
#Override
public void onConnected(Bundle bundle) {
location = LocationServices.FusedLocationApi.getLastLocation(googleClient);
searchPlace(data, getLatitude(), getLongitude());
Toast.makeText(getContext(), getLatitude() + ", " + getLongitude(), Toast.LENGTH_LONG).show();
}
public List<GetterSetter> getTheList() {
return myList;
}
public String getLatitude() {
if (location != null) {
latitude = location.getLatitude();
}
return String.valueOf(latitude);
}
public String getLongitude() {
if (location != null) {
longitude = location.getLongitude();
}
return String.valueOf(longitude);
}
#Override
public void onConnectionSuspended(int i) {
googleClient.connect();
}
#Override
public void onConnectionFailed(ConnectionResult connectionResult) {
Log.i(TAG, "Connection failed: ConnectionResult.getErrorCode() = "
+ connectionResult.getErrorCode());
}
}
MyAdapter.class
import android.content.Context;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;
import java.util.Collections;
import java.util.List;
public class MyAdapter extends RecyclerView.Adapter<MyAdapter.MyViewHolder>{
List<GetterSetter> data = Collections.emptyList();
private LayoutInflater layoutInflater;
private Context context;
public MyAdapter (Context context, List<GetterSetter> data) {
this.context = context;
this.data = data;
layoutInflater = layoutInflater.from(context);
}
#Override
public MyAdapter.MyViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View view = layoutInflater.inflate(R.layout.mylist, parent, false);
MyViewHolder holder = new MyViewHolder(view);
return holder;
}
#Override
public void onBindViewHolder(MyAdapter.MyViewHolder holder, int position) {
// Get event data
GetterSetter current = data.get(position);
holder.id.setText(current.getId());
holder.place.setText(current.getPlace());
holder.distance.setText("Distance: " + String.valueOf(current.getDistance()) + " km");
}
#Override
public int getItemCount() {
return data.size();
}
public class MyViewHolder extends RecyclerView.ViewHolder {
TextView id;
TextView place;
TextView distance;
public MyViewHolder(View itemView) {
super(itemView);
id = (TextView) itemView.findViewById(R.id.placeId);
place = (TextView) itemView.findViewById(R.id.name);
distance = (TextView) itemView.findViewById(R.id.distance);
}
}
}
Did you fix it in the meantime? What I see is that you actually share the list between the adapter and the Fragment. And you make changes (add items) to the list after the adapter was constructed. But you do not call notfyDatasetChanged() on the adapter. Add that call once you are done with applyting changes to the list.
JSONArray arr = new JSONArray(response);
for (int i = 0; i < arr.length(); i++) {
JSONObject obj = arr.getJSONObject(i);
GetterSetter getterSetter = new GetterSetter();
getterSetter.setId(obj.getString("id"));
getterSetter.setPlace(obj.getString("name"));
getterSetter.setDistance(obj.getInt("distance"));
myList.add(getterSetter);
}
myAdapter.notfyDatasetChanged()
Related
I tried to display jsonObject in Recyclerview use retrofit library, but it only accept in the Array format. I tried to change the jsonObject to jsonArray, but the problem is the server don't recognize the json type. So now my question is, how to display jsonObject to recyclerview widget. Give me tips or idea..Thank in advance
This is my Jsonobject Data..
{
"success": true,
"data": {
"id": 1,
"parent_id": null,
"name": "Ionnex Sdn Bhd",
"description": "Test Value",
"image": "http://www.ionnex.com/images/logo_ionnex.png",
"phone_no": "12345678",
"fax": "123456",
"address": "Kl Sentral",
"latitude": 0,
"longitude": 0,
"created_at": "2017-08-15 02:26:00",
"donors_count": "4",
"donors_amount": "601.00"
}
}
This is my Fragment connect to the recyclerview widget.
import android.content.Context;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentStatePagerAdapter;
import android.support.v4.view.ViewPager;
import android.support.v7.widget.DefaultItemAnimator;
import android.support.v7.widget.GridLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import com.baracode.eilsan.data.ApiRequest;
import com.baracode.eilsan.donate.DonateMenuActivity;
import com.baracode.eilsan.donate.parentOrganisation.ParentOrganisationActivity;
import com.baracode.eilsan.donate.parentOrganisation.adapter.DonateParentOrganisationAdapter;
import com.baracode.eilsan.donate.parentOrganisation.adapter.OrganisationAdapter;
import com.baracode.eilsan.donate.parentOrganisation.adapter.OrganisationModel;
import com.baracode.eilsan.R;
import com.baracode.eilsan.model.Caused;
import com.baracode.eilsan.model.Organisation;
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import com.squareup.picasso.Picasso;
import java.util.ArrayList;
import static android.R.id.message;
public class OrganisationFragment extends Fragment {
private ViewPager viewPager;
private ImageView mosqueImage;
private RecyclerView recyclerView;
// private ArrayList<OrganisationModel> organisationModelArrayList = new ArrayList<>();
private ArrayList<Organisation> organisationList = new ArrayList<>();
// Organisation organisationList = new Organisation();
private OrganisationAdapter organisationAdapter;
private OrganisationFragment.MainPagerAdapter adapter;
private Organisation organisation;
private Context context;
private ApiRequest apiRequest;
public Organisation selectedOrganization = null;
public OrganisationFragment() {
// Required empty public constructor
}
public View view = null;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
View rootView = inflater.inflate(R.layout.fragment_organisation, container, false);
recyclerView = rootView.findViewById(R.id.organisation_recyclerview);
mosqueImage = rootView.findViewById(R.id.donate_fragment_mosque_image);
// organisationModelArrayList.clear();
prepareOrganisationData();
// Organisation org = ParentOrganisationActivity.selectedOrganization;
// recyclerView.setAdapter();
return rootView;
}
//here create parse
public static OrganisationFragment newInstance(Organisation organisation) {
OrganisationFragment fragment = new OrganisationFragment();
Bundle args = new Bundle();
fragment.setArguments(args);
fragment.selectedOrganization = organisation;
return fragment;
}
public class MainPagerAdapter extends FragmentStatePagerAdapter {
private FragmentManager fragmentManager;
private final ArrayList<Fragment> fragmentList = new ArrayList<>();
private final ArrayList<String> fragmentTitleList = new ArrayList<>();
MainPagerAdapter(FragmentManager fm) {
super(fm);
fragmentManager = fm;
}
#Override
public int getItemPosition(Object object) {
return POSITION_NONE;
}
#Override
public Fragment getItem(int position) {
return fragmentList.get(position);
}
#Override
public int getCount() {
return fragmentList.size();
}
#Override
public CharSequence getPageTitle(int position) {
return fragmentTitleList.get(position);
}
void addFragment(Fragment fragment, String title) {
fragmentList.add(fragment);
fragmentTitleList.add(title);
}
}
//Organisation data change here
private void prepareOrganisationData() {
// OrganisationModel organisationModel = new OrganisationModel("Masjid Sultan Abu Bakar", "Kuala Lumpur", R.drawable.mosque_1);
// this.organisationModelArrayList.add(organisationModel);
//
// organisationModel = new OrganisationModel("Masjid Zahir", "Kuala Lumpur", R.drawable.mosque_2);
// this.organisationModelArrayList.add(organisationModel);
Bundle extras = getActivity().getIntent().getExtras();
if (extras == null) {
selectedOrganization = null;
} else {
Gson gson = new Gson();
// Gson gson = new GsonBuilder().serializeNulls().create();
selectedOrganization = gson.fromJson(extras.getString("org"), Organisation.class);
Organisation org = selectedOrganization;
Picasso.with(context).load(org.getImage()).into(mosqueImage);
}
ApiRequest.getInstance().getOrganisationIdDetails(getActivity(), selectedOrganization.id, new ApiRequest.GetAllOrgIdDetailsCallback() {
#Override
public void getAllOrgIdDetailsSuccess(ArrayList<Organisation> result) {
organisationList = result;
organisationAdapter = new OrganisationAdapter(organisationList, context);
RecyclerView.LayoutManager mLayoutManager = new GridLayoutManager(getActivity(), 2);
recyclerView.setLayoutManager(mLayoutManager);
recyclerView.setItemAnimator(new DefaultItemAnimator());
recyclerView.setAdapter(organisationAdapter);
}
#Override
public void getAllOrgDetailsFail(String message) {
}
});
}
/* TODO
add onClick listener to each object
*/
}
This is my Fragment Adapter..
import android.content.Context;
import android.content.Intent;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
import com.baracode.eilsan.R;
import com.baracode.eilsan.donate.organisation.OrganisationActivity;
import com.baracode.eilsan.model.Caused;
import com.baracode.eilsan.model.Organisation;
import com.squareup.picasso.Picasso;
import java.util.ArrayList;
import java.util.List;
public class OrganisationAdapter extends RecyclerView.Adapter<OrganisationAdapter.MyViewHolder> {
private Context context;
// private final ArrayList<OrganisationModel> organisationModelList;
ArrayList<Organisation> organisationModelList;
public OrganisationAdapter(ArrayList<Organisation> organisationModelList , Context context) {
this.organisationModelList = organisationModelList;
this.context = context;
}
#Override
public OrganisationAdapter.MyViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View itemView = LayoutInflater.from(parent.getContext()).inflate(R.layout.item_organisation_recyclerview, parent, false);
return new OrganisationAdapter.MyViewHolder(itemView);
}
#Override
public void onBindViewHolder(OrganisationAdapter.MyViewHolder holder, int position) {
// OrganisationModel organisationModel = organisationModelList.get(position);
final Organisation organisationModel = organisationModelList.get(position);
holder.organisationName.setText(organisationModel.getName());
holder.cityName.setText(organisationModel.getAddress());
// holder.mosqueImage.setImageResource(organisationModel.getOrganisationImage());
Picasso.with(context)
.load(organisationModel.getImage())
.into(holder.mosqueImage);
holder.headlineLinearLayout.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Intent intent;
switch (view.getId()) {
case R.id.organisation_linearlayout:
intent = new Intent(view.getContext(), OrganisationActivity.class);
view.getContext().startActivity(intent);
}
}
});
}
#Override
public int getItemCount() {
return organisationModelList.size();
}
public class MyViewHolder extends RecyclerView.ViewHolder {
public TextView organisationName, cityName;
public ImageView mosqueImage;
public LinearLayout headlineLinearLayout;
public MyViewHolder(View view) {
super(view);
organisationName = view.findViewById(R.id.donate_parent_organisation_name);
cityName = view.findViewById(R.id.donate_parent_organisation_city_name);
mosqueImage = view.findViewById(R.id.donate_parent_organisation_image);
headlineLinearLayout = view.findViewById(R.id.organisation_linearlayout);
}
}
/* TODO
* Implement on click listener on the recyclerview
* */
}
This is my Fragment Model(Setter n Getter)
public class OrganisationModel {
private String organisationName = "";
private String cityName = "";
private int organisationImage;
public int getOrganisationImage() {
return organisationImage;
}
public void setOrganisationImage(int organisationImage) {
this.organisationImage = organisationImage;
}
public String getOrganisationName() {
return organisationName;
}
public void setOrganisationName(String organisationName) {
this.organisationName = organisationName;
}
public String getCityName() {
return cityName;
}
public void setCityName(String cityName) {
this.cityName = cityName;
}
public OrganisationModel(String organisationName, String cityName, int organisationImage) {
this.organisationName = organisationName;
this.cityName = cityName;
this.organisationImage = organisationImage;
}
}
This is MyApirequest class to get the Json Object
public void getOrganisationIdDetails(final Context context, String organizationIdDetails, final GetAllOrgIdDetailsCallback apiCallback) {
String accessToken = LocalData.getInstance().loadStringData(LocalData.KEY_ACCESS_TOKEN);
Call<JsonObject> call = apiService.getOrgIdDetails("Bearer " + accessToken, organizationIdDetails);
call.enqueue(new Callback<JsonObject>() {
#Override
public void onResponse(Call<JsonObject> call, Response<JsonObject> response) {
Log.d("eihsan", "getOrgIdDetails: " + response.body().toString());
Boolean isSuccess = response.body().get("success").getAsBoolean();
if (isSuccess) {
JsonObject jsonData = response.body().get("data").getAsJsonObject();
//JsonArray jsonArray = jsonData.getAsJsonArray("data");
Organisation org = new Organisation();
// ArrayList<Organisation> organisationList = new ArrayList<>();
org.setId(jsonData.get("id").getAsString());
org.setParentId(jsonData.get("parent_id").toString());
org.setName(jsonData.get("name").getAsString());
org.setDescription(jsonData.get("description").getAsString());
org.setImage(jsonData.get("image").getAsString());
org.setPhone_no(jsonData.get("phone_no").getAsString());
org.setFax(jsonData.get("fax").getAsString());
org.setAddress(jsonData.get("address").getAsString());
org.setLatitude(jsonData.get("latitude").getAsString());
org.setLongitude(jsonData.get("longitude").getAsString());
org.setDonorCount(jsonData.get("donors_count").getAsString());
apiCallback.getAllOrgIdDetailsSuccess(org);
} else {
apiCallback.getAllOrgDetailsFail("Data Error occurred");
}
}
#Override
public void onFailure(Call<JsonObject> call, Throwable throwable) {
}
});
}
AFTER FEW MONTH, I SOLVED THE PROBLEM..
Use retrofit library and call the api before display. So here how to call the data for future reference....
public void getOneOrg(String orgId, final GetOneOrgCallback apiCallback) {
String auth = "Bearer " + LocalData.getInstance().loadStringData(LocalData.SP_KEY_ACCESS_TOKEN);
Call<JsonObject> call = apiService.getOneOrg(auth, orgId);
call.enqueue(new Callback<JsonObject>() {
#Override
public void onResponse(Call<JsonObject> call, Response<JsonObject> response) {
StaticFunction.showLogD("getOneOrg: " + response.body().toString());
Boolean isSuccess = response.body().get("success").getAsBoolean();
if (isSuccess) {
JsonObject jsonData = response.body().get("data").getAsJsonObject();
Organization org = gson.fromJson(jsonData, Organization.class);
apiCallback.getOneOrgSuccess(org);
} else {
apiCallback.getOneOrgFail("Data error");
}
}
#Override
public void onFailure(Call<JsonObject> call, Throwable throwable) {
apiCallback.getOneOrgFail("Data error");
}
});
}
Here how i called the json object in API "Organization" is the java file for each variables in api.
I would like to put 2 columns of recyclerview every row.
Right now my design is like this:
and i would like to put 2 so the scroll is not to long.
I have this view inside a fragment and I use a recyclerview adapter but I have no clue how to tell it to use its parent with, so it can fill the width of the screen. In the fragment I recive a JSON from an online database using an AsyncTask and fill in the recyclerview on the onPostExecute of the AsyncTask.
If anyone has any Idea how i can do it, I can't seem to find this anywhere
Thx!
My recyclerview Adapter:
package com.example.juanfri.seguridadmainactivity;
/**
* Created by jlira on 30/05/2017.
*/
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.TextView;
import com.squareup.picasso.Picasso;
import java.util.ArrayList;
/**
* Created by Juanfri on 29/05/2017.
*/
public class RecyclerAdapterSerie extends RecyclerView.Adapter<RecyclerAdapterSerie.SerieHolder> {
private ArrayList<Serie> mSerie;
#Override
public RecyclerAdapterSerie.SerieHolder onCreateViewHolder(ViewGroup viewGroup, int i) {
View inflatedView = LayoutInflater.from(viewGroup.getContext())
.inflate(R.layout.recyclerview_card, viewGroup, false);
return new SerieHolder(inflatedView);
}
#Override
public void onBindViewHolder(RecyclerAdapterSerie.SerieHolder holder, int i) {
Serie itemPhoto = mSerie.get(i);
holder.bindPhoto(itemPhoto);
}
#Override
public int getItemCount() {
return mSerie.size();
}
public RecyclerAdapterSerie(ArrayList<Serie> serie) {
mSerie = serie;
}
public static class SerieHolder extends RecyclerView.ViewHolder implements View.OnClickListener {
//2
private ImageView mItemImage;
private TextView mItemDate;
private TextView mItemDescription;
private Serie serie;
//3
private static final String PHOTO_KEY = "PHOTO";
//4
public SerieHolder(View v) {
super(v);
mItemImage = (ImageView) v.findViewById(R.id.item_image);
mItemDate = (TextView) v.findViewById(R.id.item_date);
mItemDescription = (TextView) v.findViewById(R.id.item_description);
v.setOnClickListener(this);
}
//5
#Override
public void onClick(View v) {
/*Context context = itemView.getContext();
Intent showPhotoIntent = new Intent(context, Pelicula.class);
showPhotoIntent.putExtra(PHOTO_KEY, peli);
context.startActivity(showPhotoIntent);*/
}
public void bindPhoto(Serie mserie) {
serie = mserie;
String Nombre = mserie.getNombreSerie();
if(Nombre.length() >= 25)
{
Nombre = Nombre.substring(0,22);
Nombre = Nombre + "...";
}
Picasso.with(mItemImage.getContext()).load(mserie.getPoster()).into(mItemImage);
mItemDate.setText(Nombre);
mItemDescription.setText(Integer.toString(mserie.getIdTMDB()));
}
}
}
My fragment (where i create the recyclerview)
package com.example.juanfri.seguridadmainactivity;
import android.app.ProgressDialog;
import android.os.AsyncTask;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.Toast;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import java.util.ArrayList;
import static android.content.ContentValues.TAG;
/**
* Created by jlira on 06/06/2017.
*/
public class FragmentoSeriesPelis extends Fragment {
public final String API = "5e2780b2117b40f9e4dfb96572a7bc4d";
public final String URLFOTO ="https://image.tmdb.org/t/p/original/";
private ProgressDialog pDialog;
private RecyclerView recyclerView;
private LinearLayoutManager mLinearLayoutManager;
private ArrayList<Serie> series;
private ArrayList<Pelicula> Pelis;
private RecyclerAdapterSerie mAdapterSerie;
private RecyclerAdapterPelicula mAdapterPeli;
private int pagina;
private String url;
private Button CargarMas;
private String tipo;
private int MaxPag;
#Nullable
#Override
public View onCreateView(LayoutInflater inflater, #Nullable ViewGroup container, #Nullable Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.series_pelis_layout, container, false);
view.setTag(TAG);
Bundle args = getArguments();
series = new ArrayList<>();
Pelis = new ArrayList<>();
MaxPag = 2;
pagina = args.getInt("Page");
url = args.getString("url");
tipo = args.getString("Tipo");
recyclerView = (RecyclerView) view.findViewById(R.id.recyclerViewSerieshoy);
//mLinearLayoutManagerSerie = new LinearLayoutManager(getActivity(), LinearLayoutManager.HORIZONTAL, false);
//recyclerViewSerie.setLayoutManager(mLinearLayoutManagerSerie);
//mAdapterSerie = new RecyclerAdapterSerie(seriesHoy);
//recyclerViewSerie.setAdapter(mAdapterSerie);
new GetSeriesHoy().execute();
CargarMas = (Button) view.findViewById(R.id.buttonCargarMas);
CargarMas.setOnClickListener(new View.OnClickListener()
{
#Override
public void onClick(View v)
{
if(pagina+1<=MaxPag)
{
pagina++;
new GetSeriesHoy().execute();
}
else
{
Toast.makeText(getActivity(), "No hay mas resultados", Toast.LENGTH_LONG).show();
}
}
});
return view;
}
#Override
public void onViewCreated(View view, #Nullable Bundle savedInstanceState) {
super.onViewCreated(view, savedInstanceState);
getActivity().setTitle("Series de Hoy");
}
private class GetSeriesHoy extends AsyncTask<Void, Void, Void> {
#Override
protected void onPreExecute() {
super.onPreExecute();
// Showing progress dialog
pDialog = new ProgressDialog(getActivity());
pDialog.setMessage("Please wait...");
pDialog.setCancelable(false);
pDialog.show();
}
#Override
protected Void doInBackground(Void... arg0) {
HttpHandler sh = new HttpHandler();
// Making a request to url and getting response
//url = "https://api.themoviedb.org/3/tv/airing_today?api_key="+API+"&language=en-US&page="+pagina;
String aux = url+pagina;
String jsonStr = sh.makeServiceCall(aux);
if (jsonStr != null) {
try {
JSONObject jsonObj = new JSONObject(jsonStr);
// Getting JSON Array node
MaxPag = jsonObj.getInt("total_pages");
JSONArray contacts = jsonObj.getJSONArray("results");
// looping through All Contacts
for (int i = 0; i < contacts.length(); i++) {
JSONObject c = contacts.getJSONObject(i);
int IdSerie = i;
int idTMDB = c.getInt("id");
String nombreSerie;
String poster =URLFOTO + c.getString("poster_path");
if(tipo.equalsIgnoreCase("Series"))
{
nombreSerie = c.getString("name");
Serie nuevo = new Serie();
nuevo.setIdSerie(IdSerie);
nuevo.setNombreSerie(nombreSerie);
nuevo.setIdTMDB(idTMDB);
nuevo.setPoster(poster);
series.add(nuevo);
}
else
{
nombreSerie = c.getString("title");
Pelicula nuevo = new Pelicula();
nuevo.setIdPelicula(IdSerie);
nuevo.setNombrePelicula(nombreSerie);
nuevo.setIdTMDB(idTMDB);
nuevo.setPoster(poster);
Pelis.add(nuevo);
}
}
} catch (final JSONException e) {
Toast.makeText(getActivity(),
"Json parsing error: " + e.getMessage(),
Toast.LENGTH_LONG)
.show();
}
} else {
Toast.makeText(getActivity(),
"Couldn't get json from server. Check LogCat for possible errors!",
Toast.LENGTH_LONG)
.show();
}
return null;
}
#Override
protected void onPostExecute(Void result) {
super.onPostExecute(result);
// Dismiss the progress dialog
if (pDialog.isShowing())
pDialog.dismiss();
/**
* Updating parsed JSON data into ListView
* */
//Aqui Realizar la RecycleView BuildUp
if(tipo.equalsIgnoreCase("Series"))
{
mLinearLayoutManager = new LinearLayoutManager(getActivity(), LinearLayoutManager.VERTICAL, false);
recyclerView.setLayoutManager(mLinearLayoutManager);
mAdapterSerie = new RecyclerAdapterSerie(series);
recyclerView.setAdapter(mAdapterSerie);
}else
{
mLinearLayoutManager = new LinearLayoutManager(getActivity(), LinearLayoutManager.VERTICAL, false);
recyclerView.setLayoutManager(mLinearLayoutManager);
mAdapterPeli = new RecyclerAdapterPelicula(Pelis);
recyclerView.setAdapter(mAdapterPeli);
}
}
}
}
Replace your LinearLayoutManager for a GridLayoutManager like this:
private GridLayoutManager mGridLayoutManager;
// ...
mGridLayoutManager = new GridLayoutManager(getActivity(), 2);
Then you can use it the same way as the LinearLayoutManager.
I'm using volley to load data using JSON Parsing in to a recycler view. I've used recylcer view before, but somehow, the downloaded data is persistent this time, meaning its still there after the app is closed, maybe stays in cache. I'm not sure, what I'm doing wrong here. Any help is appreciated, thanks.
Edit: The application is storing downloaded data after the app is closed, which doesn't happen when using recycler view.
This is my Activity Class:
package com.example.recyclerview;
import android.app.ProgressDialog;
import android.content.Intent;
import android.os.AsyncTask;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.support.v7.widget.Toolbar;
import android.util.Log;
import android.view.View;
import android.widget.Toast;
import com.android.volley.Request;
import com.android.volley.RequestQueue;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.JsonArrayRequest;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import java.util.ArrayList;
public class PostActivity extends AppCompatActivity implements
OnItemClick{
private ArrayList<PostData> posts = new ArrayList<>();
private PostRecycleViewAdapter viewAdapter;
private String listingJsonUrl = "https://jsonplaceholder.typicode.com/posts/";
Toolbar toolbar;
private ProgressDialog progressDialog;
private RequestQueue requestQueue;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
toolbar = (Toolbar) findViewById(R.id.toolbar);
progressDialog = new ProgressDialog(this);
progressDialog.setProgressStyle(ProgressDialog.STYLE_SPINNER);
progressDialog.setCancelable(true);
final RecyclerView.LayoutManager viewLayoutManager = new LinearLayoutManager(getApplicationContext());
viewAdapter = new PostRecycleViewAdapter(posts);
final RecyclerView recyclerView = (RecyclerView) findViewById(R.id.recyclerView);
recyclerView.setLayoutManager(viewLayoutManager);
recyclerView.setAdapter(viewAdapter);
viewAdapter.setClickListener(this);
new DownloadData().execute(listingJsonUrl);
}
#Override
public void onClick(View view, int position) {
final PostData data = posts.get(position);
String title;
int id;
Intent commentIntent = new Intent(this, CommentsActivity.class);
id = data.getId();
title = data.getTitle();
if(title.length() > 25){
title = title.substring(0,25);
title = title.concat("..");
}
commentIntent.putExtra("title",title) ;
commentIntent.putExtra("id", id);
startActivity(commentIntent);
}
class DownloadData extends AsyncTask<String, String, String>{
#Override
protected void onPostExecute(String s) {
super.onPostExecute(s);
}
#Override
protected String doInBackground(String... url) {
JsonArrayRequest jsonArrayRequest = new JsonArrayRequest(Request.Method.GET, url[0], new Response.Listener<JSONArray>() {
#Override
public void onResponse(JSONArray response) {
try {
JSONArray jsonArray = new JSONArray(response.toString());
for (int i = 0; i < jsonArray.length(); i++) {
JSONObject jsonObject = jsonArray.getJSONObject(i);
PostData postData = new PostData(jsonObject.getInt("id"),jsonObject.getString("title"), jsonObject.getString("body"));
posts.add(postData);
viewAdapter.notifyDataSetChanged();
}
}
catch (JSONException e)
{
e.printStackTrace();
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Log.d("JsonError", error.getMessage());
}
});
getRequestQueue().add(jsonArrayRequest);
return null;
}
}
public RequestQueue getRequestQueue()
{
if (requestQueue == null)
{
requestQueue = com.android.volley.toolbox.Volley.newRequestQueue(getApplicationContext());
}
return requestQueue;
}
}
This is my RecyclerView Adapter Class:
package com.example.recyclerview;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;
import java.util.List;
public class PostRecycleViewAdapter extends RecyclerView.Adapter<PostRecycleViewAdapter.ViewHolder>
{
private List<PostData> postData;
private OnItemClick itemClick;
public class ViewHolder extends RecyclerView.ViewHolder implements View.OnClickListener{
public TextView title, body;
public ViewHolder(View view){
super(view);
title = (TextView) view.findViewById(R.id.title);
body = (TextView) view.findViewById(R.id.body);
view.setTag(view);
view.setOnClickListener(this);
}
#Override
public void onClick(View view) {
if(itemClick != null) itemClick.onClick(view, getAdapterPosition());
}
}
public PostRecycleViewAdapter(List<PostData> postData)
{
this.postData = postData;
}
#Override
public ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View itemLayout = LayoutInflater.from(parent.getContext()).inflate(R.layout.post_recycler_view,parent,false);
return new ViewHolder(itemLayout);
}
#Override
public void onBindViewHolder(PostRecycleViewAdapter.ViewHolder holder, int position) {
PostData data = postData.get(position);
holder.title.setText(data.getTitle());
holder.body.setText(data.getBody());
}
#Override
public int getItemCount() {
return postData.size();
}
#Override
public void onAttachedToRecyclerView(RecyclerView recyclerView) {
super.onAttachedToRecyclerView(recyclerView);}
public void setClickListener(OnItemClick itemClick) {
this.itemClick = itemClick;
}
}
And this is the data item class:
package com.example.recyclerview;
public class PostData {
private String title, body;
private int id;
public PostData(int id, String title, String body)
{
this.id = id;
this.title = title;
this.body = body;
}
public String getTitle() {
return title;
}
public String getBody() {
return body;
}
public int getId() {
return id;
}
}
Inside my tab bar i want to show my data in Recycler view by using json parsing using volley library. I parsed the data and it showing in toast perfectly.But in Recycler view its not showing Here is my codes.
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Toast;
import com.android.volley.Request;
import com.android.volley.RequestQueue;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.ImageLoader;
import com.android.volley.toolbox.JsonObjectRequest;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import javax.xml.transform.ErrorListener;
import info.tatwa.adupter.AdupterBoxOffice;
import info.tatwa.extras.Keys;
import info.tatwa.extras.UrlEndPoint;
import info.tatwa.login.L;
import info.tatwa.model.Movies;
import info.tatwa.network.MyApplication;
import info.tatwa.network.VolleySingleton;
import info.tatwa.newnav.R;
import info.tatwa.extras.UrlEndPoint.*;
import info.tatwa.extras.Keys.EndpointBoxOffice.*;
public class FragmentBoxOffice extends Fragment {
private VolleySingleton volleySingleton;
private RequestQueue requestQueue;
private AdupterBoxOffice adupterBoxOffice;
private ArrayList<Movies>listMovie = new ArrayList<>();
private ImageLoader imageLoader;
private DateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");
public static final String ROTET_TOMATO_URL_BOX_OFFICE="My url is here"
private static final String ARG_PARAM1 = "param1";
private static final String ARG_PARAM2 = "param2";
private RecyclerView listMovieHits;
// TODO: Rename and change types of parameters
private String mParam1;
private String mParam2;
/**
* Use this factory method to create a new instance of
* this fragment using the provided parameters.
*
* #param param1 Parameter 1.
* #param param2 Parameter 2.
* #return A new instance of fragment FragmentBoxOffice.
*/
public static FragmentBoxOffice newInstance(String param1, String param2) {
FragmentBoxOffice fragment = new FragmentBoxOffice();
Bundle args = new Bundle();
args.putString(ARG_PARAM1, param1);
args.putString(ARG_PARAM2, param2);
fragment.setArguments(args);
return fragment;
}
public static String getRequestUrl(int limit){
//ROTET_TOMATO_URL_BOX_OFFICE+"?apikey="+ MyApplication.ROTET_TOMATO_API_KEY+"&limit="+limit;
return UrlEndPoint.URL_BOX_OFFICE +
UrlEndPoint.URL_CHAR_QUASTIAN+
UrlEndPoint.URL_CHAR_PAREM_APIKEY +
MyApplication.ROTET_TOMATO_API_KEY +
UrlEndPoint.URL_CHAR_APPEND+
UrlEndPoint.URL_CHAR_PAREM_LIMIT + limit;
}
public FragmentBoxOffice() {
// Required empty public constructor
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
if (getArguments() != null) {
mParam1 = getArguments().getString(ARG_PARAM1);
mParam2 = getArguments().getString(ARG_PARAM2);
}
volleySingleton = VolleySingleton.getsInstance();
requestQueue = volleySingleton.getmRequestQueue();
senJsonRequest();
}
public void senJsonRequest(){
JsonObjectRequest request = new JsonObjectRequest(Request.Method.GET, getRequestUrl(10), (String)null, new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject response) {
paresJSONResponse(response);
listMovie =paresJSONResponse(response);
adupterBoxOffice.setMovieList(listMovie);
L.t(getActivity(), response.toString());
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Toast.makeText(getActivity(),"Error"+error.getMessage(),Toast.LENGTH_SHORT).show();
}
});
requestQueue.add(request);
}
public ArrayList<Movies> paresJSONResponse(JSONObject response){
ArrayList<Movies> listMovie = new ArrayList<>();
if(response ==null|| response.length()==0 ){
return null;
}
try {
StringBuilder data = new StringBuilder();
JSONArray arrayMovie = response.getJSONArray(Keys.EndpointBoxOffice.KEY_MOVIES);
Log.v("BIKASH", "JSON Object id" + arrayMovie);
for(int i = 0; i<arrayMovie.length();i++){
JSONObject currentMovies= arrayMovie.getJSONObject(i);
Long id =currentMovies.getLong(Keys.EndpointBoxOffice.KEY_ID);
String title=currentMovies.getString(Keys.EndpointBoxOffice.KEY_TITLE);
JSONObject objectReleaseDates=currentMovies.getJSONObject(Keys.EndpointBoxOffice.KEY_RELEASE_DATES);
String releaseDate=null;
if(objectReleaseDates.has(Keys.EndpointBoxOffice.KEY_THEATER)){
releaseDate = objectReleaseDates.getString(Keys.EndpointBoxOffice.KEY_THEATER);
}
else {
releaseDate="NA";
}
int audianceRatting=-1;
JSONObject objectRatting = currentMovies.getJSONObject(Keys.EndpointBoxOffice.KEY_RATINGS);
{
if(objectRatting.has(Keys.EndpointBoxOffice.KEY_AUDIENCE_SCORE)){
audianceRatting=objectRatting.getInt(Keys.EndpointBoxOffice.KEY_AUDIENCE_SCORE);
}
}
String synuypsis = currentMovies.getString(Keys.EndpointBoxOffice.KEY_SYNOPSIS);
String urlThumbnel = null;
JSONObject objPoster = currentMovies.getJSONObject(Keys.EndpointBoxOffice.KEY_THUMBNAIL);
if(objPoster.has(Keys.EndpointBoxOffice.KEY_THUMBNAIL)){
urlThumbnel = objPoster.getString(Keys.EndpointBoxOffice.KEY_THUMBNAIL);
}
Movies movie =new Movies();
movie.setId(id);
movie.setTitle(title);
Date date = dateFormat.parse(releaseDate);
movie.setReleaseDateTheater(date);
movie.setAudienceScore(audianceRatting);
movie.setSynopsis(synuypsis);
movie.setUrlThumbnail(urlThumbnel);
listMovie.add(movie);
// data.append(id + "\n");
}
L.t(getActivity(),listMovie.toString());
} catch (JSONException e) {
e.printStackTrace();
} catch (ParseException e) {
e.printStackTrace();
}
return listMovie;
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
View view =inflater.inflate(R.layout.fragment_fragment_box_office, container, false);
listMovieHits =(RecyclerView)view.findViewById(R.id.listMovieHits);
listMovieHits.setLayoutManager(new LinearLayoutManager(getActivity()));
adupterBoxOffice = new AdupterBoxOffice(getActivity());
listMovieHits.setAdapter(adupterBoxOffice);
senJsonRequest();
return view;
}
}
My Adupter
import android.content.Context;
import android.support.v4.app.FragmentActivity;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.RatingBar;
import android.widget.TextView;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.ImageLoader;
import java.util.ArrayList;
import info.tatwa.model.Movies;
import info.tatwa.myfragment.FragmentBoxOffice;
import info.tatwa.network.VolleySingleton;
import info.tatwa.newnav.R;
public class AdupterBoxOffice extends RecyclerView.Adapter<AdupterBoxOffice.ViewHolderBoxOffice> {
private LayoutInflater layoutInflater;
FragmentBoxOffice activity;
private ArrayList<Movies> listMovie = new ArrayList<>();
private VolleySingleton volleySingleton;
private ImageLoader imageLoader;
public AdupterBoxOffice(Context context){
layoutInflater=LayoutInflater.from(context);
volleySingleton=VolleySingleton.getsInstance();
imageLoader = volleySingleton.getImageLoader();
}
public void setMovieList(ArrayList<Movies>listMovie){
this.listMovie = listMovie;
notifyItemRangeChanged(0,listMovie.size());
}
#Override
public ViewHolderBoxOffice onCreateViewHolder(ViewGroup parent, int viewType) {
layoutInflater = LayoutInflater.from(parent.getContext());
View view = layoutInflater.inflate(R.layout.movie_list_itom,parent,false);
ViewHolderBoxOffice viewHolder =new ViewHolderBoxOffice(view);
return viewHolder;
}
#Override
public void onBindViewHolder(final ViewHolderBoxOffice holder, int position) {
Movies currentMovie =listMovie.get(position);
holder.movieTitle.setText(currentMovie.getTitle());
holder.movieReleaseDate.setText(currentMovie.getReleaseDateTheater().toString());
holder.movieRatting.setRating(currentMovie.getAudienceScore()/20.0f);
String urlThumbnel = currentMovie.getUrlThumbnail();
if(urlThumbnel!=null){
imageLoader.get(urlThumbnel, new ImageLoader.ImageListener() {
#Override
public void onResponse(ImageLoader.ImageContainer response, boolean isImmediate) {
holder.imagePoster.setImageBitmap(response.getBitmap());
}
#Override
public void onErrorResponse(VolleyError error) {
}
});
}
}
#Override
public int getItemCount() {
return listMovie.size();
}
static class ViewHolderBoxOffice extends RecyclerView.ViewHolder {
private ImageView imagePoster;
private TextView movieTitle;
private TextView movieReleaseDate;
private RatingBar movieRatting;
public ViewHolderBoxOffice(View itemView) {
super(itemView);
imagePoster=(ImageView)itemView.findViewById(R.id.movieThumbnail);
movieTitle =(TextView)itemView.findViewById(R.id.movieTitle);
movieReleaseDate=(TextView)itemView.findViewById(R.id.movieReleaseDate);
movieRatting=(RatingBar)itemView.findViewById(R.id.movieAudienceScore);
}
}
}
And My Model class
import android.os.Parcel;
import android.os.Parcelable;
import java.util.Date;
public class Movies{
private long id;
private String title;
private Date releaseDateTheater;
private int audienceScore;
private String synopsis;
private String urlThumbnail;
private String urlSelf;
private String urlCast;
private String urlReviews;
private String urlSimilar;
public Movies() {
}
public Movies(long id,
String title,
Date releaseDateTheater,
int audienceScore,
String synopsis,
String urlThumbnail,
String urlSelf,
String urlCast,
String urlReviews,
String urlSimilar) {
this.id = id;
this.title = title;
this.releaseDateTheater = releaseDateTheater;
this.audienceScore = audienceScore;
this.synopsis = synopsis;
this.urlThumbnail = urlThumbnail;
this.urlSelf = urlSelf;
this.urlCast = urlCast;
this.urlReviews = urlReviews;
this.urlSimilar = urlSimilar;
}
public long getId() {
return id;
}
public void setId(long id) {
this.id = id;
}
public String getTitle() {
return title;
}
public void setTitle(String title) {
this.title = title;
}
public Date getReleaseDateTheater() {
return releaseDateTheater;
}
public void setReleaseDateTheater(Date releaseDateTheater) {
this.releaseDateTheater = releaseDateTheater;
}
public int getAudienceScore() {
return audienceScore;
}
public void setAudienceScore(int audienceScore) {
this.audienceScore = audienceScore;
}
public String getSynopsis() {
return synopsis;
}
public void setSynopsis(String synopsis) {
this.synopsis = synopsis;
}
public String getUrlThumbnail() {
return urlThumbnail;
}
public void setUrlThumbnail(String urlThumbnail) {
this.urlThumbnail = urlThumbnail;
}
public String getUrlSelf() {
return urlSelf;
}
public void setUrlSelf(String urlSelf) {
this.urlSelf = urlSelf;
}
public String getUrlCast() {
return urlCast;
}
public void setUrlCast(String urlCast) {
this.urlCast = urlCast;
}
public String getUrlReviews() {
return urlReviews;
}
public void setUrlReviews(String urlReviews) {
this.urlReviews = urlReviews;
}
public String getUrlSimilar() {
return urlSimilar;
}
public void setUrlSimilar(String urlSimilar) {
this.urlSimilar = urlSimilar;
}
#Override
public String toString() {
return "\nID: " + id +
"\nTitle " + title +
"\nDate " + releaseDateTheater +
"\nSynopsis " + synopsis +
"\nScore " + audienceScore +
"\nurlThumbnail " + urlThumbnail +
"\nurlSelf " + urlSelf +
"\nurlCast " + urlCast +
"\nurlReviews " + urlReviews +
"\nurlSimilar " + urlSimilar +
"\n";
}
}
Please help me out .. Thanks in advance ..
After adupterBoxOffice.setMovieList(listMovie);
try add adupterBoxOffice.notifyDataSetChanged();
I found my solution.I put some wrong key during pars the Json. That's why my ArrayList returning zero.
Many many thanks to all for helping me out.
I'm making a parse json app and i've got an issue !
I've got these codes :
Temps.java :
package model;
public class Temps {
private String direction;
private String ligne;
private String temps;
public Temps() {
}
public Temps(String direction, String ligne, String temps) {
this.direction = direction;
this.ligne = ligne;
this.temps = temps;
}
public String getDirection() {
return direction;
}
public void setDirection(String thumbnailUrl) {
this.direction = thumbnailUrl;
}
public String getTemps() {
return temps;
}
public void setTemps(String temps) {
this.temps = temps;
}
public String getLigne() {
return ligne;
}
public void setLigne(String ligne) {
this.ligne = ligne;
}
}
TempsActivity.java :
package activity;
import android.content.Intent;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentTransaction;
import android.support.v4.widget.SwipeRefreshLayout;
import android.support.v7.app.ActionBarActivity;
import android.support.v7.widget.Toolbar;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ListView;
import android.widget.Toast;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.VolleyLog;
import com.android.volley.toolbox.JsonArrayRequest;
import com.example.pierre.tan.R;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import adapter.CustomListAdapterTemps;
import app.AppController;
import model.Temps;
public class TempsActivity extends ActionBarActivity {
private Toolbar mToolbar;
private static final String TAG = MainActivity.class.getSimpleName();
// Movies json url
private List<Temps> directionList = new ArrayList<Temps>();
private ListView listView2;
private CustomListAdapterTemps adapter;
private SwipeRefreshLayout swipeLayout;
private Menu menu;
private MenuInflater inflater;
HashMap<String, String> lieumap = new HashMap<String, String>();
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.activity_temps, container, false);
// Inflate the layout for this fragment
return rootView;
}
public void onActivityCreated(Bundle savedInstanceState) {
Intent intent = getIntent();
final String url = "https://open.tan.fr/ewp/tempsattente.json/" + intent.getExtras().getString("text") + " ";
System.out.println(intent.getExtras().getString("text") + " Test Test ");
listView2 = (ListView) findViewById(R.id.list_temps);
// movieList is an empty array at this point.
adapter = new CustomListAdapterTemps(getParent(), directionList);
listView2.setAdapter(adapter);
// Showing progress dialog before making http request
swipeLayout = (SwipeRefreshLayout) findViewById(R.id.container);
swipeLayout.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() {
#Override
public void onRefresh() {
Toast.makeText(getApplication(), "Rechargement...", Toast.LENGTH_SHORT).show();
JsonArrayRequest movieReq = new JsonArrayRequest(url,
new Response.Listener<JSONArray>() {
#Override
public void onResponse(JSONArray response) {
Log.d(TAG, response.toString());
// Parsing json
for (int i = 0; i < response.length(); i++) {
try {
JSONObject obj = null;
try {
obj = response.getJSONObject(i);
} catch (JSONException e) {
e.printStackTrace();
}
Temps temps = new Temps();
temps.setDirection(obj.getString("terminus"));
temps.setLigne(obj.getString("sens"));
temps.setTemps(obj.getString("temps"));
} 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());
Toast.makeText(getApplicationContext(), "No internet connection !", Toast.LENGTH_LONG).show();
}
});
AppController.getInstance().addToRequestQueue(movieReq);
swipeLayout.setRefreshing(false);
}
});
swipeLayout.setColorScheme(android.R.color.holo_blue_bright,
android.R.color.holo_green_light,
android.R.color.holo_orange_light,
android.R.color.holo_red_light);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.menu_main, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
//noinspection SimplifiableIfStatement
if (id == R.id.action_settings) {
return true;
}
if (id == R.id.action_search) {
String title = getString(R.string.app_name);
Fragment fragment = null;
fragment = new ArretsFragment();
title = "Rechercher";
FragmentManager fragmentManager = getSupportFragmentManager();
FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction();
fragmentTransaction.replace(R.id.container_body, fragment);
fragmentTransaction.commit();
getSupportActionBar().setTitle(title);
return true;
}
return super.onOptionsItemSelected(item);
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_temps);
mToolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(mToolbar);
getSupportActionBar().setDisplayShowHomeEnabled(true);
Intent intent = getIntent();
final String url = "https://open.tan.fr/ewp/tempsattente.json/" + intent.getExtras().getString("text") + " ";
listView2 = (ListView) findViewById(R.id.list_temps);
// movieList is an empty array at this point.
adapter = new CustomListAdapterTemps(this, directionList);
listView2.setAdapter(adapter);
JsonArrayRequest movieReq = new JsonArrayRequest(url,
new Response.Listener<JSONArray>() {
#Override
public void onResponse(JSONArray response) {
Log.d(TAG, response.toString());
// Parsing json
for (int i = 0; i < response.length(); i++) {
try {
JSONObject obj = null;
try {
obj = response.getJSONObject(i);
} catch (JSONException e) {
e.printStackTrace();
}
Temps temps = new Temps();
temps.setDirection(obj.getString("terminus"));
temps.setLigne(obj.getString("sens"));
temps.setTemps(obj.getString("temps"));
} 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());
Toast.makeText(getApplicationContext(), "No internet connection !", Toast.LENGTH_LONG).show();
}
});
// Adding request to request queue
AppController.getInstance().addToRequestQueue(movieReq);
}
}
And CustomListViewAdapterTemps.java :
package adapter;
import android.app.Activity;
import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.TextView;
import com.android.volley.toolbox.ImageLoader;
import com.example.pierre.tan.R;
import java.util.List;
import app.AppController;
import model.Temps;
public class CustomListAdapterTemps extends BaseAdapter {
private Activity activity;
private LayoutInflater inflater;
private List<Temps> directionItems;
ImageLoader imageLoader = AppController.getInstance().getImageLoader();
public CustomListAdapterTemps(Activity activity, List<Temps> directionItems) {
this.activity = activity;
this.directionItems = directionItems;
}
#Override
public int getCount() {
return directionItems.size();
}
#Override
public Object getItem(int location) {
return directionItems.get(location);
}
#Override
public long getItemId(int position) {
return position;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
if (inflater == null)
inflater = (LayoutInflater) activity
.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
if (convertView == null)
convertView = inflater.inflate(R.layout.list_rowtemps, null);
if (imageLoader == null)
imageLoader = AppController.getInstance().getImageLoader();
TextView direction = (TextView) convertView.findViewById(R.id.direction);
TextView ligne = (TextView) convertView.findViewById(R.id.ligne);
TextView temps = (TextView) convertView.findViewById(R.id.temps);
// getting movie data for the row
Temps m = directionItems.get(position);
// title
direction.setText(m.getDirection());
ligne.setText(m.getLigne());
temps.setText(m.getTemps());
return convertView;
}
}
I don't understand why I get a Blank ListView because the url json work and in the console we can see just the json Request with the data. If someone can help me it would be very nice!
That's because your directionList is empty. In your loops, where you parse JSON, you're creating your Temps object:
Temps temps = new Temps();
temps.setDirection(obj.getString("terminus"));
temps.setLigne(obj.getString("sens"));
temps.setTemps(obj.getString("temps"));
but you're not adding them to your directionsList. Add this line just after the above:
directionList.add(temps);
Hi i think that you are not adding your response to the list, please try this:
Temps temps = new Temps();
temps.setDirection(obj.getString("terminus"));
temps.setLigne(obj.getString("sens"));
temps.setTemps(obj.getString("temps"));
directionList.add(temps);