I'm trying to get all the JSON result into my listview. I have successfully retrieved the data but it keeps only shows one data (example if JNE, only showing OKE result). I'm using Retrofit. Below is the example JSON data from the documentation that I want to show all in my listview. Please help me why it is not showing all the result. Thank you.
{
"rajaongkir":{
"query":{
"origin":"501",
"destination":"114",
"weight":1700,
"courier":"jne"
},
"status":{
"code":200,
"description":"OK"
},
"origin_details":{
"city_id":"501",
"province_id":"5",
"province":"DI Yogyakarta",
"type":"Kota",
"city_name":"Yogyakarta",
"postal_code":"55000"
},
"destination_details":{
"city_id":"114",
"province_id":"1",
"province":"Bali",
"type":"Kota",
"city_name":"Denpasar",
"postal_code":"80000"
},
"results":[
{
"code":"jne",
"name":"Jalur Nugraha Ekakurir (JNE)",
"costs":[
{
"service":"OKE",
"description":"Ongkos Kirim Ekonomis",
"cost":[
{
"value":38000,
"etd":"4-5",
"note":""
}
]
},
{
"service":"REG",
"description":"Layanan Reguler",
"cost":[
{
"value":44000,
"etd":"2-3",
"note":""
}
]
},
{
"service":"SPS",
"description":"Super Speed",
"cost":[
{
"value":349000,
"etd":"",
"note":""
}
]
},
{
"service":"YES",
"description":"Yakin Esok Sampai",
"cost":[
{
"value":98000,
"etd":"1-1",
"note":""
}
]
}
]
}
]
}
}
My Call
public void getCoast(String origin,
String destination,
String weight,
String courier) {
Retrofit retrofit = new Retrofit.Builder()
.baseUrl(ApiUrl.URL_ROOT_HTTPS)
.addConverterFactory(GsonConverterFactory.create())
.build();
ApiService service = retrofit.create(ApiService.class);
Call<ItemCost> call = service.getCost(
"c5333cdcc37b3511c909088d99587fd8",
origin,
destination,
weight,
courier
);
call.enqueue(new Callback<ItemCost>() {
#Override
public void onResponse(Call<ItemCost> call, Response<ItemCost> response) {
Log.v("wow", "json : " + new Gson().toJson(response));
progressDialog.dismiss();
if (response.isSuccessful()) {
int statusCode = response.body().getRajaongkir().getStatus().getCode();
if (statusCode == 200) {
LayoutInflater inflater = (LayoutInflater) getSystemService(Context.LAYOUT_INFLATER_SERVICE);
View alertLayout = inflater.inflate(R.layout.custom_results, null);
alert = new AlertDialog.Builder(MainActivity.this);
alert.setTitle("Result Cost");
alert.setMessage("this result your search");
alert.setView(alertLayout);
alert.setCancelable(true);
ad = alert.show();
String originCity = response.body().getRajaongkir().getOriginDetails().getCityName();
String originPostalCode = response.body().getRajaongkir().getOriginDetails().getPostalCode();
String destinationCity = response.body().getRajaongkir().getDestinationDetails().getCityName();
String destinationPostalCode = response.body().getRajaongkir().getDestinationDetails().getPostalCode();
//results
List<com.bagicode.cekongkir.model.cost.Result> ListResults = response.body().getRajaongkir().getResults();
//costs
List<com.bagicode.cekongkir.model.cost.Cost> ListCosts = response.body().getRajaongkir().getResults().get(0).getCosts();
//cost
List<com.bagicode.cekongkir.model.cost.Cost_> ListCost = response.body().getRajaongkir().getResults().get(0).getCosts().get(0).getCost();
mListView = (ListView) alertLayout.findViewById(R.id.listItem);
adapter_results = new ResultsAdapter(MainActivity.this, originCity, originPostalCode, destinationCity, destinationPostalCode, ListResults, ListCosts, ListCost);
mListView.setAdapter(adapter_results);
mListView.setClickable(true);
adapter_results.notifyDataSetChanged();
} else {
String message = response.body().getRajaongkir().getStatus().getDescription();
Toast.makeText(MainActivity.this, message, Toast.LENGTH_SHORT).show();
}
} else {
String error = "Error Retrive Data from Server !!!";
Toast.makeText(MainActivity.this, error, Toast.LENGTH_SHORT).show();
}
}
#Override
public void onFailure(Call<ItemCost> call, Throwable t) {
progressDialog.dismiss();
Toast.makeText(MainActivity.this, "Message : Error " + t.getMessage(), Toast.LENGTH_SHORT).show();
}
});
}
Api Interface
// Cost
#FormUrlEncoded
#POST("cost")
Call<ItemCost> getCost (#Field("key") String Token,
#Field("origin") String origin,
#Field("destination") String destination,
#Field("weight") String weight,
#Field("courier") String courier);
Pojo
ItemCost
public class ItemCost {
#SerializedName("rajaongkir")
#Expose
private Rajaongkir rajaongkir;
public Rajaongkir getRajaongkir() {
return rajaongkir;
}
public void setRajaongkir(Rajaongkir rajaongkir) {
this.rajaongkir = rajaongkir;
}
}
rajaOngkir Pojo (List)
public class Rajaongkir {
#SerializedName("query")
#Expose
private Query query;
#SerializedName("status")
#Expose
private Status status;
#SerializedName("origin_details")
#Expose
private OriginDetails originDetails;
#SerializedName("destination_details")
#Expose
private DestinationDetails destinationDetails;
#SerializedName("results")
#Expose
private List<Result> results = null;
public Query getQuery() {
return query;
}
public void setQuery(Query query) {
this.query = query;
}
public Status getStatus() {
return status;
}
public void setStatus(Status status) {
this.status = status;
}
public OriginDetails getOriginDetails() {
return originDetails;
}
public void setOriginDetails(OriginDetails originDetails) {
this.originDetails = originDetails;
}
public DestinationDetails getDestinationDetails() {
return destinationDetails;
}
public void setDestinationDetails(DestinationDetails destinationDetails) {
this.destinationDetails = destinationDetails;
}
public List<Result> getResults() {
return results;
}
public void setResults(List<Result> results) {
this.results = results;
}
}
Results List Pojo
public class Result {
#SerializedName("code")
#Expose
private String code;
#SerializedName("name")
#Expose
private String name;
#SerializedName("costs")
#Expose
private List<Cost> costs = null;
public Result(String code, String name, List<Cost> costs) {
this.code = code;
this.name = name;
this.costs = costs;
}
public Result(String code, String name) {
this.code = code;
this.name = name;
}
public String getCode() {
return code;
}
public void setCode(String code) {
this.code = code;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public List<Cost> getCosts() {
return costs;
}
public void setCosts(List<Cost> costs) {
this.costs = costs;
}
}
Costs List Pojo
public class Cost {
#SerializedName("service")
#Expose
private String service;
#SerializedName("description")
#Expose
private String description;
#SerializedName("cost")
#Expose
private List<Cost_> cost = null;
public Cost(String service, String description) {
this.service = service;
this.description = description;
}
public String getService() {
return service;
}
public void setService(String service) {
this.service = service;
}
public String getDescription() {
return description;
}
public void setDescription(String description) {
this.description = description;
}
public List<Cost_> getCost() {
return cost;
}
public void setCost(List<Cost_> cost) {
this.cost = cost;
}
}
cost list Pojo
public class Cost_ {
#SerializedName("value")
#Expose
private Integer value;
#SerializedName("etd")
#Expose
private String etd;
#SerializedName("note")
#Expose
private String note;
public Cost_(Integer value, String etd, String note) {
this.value = value;
this.etd = etd;
this.note = note;
}
public Integer getValue() {
return value;
}
public void setValue(Integer value) {
this.value = value;
}
public String getEtd() {
return etd;
}
public void setEtd(String etd) {
this.etd = etd;
}
public String getNote() {
return note;
}
public void setNote(String note) {
this.note = note;
}
}
ListView Adapter
public class ResultsAdapter extends BaseAdapter {
private Activity activity;
private LayoutInflater inflater;
private List<Result> resulsItems;
private List<Cost> costsItems;
private List<Cost_> costItems;
TextView tv_origin, tv_destination, tv_expedisi, tv_coast, tv_time;
private String originCity, destinationCity, originPostalCode, destinationPostalCode;
public ResultsAdapter(MainActivity mainActivity, String originCity, String originPostalCode, String destinationCity, String destinationPostalCode, List<Result> listResults, List<Cost> listCosts, List<Cost_> listCost) {
this.activity = mainActivity;
this.originCity = originCity;
this.originPostalCode = originPostalCode;
this.destinationCity = destinationCity;
this.destinationPostalCode = destinationPostalCode;
this.resulsItems = listResults;
this.costsItems = listCosts;
this.costItems = listCost;
}
#Override
public int getCount() {
return resulsItems.size();
}
#Override
public Object getItem(int location) {
return resulsItems.get(location);
}
#Override
public long getItemId(int position) {
return position;
}
#Override
public View getView(int i, View convertView, ViewGroup parent) {
if (inflater == null)
inflater = (LayoutInflater) activity
.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
if (convertView == null)
convertView = inflater.inflate(R.layout.item_results, null);
tv_origin = (TextView) convertView.findViewById(R.id.tv_origin);
tv_destination = (TextView) convertView.findViewById(R.id.tv_destination);
tv_expedisi = convertView.findViewById(R.id.tv_expedisi);
tv_coast = convertView.findViewById(R.id.tv_coast);
tv_time = convertView.findViewById(R.id.tv_time);
results = resulsItems.get(i);
costs = costsItems.get(i);
cost = costItems.get(i);
tv_origin.setText(originCity);
tv_destination.setText(destinationCity);
tv_expedisi.setText(results.getName());
tv_coast.setText(String.valueOf(cost.getValue()));
tv_time.setText(cost.getEtd());
return convertView;
}
}
ACtual Response Log
{"body":{"rajaongkir":{"destination_details":{"city_id":"114","city_name":"Denpasar","postal_code":"80227","province":"Bali","province_id":"1","type":"Kota"},"origin_details":{"city_id":"501","city_name":"Yogyakarta","postal_code":"55111","province":"DI Yogyakarta","province_id":"5","type":"Kota"},"query":{"courier":"jne","destination":"114","key":"c5333cdcc37b3511c909088d99587fd8","origin":"501","weight":1000},"results":[{"code":"jne","costs":[{"cost":[{"etd":"4-5","note":"","value":26000}],"description":"Ongkos Kirim Ekonomis","service":"OKE"},{"cost":[{"etd":"2-3","note":"","value":28000}],"description":"Layanan Reguler","service":"REG"},{"cost":[{"etd":"1-1","note":"","value":43000}],"description":"Yakin Esok Sampai","service":"YES"}],"name":"Jalur Nugraha Ekakurir (JNE)"}],"status":{"code":200,"description":"OK"}}},"rawResponse":{"body":{"contentLength":823,"contentType":{"mediaType":"application/json","subtype":"json","type":"application"}},"code":200,"handshake":{"cipherSuite":"TLS_ECDHE_RSA_WITH_AES_128_GCM_SHA256","localCertificates":[],"peerCertificates":[{"hash":-1,"type":"X.509"},{"hash":-1,"type":"X.509"}],"tlsVersion":"TLS_1_2"},"headers":{"namesAndValues":["Date","Thu, 02 May 2019 13:09:21 GMT","Server","Apache/2.4.7 (Ubuntu)","Content-Length","823","Keep-Alive","timeout\u003d15, max\u003d100","Connection","Keep-Alive","Content-Type","application/json"]},"message":"OK","networkResponse":{"code":200,"handshake":{"cipherSuite":"TLS_ECDHE_RSA_WITH_AES_128_GCM_SHA256","localCertificates":[],"peerCertificates":[{"hash":-1,"type":"X.509"},{"hash":-1,"type":"X.509"}],"tlsVersion":"TLS_1_2"},"headers":{"namesAndValues":["Date","Thu, 02 May 2019 13:09:21 GMT","Server","Apache/2.4.7 (Ubuntu)","Content-Length","823","Keep-Alive","timeout\u003d15, max\u003d100","Connection","Keep-Alive","Content-Type","application/json"]},"message":"OK","protocol":"HTTP_1_1","receivedResponseAtMillis":1556802600578,"request":{"body":{"encodedNames":["key","origin","destination","weight","courier"],"encodedValues":["c5333cdcc37b3511c909088d99587fd8","501","114","1000","jne"]},"cacheControl":{"isPrivate":false,"isPublic":false,"maxAgeSeconds":-1,"maxStaleSeconds":-1,"minFreshSeconds":-1,"mustRevalidate":false,"noCache":false,"noStore":false,"noTransform":false,"onlyIfCached":false,"sMaxAgeSeconds":-1},"headers":{"namesAndValues":["Content-Type","application/x-www-form-urlencoded","Content-Length","87","Host","api.rajaongkir.com","Connection","Keep-Alive","Accept-Encoding","gzip","User-Agent","okhttp/3.3.0"]},"method":"POST","tag":{"body":{"encodedNames":["key","origin","destination","weight","courier"],"encodedValues":["c5333cdcc37b3511c909088d99587fd8","501","114","1000","jne"]},"headers":{"namesAndValues":[]},"method":"POST","url":{"host":"api.rajaongkir.com","password":"","pathSegments":["starter","cost"],"port":443,"scheme":"https","url":"https://api.rajaongkir.com/starter/cost","username":""}},"url":{"host":"api.rajaongkir.com","password":"","pathSegments":["starter","cost"],"port":443,"scheme":"https","url":"https://api.rajaongkir.com/starter/cost","username":""}},"sentRequestAtMillis":1556802600415},"protocol":"HTTP_1_1","receivedResponseAtMillis":1556802600578,"request":{"body":{"encodedNames":["key","origin","destination","weight","courier"],"encodedValues":["c5333cdcc37b3511c909088d99587fd8","501","114","1000","jne"]},"headers":{"namesAndValues":["Content-Type","application/x-www-form-urlencoded","Content-Length","87"]},"method":"POST","tag":{"body":{"encodedNames":["key","origin","destination","weight","courier"],"encodedValues":["c5333cdcc37b3511c909088d99587fd8","501","114","1000","jne"]},"headers":{"namesAndValues":[]},"method":"POST","url":{"host":"api.rajaongkir.com","password":"","pathSegments":["starter","cost"],"port":443,"scheme":"https","url":"https://api.rajaongkir.com/starter/cost","username":""}},"url":{"host":"api.rajaongkir.com","password":"","pathSegments":["starter","cost"],"port":443,"scheme":"https","url":"https://api.rajaongkir.com/starter/cost","username":""}},"sentRequestAtMillis":1556802600415}}
public void getCoast(String origin,
String destination,
String weight,
String courier) {
Retrofit retrofit = new Retrofit.Builder()
.baseUrl(ApiUrl.URL_ROOT_HTTPS)
.addConverterFactory(GsonConverterFactory.create())
.build();
ApiService service = retrofit.create(ApiService.class);
Call<ItemCost> call = service.getCost(
"c5333cdcc37b3511c909088d99587fd8",
origin,
destination,
weight,
courier
);
call.enqueue(new Callback<ItemCost>() {
#Override
public void onResponse(Call<ItemCost> call, Response<ItemCost> response) {
Log.v("wow", "json : " + new Gson().toJson(response));
progressDialog.dismiss();
if (response.isSuccessful()) {
int statusCode = response.body().getRajaongkir().getStatus().getCode();
if (statusCode == 200) {
LayoutInflater inflater = (LayoutInflater) getSystemService(Context.LAYOUT_INFLATER_SERVICE);
View alertLayout = inflater.inflate(R.layout.custom_results, null);
alert = new AlertDialog.Builder(MainActivity.this);
alert.setTitle("Result Cost");
alert.setMessage("this result your search");
alert.setView(alertLayout);
alert.setCancelable(true);
ad = alert.show();
String originCity = response.body().getRajaongkir().getOriginDetails().getCityName();
String originPostalCode = response.body().getRajaongkir().getOriginDetails().getPostalCode();
String destinationCity = response.body().getRajaongkir().getDestinationDetails().getCityName();
String destinationPostalCode = response.body().getRajaongkir().getDestinationDetails().getPostalCode();
//results
List<com.bagicode.cekongkir.model.cost.Result> ListResults = response.body().getRajaongkir().getResults();
//costs
List<com.bagicode.cekongkir.model.cost.Cost> ListCosts = response.body().getRajaongkir().getResults().get(0).getCosts();
//cost
List<com.bagicode.cekongkir.model.cost.Cost_> ListCost = response.body().getRajaongkir().getResults().get(0).getCosts().get(0).getCost();
mListView = (ListView) alertLayout.findViewById(R.id.listItem);
adapter_results = new ResultsAdapter(MainActivity.this, originCity, originPostalCode, destinationCity, destinationPostalCode, ListResults, ListCosts, ListCost);
mListView.setAdapter(adapter_results);
mListView.setClickable(true);
adapter_results.notifyDataSetChanged();
} else {
String message = response.body().getRajaongkir().getStatus().getDescription();
Toast.makeText(MainActivity.this, message, Toast.LENGTH_SHORT).show();
}
} else {
String error = "Error Retrive Data from Server !!!";
Toast.makeText(MainActivity.this, error, Toast.LENGTH_SHORT).show();
}
}
#Override
public void onFailure(Call<ItemCost> call, Throwable t) {
progressDialog.dismiss();
Toast.makeText(MainActivity.this, "Message : Error " + t.getMessage(), Toast.LENGTH_SHORT).show();
}
});
}
I want to fetch the array list of users. I have three POGO classes i.e Root(Parent class), ContactFamilyDetails(Child class), DataModelFamilyDetails(GrandChild class).
The problem that I have faced all the time that when I run the application at that time I only get the first array value, unfortunately, I didn't get the rest of the values. So I am going to share my whole code so please go through it and help me out of it !! Thank You!!
AddUserActivity (Act as MainActivity)
public class AddUserActivity extends AppCompatActivity {
SharedPreferences prefs;
String FirstName;
String ContactNo,Authentication,ID;
FloatingActionButton FAB;
private DataModelFamilyDetails dataModelFamDetails;
ArrayList<DataModelFamilyDetails> dataModelFamilyDetails;
RecyclerViewAdapter adapter;
RecyclerView myrv;
Context context;
#Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_add_user);
// Initialize FloatingAction button
FAB=findViewById(R.id.fab_id);
//SharedPreference Login details
prefs = this.getSharedPreferences("logindata", MODE_PRIVATE);
FirstName = prefs.getString("fname", "");
ContactNo = prefs.getString("contact_no1", "");
Authentication=prefs.getString("Authentication","");
ID=prefs.getString("id","");
//Setting RecyclerView
myrv = findViewById(R.id.recyclerview_id);
LinearLayoutManager mLayoutManager = new LinearLayoutManager(AddUserActivity.this);
myrv.setLayoutManager(mLayoutManager);
dataModelFamilyDetails=new ArrayList<DataModelFamilyDetails>();
//Set Click listener on Floating Action Button
FAB.setOnClickListener(new View.OnClickListener()
{
#Override
public void onClick(View view) {
Intent intent=new Intent(AddUserActivity.this,AddNewUserActivity.class);
startActivity(intent);
}
});
//Call the Retrofit Class data
getResult1();
}
//Fetching Family Details using Retrofit
private void getResult1()
{
RequestBody requestBody=new FormBody.Builder()
.add("id",ID)
.add("Authentication",Authentication)
.build();
//Below, API call by a Retrofit Class to the java Interface
try
{
Retrofit_Class.getDefault().apiInterface().getFamilyDetails(requestBody).enqueue(new Callback<Root<ContactFamilyDetails>>()
{
#Override
public void onResponse(Call<Root<ContactFamilyDetails>> call, retrofit2.Response<Root<ContactFamilyDetails>> response)
{
ContactFamilyDetails contactFamilyDetails=response.body().getRoot();
String Status=contactFamilyDetails.getStatus();
if(Status.equals("true"))
{
dataModelFamilyDetails=contactFamilyDetails.getData();
myrv.setAdapter(new RecyclerViewAdapter(getApplicationContext(),dataModelFamilyDetails));
RecyclerViewAdapter(getApplicationContext(),dataModelFamilyDetails);
}else
{
Toast.makeText(context, "You haven't added any family member yet !!", Toast.LENGTH_LONG).show();
}
}
#Override
public void onFailure(Call<Root<ContactFamilyDetails>> call, Throwable t)
{
Log.d("Error",t.getMessage());
Toast.makeText(context, "Error fetching data", Toast.LENGTH_SHORT).show();
}
});
}catch (Exception e)
{
Log.d("Error",e.getMessage());
Toast.makeText(context, e.toString(), Toast.LENGTH_SHORT).show();
}
}
}
RecyclerViewAdapter Class
public class RecyclerViewAdapter extends RecyclerView.Adapter<RecyclerViewAdapter.MyViewHolder>{
ArrayList<DataModelFamilyDetails> dataModelFamilyDetails=new ArrayList<DataModelFamilyDetails>();
Context mContext;
public RecyclerViewAdapter(Context mContext, ArrayList<DataModelFamilyDetails> dataModelFamilyDetails) {
this.mContext=mContext;
this.dataModelFamilyDetails=dataModelFamilyDetails;
}
//3 Implemented methods of RecyclerView.Adapter
#NonNull
#Override
public RecyclerViewAdapter.MyViewHolder onCreateViewHolder(#NonNull ViewGroup parent, int viewType)
{
View itemView = LayoutInflater.from(parent.getContext()).inflate(R.layout.cardview_user_details, parent, false);
return new MyViewHolder(itemView);
}
#Override
public void onBindViewHolder( RecyclerViewAdapter.MyViewHolder holder, int position)
{
holder.Name.setText(dataModelFamilyDetails.get(position).getName());
holder.Contact.setText(dataModelFamilyDetails.get(position).getContact_no());
}
#Override
public int getItemCount()
{
return dataModelFamilyDetails.size();
}
//Inner Class of RecyclerViewAdapter
public static class MyViewHolder extends RecyclerView.ViewHolder
{
TextView Name,Download,Contact;
ImageView DeleteDustbin,Call;
CardView cardView;
public MyViewHolder(View itemView) {
super(itemView);
//Initialize the variables
Name=itemView.findViewById(R.id.tv1_id);
Download=itemView.findViewById(R.id.tv2_id);
Contact=itemView.findViewById(R.id.tv_contact_id);
cardView=itemView.findViewById(R.id.cardview_id);
DeleteDustbin=itemView.findViewById(R.id.delete_img_id);
Call=itemView.findViewById(R.id.call_img_id);
}
}
}
Root (POGO Class(Parent class))
public class Root<T> {
private T root;
public T getRoot()
{
return root;
}
}
ContactFamilyDetails (POGO Class(Child class))
public class ContactFamilyDetails {
#SerializedName("status")
private String Status;
#SerializedName("message")
private String Message;
#SerializedName("data")
private ArrayList<DataModelFamilyDetails> data;
public String getStatus() {
return Status;
}
public String getMessage() {
return Message;
}
public ArrayList<DataModelFamilyDetails> getData() {
return data;
}
}
DataModelFamilyDetails (POGO Class (GrandChild class))
public class DataModelFamilyDetails {
#SerializedName("id")
private String id;
#SerializedName("parentId")
private String parentId;
#SerializedName("name")
private String name;
#SerializedName("age")
private String age;
#SerializedName("sex")
private String sex;
#SerializedName("relation")
private String relation;
#SerializedName("contact_no")
private String contact_no;
#SerializedName("email")
private String email;
#SerializedName("description")
private String description;
#SerializedName("status")
private String status;
#SerializedName("image")
private String image;
#SerializedName("regDateTime")
private String regDateTime;
public DataModelFamilyDetails(String name, String contact_no) {
this.name = name;
this.contact_no = contact_no;
}
public String getId() {
return id;
}
public String getParentId() {
return parentId;
}
public String getName() {
return name;
}
public String getAge() {
return age;
}
public String getSex() {
return sex;
}
public String getRelation() {
return relation;
}
public String getContact_no() {
return contact_no;
}
public String getEmail() {
return email;
}
public String getDescription() {
return description;
}
public String getStatus() {
return status;
}
public String getImage() {
return image;
}
public String getRegDateTime() {
return regDateTime;
}
}
Retrofit Class
public class Retrofit_Class {
//set an Url here
public static final String API_BASE_URL = "http://www.hawktechnologies.in/society-management/appservices/";
//Create a reference of the class here
private static Retrofit_Class mInstance;
//Object creation of Retrofit.builder
private static Retrofit.Builder builder =
new Retrofit.Builder()
.baseUrl(API_BASE_URL)
.addConverterFactory(GsonConverterFactory.create(Retrofit_Class.getDefault().getGsonParser()));
private ApiInterface apiInterface;
private OkHttpClient okHttpClient;
private Gson gson;
//Constructor
private Retrofit_Class() {
//No External Instances
}
public static <S> S createService(Class<S> serviceClass) {
Retrofit retrofit = builder.client(Retrofit_Class.getDefault().getOkHttpClient()).build();
return retrofit.create(serviceClass);
}
//Retrofit class method
public static Retrofit_Class getDefault() {
if (mInstance == null) {
mInstance = new Retrofit_Class();
}
return mInstance;
}
//Interface class method
public ApiInterface apiInterface() {
if (apiInterface == null) {
apiInterface = createService(ApiInterface.class);
}
return apiInterface;
}
//Method type Gson
public Gson getGsonParser() {
if (gson == null) {
gson = new Gson();
}
return gson;
}
//Use of HTTP
public OkHttpClient getOkHttpClient() {
if (okHttpClient == null) {
HttpLoggingInterceptor loggingInterceptor = new HttpLoggingInterceptor(new HttpLoggingInterceptor.Logger() {
#Override
public void log(String message) {
Timber.tag("OkHttp").d(message);
}
});
if (BuildConfig.DEBUG) {
loggingInterceptor.setLevel(HttpLoggingInterceptor.Level.BODY);
} else {
loggingInterceptor.setLevel(HttpLoggingInterceptor.Level.NONE);
}
okHttpClient = new OkHttpClient.Builder()
.connectTimeout(20, TimeUnit.SECONDS)
.readTimeout(20, TimeUnit.SECONDS)
.addInterceptor(loggingInterceptor)
.build();
}
return okHttpClient;
}
}
Interface
public interface ApiInterface
{
#POST("user-login.php")
Call<Root<Contact>> getLogin(#Body RequestBody requestBody);
#POST("get_familymembers.php")
Call<Root<ContactFamilyDetails>> getFamilyDetails(#Body RequestBody requestBody);
}
Instead of getting 4 results I am getting only one, please click on the link to see the Picture.
Picture Link
I’ve been trying to get recycler view working with retrofit. I seem to be pulling in the JSON fine from within getRecipes() method, and my logs are showing me that the some data is there.
However, when I call my getRecipes() method from onCreate(), something seems to be going wrong. When I check to see if my recipeList array contains my JSON results within onCreate, it is telling me it is empty. Why is it doing this if my logs within my getRecipes() method are showing me that data is there...?
Not sure if it is an issue with my recycler view or what I am doing with retrofit, or something else. Been trying for days to figure out, so any advice would be greatly appreciated.
JSON
https://d17h27t6h515a5.cloudfront.net/topher/2017/May/59121517_baking/baking.json
public class ItemListActivity extends AppCompatActivity {
private boolean mTwoPane;
public static final String LOG_TAG = "myLogs";
public static List<Recipe> recipeList = new ArrayList<>();
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
getRecipes();
setContentView(R.layout.activity_item_list);
getRecipes();
//Logging to check that recipeList contains data
if(recipeList.isEmpty()){
Log.d(LOG_TAG, "Is empty");
}else {
Log.d(LOG_TAG, "Is not empty");
}
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
toolbar.setTitle(getTitle());
RecyclerView recyclerView = (RecyclerView) findViewById(R.id.item_list);
RecyclerView.LayoutManager layoutManager = new LinearLayoutManager(this);
recyclerView.setLayoutManager(layoutManager);
SimpleItemRecyclerViewAdapter simpleItemRecyclerViewAdapter = new SimpleItemRecyclerViewAdapter(recipeList);
recyclerView.setAdapter(simpleItemRecyclerViewAdapter);
if (findViewById(R.id.item_detail_container) != null) {
mTwoPane = true;
}
}
public void getRecipes(){
String ROOT_URL = "https://d17h27t6h515a5.cloudfront.net/topher/2017/May/59121517_baking/";
Retrofit RETROFIT = new Retrofit.Builder()
.baseUrl(ROOT_URL)
.addConverterFactory(GsonConverterFactory.create())
.build();
RecipeService service = RETROFIT.create(RecipeService.class);
Call<List<Recipe>> call = service.getMyJson();
call.enqueue(new Callback<List<Recipe>>() {
#Override
public void onResponse(Call<List<Recipe>> call, Response<List<Recipe>> response) {
Log.d(LOG_TAG, "Got here");
if (!response.isSuccessful()) {
Log.d(LOG_TAG, "No Success");
}
Log.d(LOG_TAG, "Got here");
recipeList = response.body();
//Logging to check data is there
Log.v(LOG_TAG, "LOGS" + recipeList.size());
for (int i = 0; i < recipeList.size(); i++) {
String newString = recipeList.get(i).getName();
Ingredients[] ingredients = recipeList.get(i).getIngredients();
for(int j = 0; j < ingredients.length; j++){
Log.d(LOG_TAG, ingredients[j].getIngredient());
}
Steps[] steps = recipeList.get(i).getSteps();
for(int k = 0; k < steps.length; k++){
Log.d(LOG_TAG, steps[k].getDescription());
}
Log.d(LOG_TAG, newString);
}
}
#Override
public void onFailure(Call<List<Recipe>> call, Throwable t) {
Log.e("getRecipes throwable: ", t.getMessage());
t.printStackTrace();
}
});
}
public class SimpleItemRecyclerViewAdapter
extends RecyclerView.Adapter<SimpleItemRecyclerViewAdapter.ViewHolder> {
private final List<Recipe> mValues;
public SimpleItemRecyclerViewAdapter(List<Recipe> items) {
mValues = items;
}
#Override
public ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View view = LayoutInflater.from(parent.getContext())
.inflate(R.layout.item_list_content, parent, false);
return new ViewHolder(view);
}
#Override
public void onBindViewHolder(final ViewHolder holder, int position) {
holder.mItem = mValues.get(position);
holder.mContentView.setText(mValues.get(position).getName());
holder.mView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (mTwoPane) {
Bundle arguments = new Bundle();
arguments.putString(ItemDetailFragment.ARG_ITEM_ID, holder.mItem.getId());
ItemDetailFragment fragment = new ItemDetailFragment();
fragment.setArguments(arguments);
getSupportFragmentManager().beginTransaction()
.replace(R.id.item_detail_container, fragment)
.commit();
} else {
Context context = v.getContext();
Intent intent = new Intent(context, ItemDetailActivity.class);
intent.putExtra(ItemDetailFragment.ARG_ITEM_ID, holder.mItem.getId());
context.startActivity(intent);
}
}
});
}
#Override
public int getItemCount() {
return mValues.size();
}
public class ViewHolder extends RecyclerView.ViewHolder {
public View mView;
public TextView mContentView;
public Recipe mItem;
public ViewHolder(View view) {
super(view);
mView = view;
mContentView = (TextView) view.findViewById(R.id.content);
}
#Override
public String toString() {
return super.toString() + " '" + mContentView.getText() + "'";
}
}
}
RecipeService
public interface RecipeService {
#GET("baking.json")
Call<List<Recipe>> getMyJson();}
Models
Recipe
public class Recipe{
private Ingredients[] ingredients;
private String id;
private String servings;
private String name;
private String image;
private Steps[] steps;
public Ingredients[] getIngredients ()
{
return ingredients;
}
public void setIngredients (Ingredients[] ingredients)
{
this.ingredients = ingredients;
}
public String getId ()
{
return id;
}
public void setId (String id)
{
this.id = id;
}
public String getServings ()
{
return servings;
}
public void setServings (String servings)
{
this.servings = servings;
}
public String getName ()
{
return name;
}
public void setName (String name)
{
this.name = name;
}
public String getImage ()
{
return image;
}
public void setImage (String image)
{
this.image = image;
}
public Steps[] getSteps ()
{
return steps;
}
public void setSteps (Steps[] steps)
{
this.steps = steps;
}
#Override
public String toString()
{
return "[ingredients = "+ingredients+", id = "+id+", servings = "+servings+", name = "+name+", image = "+image+", steps = "+steps+"]";
}}
Ingredients
public class Ingredients{
private String measure;
private String ingredient;
private String quantity;
public String getMeasure ()
{
return measure;
}
public void setMeasure (String measure)
{
this.measure = measure;
}
public String getIngredient ()
{
return ingredient;
}
public void setIngredient (String ingredient)
{
this.ingredient = ingredient;
}
public String getQuantity ()
{
return quantity;
}
public void setQuantity (String quantity)
{
this.quantity = quantity;
}
#Override
public String toString()
{
return "[measure = "+measure+", ingredient = "+ingredient+", quantity = "+quantity+"]";
}}
Steps
public class Steps{
private String id;
private String shortDescription;
private String description;
private String videoURL;
private String thumbnailURL;
public String getId ()
{
return id;
}
public void setId (String id)
{
this.id = id;
}
public String getShortDescription ()
{
return shortDescription;
}
public void setShortDescription (String shortDescription)
{
this.shortDescription = shortDescription;
}
public String getDescription ()
{
return description;
}
public void setDescription (String description)
{
this.description = description;
}
public String getVideoURL ()
{
return videoURL;
}
public void setVideoURL (String videoURL)
{
this.videoURL = videoURL;
}
public String getThumbnailURL ()
{
return thumbnailURL;
}
public void setThumbnailURL (String thumbnailURL)
{
this.thumbnailURL = thumbnailURL;
}
#Override
public String toString()
{
return "[id = "+id+", shortDescription = "+shortDescription+", description = "+description+", videoURL = "+videoURL+", thumbnailURL = "+thumbnailURL+"]";
}}
Logs
https://gist.github.com/2triggers/12b6eeb32ed8909ab50bbadd4742d7f7
this will be empty always because this line will execute before getting the response from a server.
if(recipeList.isEmpty()){
Log.d(LOG_TAG, "Is empty");
}else {
Log.d(LOG_TAG, "Is not empty");
}
Better call this after this line recipeList = response.body();
SimpleItemRecyclerViewAdapter simpleItemRecyclerViewAdapter = new SimpleItemRecyclerViewAdapter(recipeList);
recyclerView.setAdapter(simpleItemRecyclerViewAdapter);
if (findViewById(R.id.item_detail_container) != null) {
mTwoPane = true;
}
it is because you are sending the recipelist into the adapter before even it is populated , after you are sending the recipelist into the adapter which is empty you are populating your recipelist from getRecipes method, you might be wondering you have declared the getRecipes method before even you are assigning the recipelist to adapter so how come it is empty, yea but the fact is your getRecipes work on background thread so even before your recipelist gets populated your adapter assignment takes place on the main thread so you are basically assigning the empty list, one thing you can do is notify when the adapter when the data changes or when the the recipelist is filled with data that is from within the getRecipe method.
when you assign the recipelist = response.body right after this you can notify the adapter
or move this two lines
SimpleItemRecyclerViewAdapter simpleItemRecyclerViewAdapter = new SimpleItemRecyclerViewAdapter(recipeList);
recyclerView.setAdapter(simpleItemRecyclerViewAdapter);
right after the
recipelist = response.body;
in getRecipes method
Try create the Constructor with all atributes from your Recipe.class
Like:
public Ingredients(String measure, String ingredients, String quantity ){
this.measure = measure;
this.ingredients = ingredients;
this.quantity = quantity
}
Do same in all class where make up your object of list.
I am using openweathermap to parse weather information, it works fine without the city, but when I try to fetch city, it force closes. How do I fix this? been searching for hours but no luck.
#Override
protected void onPostExecute(Weather weather) {
super.onPostExecute(weather);
if (weather.iconData != null && weather.iconData.length > 0) {
Bitmap img = BitmapFactory.decodeByteArray(weather.iconData, 0, weather.iconData.length);
imgView.setImageBitmap(img);
}
cityText.setText(weather.location.getCity() + "," + weather.location.getCountry());
condDescr
.setText(weather.currentCondition.getCondition() + "(" + weather.currentCondition.getDescr() + ")");
temp.setText("" + Math.round((weather.temperature.getTemp() - 273.15)) + "�C");
hum.setText("" + weather.currentCondition.getHumidity() + "%");
press.setText("" + weather.currentCondition.getPressure() + " hPa");
windSpeed.setText("" + weather.wind.getSpeed() + " mps");
windDeg.setText("" + weather.wind.getDeg() + "�");
}
}
public class Location implements Serializable {
private float longitude;
private float latitude;
private long sunset;
private long sunrise;
private String country;
private String city;
...
public String getCountry() {
return country;
}
public String getCity() {
return city;
}
here is my log-
FATAL EXCEPTION: main
Process: com.survivingwithandroid.weatherapp, PID: 2057
java.lang.NullPointerException: Attempt to invoke virtual method 'java.lang.String com.myweather.weatherapp.model.Location.getCity()' on a null object reference
at com.survivingwithandroid.weatherapp.MainActivity$JSONWeatherTask.onPostExecute(MainActivity.java:114)
UPDATE
JSONWeatherParser.java
package com.survivingwithandroid.weatherapp;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import com.survivingwithandroid.weatherapp.model.Location;
import com.survivingwithandroid.weatherapp.model.Weather;
public class JSONWeatherParser {
public static Weather getWeather(String data) throws JSONException {
Weather weather = new Weather();
// We create out JSONObject from the data
JSONObject jObj = new JSONObject(data);
// We start extracting the info
Location loc = new Location();
JSONObject coordObj = getObject("coord", jObj);
loc.setLatitude(getFloat("lat", coordObj));
loc.setLongitude(getFloat("lon", coordObj));
JSONObject sysObj = getObject("sys", jObj);
loc.setCountry(getString("country", sysObj));
loc.setSunrise(getInt("sunrise", sysObj));
loc.setSunset(getInt("sunset", sysObj));
loc.setCity(getString("name", jObj));
weather.location = loc;
// We get weather info (This is an array)
JSONArray jArr = jObj.getJSONArray("weather");
// We use only the first value
JSONObject JSONWeather = jArr.getJSONObject(0);
weather.currentCondition.setWeatherId(getInt("id", JSONWeather));
weather.currentCondition.setDescr(getString("description", JSONWeather));
weather.currentCondition.setCondition(getString("main", JSONWeather));
weather.currentCondition.setIcon(getString("icon", JSONWeather));
JSONObject mainObj = getObject("main", jObj);
weather.currentCondition.setHumidity(getInt("humidity", mainObj));
weather.currentCondition.setPressure(getInt("pressure", mainObj));
weather.temperature.setMaxTemp(getFloat("temp_max", mainObj));
weather.temperature.setMinTemp(getFloat("temp_min", mainObj));
weather.temperature.setTemp(getFloat("temp", mainObj));
// Wind
JSONObject wObj = getObject("wind", jObj);
weather.wind.setSpeed(getFloat("speed", wObj));
weather.wind.setDeg(getFloat("deg", wObj));
// Clouds
JSONObject cObj = getObject("clouds", jObj);
weather.clouds.setPerc(getInt("all", cObj));
// We download the icon to show
return weather;
}
private static JSONObject getObject(String tagName, JSONObject jObj) throws JSONException {
JSONObject subObj = jObj.getJSONObject(tagName);
return subObj;
}
private static String getString(String tagName, JSONObject jObj) throws JSONException {
return jObj.getString(tagName);
}
private static float getFloat(String tagName, JSONObject jObj) throws JSONException {
return (float) jObj.getDouble(tagName);
}
private static int getInt(String tagName, JSONObject jObj) throws JSONException {
return jObj.getInt(tagName);
}
}
MainActivity.java
package com.survivingwithandroid.weatherapp;
import org.json.JSONException;
import com.survivingwithandroid.weatherapp.model.Weather;
import android.app.Activity;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.AsyncTask;
import android.os.Bundle;
import android.view.Menu;
import android.widget.ImageView;
import android.widget.TextView;
public class MainActivity extends Activity {
private TextView cityText;
private TextView condDescr;
private TextView temp;
private TextView press;
private TextView windSpeed;
private TextView windDeg;
private TextView hum;
private ImageView imgView;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
String city = "London,UK";
cityText = (TextView) findViewById(R.id.cityText);
condDescr = (TextView) findViewById(R.id.condDescr);
temp = (TextView) findViewById(R.id.temp);
hum = (TextView) findViewById(R.id.hum);
press = (TextView) findViewById(R.id.press);
windSpeed = (TextView) findViewById(R.id.windSpeed);
windDeg = (TextView) findViewById(R.id.windDeg);
imgView = (ImageView) findViewById(R.id.condIcon);
JSONWeatherTask task = new JSONWeatherTask();
task.execute(new String[] { city });
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
private class JSONWeatherTask extends AsyncTask<String, Void, Weather> {
#Override
protected Weather doInBackground(String... params) {
Weather weather = new Weather();
String data = ((new WeatherHttpClient()).getWeatherData(params[0]));
try {
weather = JSONWeatherParser.getWeather(data);
// Let's retrieve the icon
weather.iconData = ((new WeatherHttpClient()).getImage(weather.currentCondition.getIcon()));
} catch (JSONException e) {
e.printStackTrace();
}
return weather;
}
#Override
protected void onPostExecute(Weather weather) {
super.onPostExecute(weather);
if (weather.iconData != null && weather.iconData.length > 0) {
Bitmap img = BitmapFactory.decodeByteArray(weather.iconData, 0, weather.iconData.length);
imgView.setImageBitmap(img);
}
cityText.setText(weather.location.getCity() + "," + weather.location.getCountry());
condDescr
.setText(weather.currentCondition.getCondition() + "(" + weather.currentCondition.getDescr() + ")");
temp.setText("" + Math.round((weather.temperature.getTemp() - 273.15)) + "�C");
hum.setText("" + weather.currentCondition.getHumidity() + "%");
press.setText("" + weather.currentCondition.getPressure() + " hPa");
windSpeed.setText("" + weather.wind.getSpeed() + " mps");
windDeg.setText("" + weather.wind.getDeg() + "�");
}
}
}
WeatherHttpClient.java
package com.survivingwithandroid.weatherapp;
import java.io.BufferedReader;
import java.io.ByteArrayOutputStream;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
public class WeatherHttpClient {
private static String BASE_URL = "http://api.openweathermap.org/data/2.5/weather?q=";
private static String IMG_URL = "http://openweathermap.org/img/w/";
public String getWeatherData(String location) {
HttpURLConnection con = null;
InputStream is = null;
try {
con = (HttpURLConnection) (new URL(BASE_URL + location)).openConnection();
con.setRequestMethod("GET");
con.setDoInput(true);
con.setDoOutput(true);
con.connect();
// Let's read the response
StringBuffer buffer = new StringBuffer();
is = con.getInputStream();
BufferedReader br = new BufferedReader(new InputStreamReader(is));
String line = null;
while ((line = br.readLine()) != null)
buffer.append(line + "\r\n");
is.close();
con.disconnect();
return buffer.toString();
} catch (Throwable t) {
t.printStackTrace();
} finally {
try {
is.close();
} catch (Throwable t) {
}
try {
con.disconnect();
} catch (Throwable t) {
}
}
return null;
}
public byte[] getImage(String code) {
HttpURLConnection con = null;
InputStream is = null;
try {
con = (HttpURLConnection) (new URL(IMG_URL + code)).openConnection();
con.setRequestMethod("GET");
con.setDoInput(true);
con.setDoOutput(true);
con.connect();
// Let's read the response
is = con.getInputStream();
byte[] buffer = new byte[1024];
ByteArrayOutputStream baos = new ByteArrayOutputStream();
while (is.read(buffer) != -1)
baos.write(buffer);
return baos.toByteArray();
} catch (Throwable t) {
t.printStackTrace();
} finally {
try {
is.close();
} catch (Throwable t) {
}
try {
con.disconnect();
} catch (Throwable t) {
}
}
return null;
}
}
Location.java
package com.survivingwithandroid.weatherapp.model;
import java.io.Serializable;
public class Location implements Serializable {
private float longitude;
private float latitude;
private long sunset;
private long sunrise;
private String country;
private String city;
public float getLongitude() {
return longitude;
}
public void setLongitude(float longitude) {
this.longitude = longitude;
}
public float getLatitude() {
return latitude;
}
public void setLatitude(float latitude) {
this.latitude = latitude;
}
public long getSunset() {
return sunset;
}
public void setSunset(long sunset) {
this.sunset = sunset;
}
public long getSunrise() {
return sunrise;
}
public void setSunrise(long sunrise) {
this.sunrise = sunrise;
}
public String getCountry() {
return country;
}
public void setCountry(String country) {
this.country = country;
}
public String getCity() {
return city;
}
public void setCity(String city) {
this.city = city;
}
}
Weather.java
package com.survivingwithandroid.weatherapp.model;
public class Weather {
public Location location;
public CurrentCondition currentCondition = new CurrentCondition();
public Temperature temperature = new Temperature();
public Wind wind = new Wind();
public Rain rain = new Rain();
public Snow snow = new Snow();
public Clouds clouds = new Clouds();
public byte[] iconData;
public class CurrentCondition {
private int weatherId;
private String condition;
private String descr;
private String icon;
private float pressure;
private float humidity;
public int getWeatherId() {
return weatherId;
}
public void setWeatherId(int weatherId) {
this.weatherId = weatherId;
}
public String getCondition() {
return condition;
}
public void setCondition(String condition) {
this.condition = condition;
}
public String getDescr() {
return descr;
}
public void setDescr(String descr) {
this.descr = descr;
}
public String getIcon() {
return icon;
}
public void setIcon(String icon) {
this.icon = icon;
}
public float getPressure() {
return pressure;
}
public void setPressure(float pressure) {
this.pressure = pressure;
}
public float getHumidity() {
return humidity;
}
public void setHumidity(float humidity) {
this.humidity = humidity;
}
}
public class Temperature {
private float temp;
private float minTemp;
private float maxTemp;
public float getTemp() {
return temp;
}
public void setTemp(float temp) {
this.temp = temp;
}
public float getMinTemp() {
return minTemp;
}
public void setMinTemp(float minTemp) {
this.minTemp = minTemp;
}
public float getMaxTemp() {
return maxTemp;
}
public void setMaxTemp(float maxTemp) {
this.maxTemp = maxTemp;
}
}
public class Wind {
private float speed;
private float deg;
public float getSpeed() {
return speed;
}
public void setSpeed(float speed) {
this.speed = speed;
}
public float getDeg() {
return deg;
}
public void setDeg(float deg) {
this.deg = deg;
}
}
public class Rain {
private String time;
private float ammount;
public String getTime() {
return time;
}
public void setTime(String time) {
this.time = time;
}
public float getAmmount() {
return ammount;
}
public void setAmmount(float ammount) {
this.ammount = ammount;
}
}
public class Snow {
private String time;
private float ammount;
public String getTime() {
return time;
}
public void setTime(String time) {
this.time = time;
}
public float getAmmount() {
return ammount;
}
public void setAmmount(float ammount) {
this.ammount = ammount;
}
}
public class Clouds {
private int perc;
public int getPerc() {
return perc;
}
public void setPerc(int perc) {
this.perc = perc;
}
}
}
Please find attached code for fetching location using LocationManager.
private GoogleApiClient mGoogleApiClient;
private Context mContext;
#SuppressWarnings({"MissingPermission"})
public void getLocation(Context context) {
mContext = context;
LocationManager locationManager = (LocationManager) context.getSystemService(Context.LOCATION_SERVICE);
if (locationManager != null) {
// getting GPS status
boolean isGPSEnabled = locationManager.isProviderEnabled(LocationManager.GPS_PROVIDER);
// getting network status
boolean isNetworkEnabled = locationManager.isProviderEnabled(LocationManager.NETWORK_PROVIDER);
if (!isGPSEnabled && !isNetworkEnabled) {
//Show message alert for gps enable
} else {
mGoogleApiClient = new GoogleApiClient.Builder(context)
.addConnectionCallbacks(this)
.addOnConnectionFailedListener(this)
.addApi(LocationServices.API)
.build();
mGoogleApiClient.connect();
}
}
}
After that, you will get callback on onConnected method and you get location from there
#Override
public void onConnected(#Nullable Bundle bundle) {
Location location = LocationServices.FusedLocationApi.getLastLocation(
mGoogleApiClient);
if (location != null) {
double lat= location.getLatitude();
double lang= location.getLongitude());
} else {
//No location found message
}
mGoogleApiClient.disconnect();
}
So am working with retrofit and rxjava for my application.so am using the #GET annociation to pull my blog details from the server that include blog_title, blog_content, blog_thumbnail etc and all this parameter are within an array called blog_post.
I have my APIClient:
public class ApiClient {
private static final String STAGING_BASE_URL = "https://watchnollywood.ml/api/";
private static ApiClient instance;
private ApiService apiService;
private ApiClient(){
HttpLoggingInterceptor logging = new HttpLoggingInterceptor();
// set your desired log level
// TODO: 21/03/2017 when going live change the log level to NONE, to enhance performance
logging.setLevel(HttpLoggingInterceptor.Level.BODY);
OkHttpClient.Builder httpClient = new OkHttpClient.Builder();
// add logging as last interceptor
httpClient.addInterceptor(logging); // <-- this is the important line for logging requests!
final Gson gson = new GsonBuilder().setFieldNamingPolicy(FieldNamingPolicy.LOWER_CASE_WITH_UNDERSCORES).create();
//final Retrofit retrofit = new Retrofit.Builder().baseUrl(STAGING_BASE_URL).addCallAdapterFactory(RxJavaCallAdapterFactory.create()).addConverterFactory(GsonConverterFactory.create(gson)).client(httpClient.build()).build();
Retrofit retrofit = new Retrofit.Builder()
.baseUrl(STAGING_BASE_URL)
.client(httpClient.build())
.addConverterFactory(GsonConverterFactory.create())
.addCallAdapterFactory(RxJava2CallAdapterFactory.create())
.build();
apiService = retrofit.create(ApiService.class);
}
public static ApiClient getInstance(){
if(instance == null){
instance = new ApiClient();
}
return instance;
}
//API CALL FOR LOGIN
public Observable<UserItem> login(String email, String password){
return apiService.signIn(email,password);
}
//API CALL FOR SIGNUP
public Observable<StatusItem> signup(String email, String password, String full_name, String phone){
return apiService.signUp(email, password,phone,full_name);
}
//API CALL FOR BLOG DETAILS
public Observable<BlogResponse> blog_post(){
return apiService.blog_post();
}
}
ApiService:
public interface ApiService {
#FormUrlEncoded
#POST("signin")
Observable<UserItem> signIn(#Field("email") String email, #Field("password") String password);
#FormUrlEncoded
#POST("signup")
Observable<StatusItem> signUp(#Field("full_name")String full_name, #Field("phone") String phone, #Field("email") String email, #Field("password") String password);
#GET("blog")
Observable<BlogResponse> blog_post();
}
pojo classes:
public class BlogItem {
private int thumbNail;
private String title;
private String summary;
public int getThumbNail() {
return thumbNail;
}
public void setThumbNail(#DrawableRes int thumbNail) {
this.thumbNail = thumbNail;
}
public String getTitle() {
return title;
}
public void setTitle(String title) {
this.title = title;
}
public String getSummary() {
return summary;
}
public void setSummary(String summary) {
this.summary = summary;
}
}
public class BlogResponse {
private BlogItem[] blogItems;
public BlogItem[] getBlogItems() {
return blogItems;
}
public void setBlogItems(BlogItem[] blogItems) {
this.blogItems = blogItems;
}
}
I have a recyclerview that will hold all the information that will be coming from the server. But the problem is that when I run it I get a log response in my RUN terminal but nothing is showing on the app screen.
this is my FragmentClass that holds the information from the server:
BlogFragment:
public class BlogFragment extends Fragment {
private static final String ARG_PARAM1 = "param1";
private String mParam1;
private RecyclerView recyclerView;
private BlogAdapter adapter;
private List<BlogItem> blogItems;
private View view;
public BlogFragment() {
// Required empty public constructor
}
public static BlogFragment newInstance(String param1) {
BlogFragment fragment = new BlogFragment();
Bundle args = new Bundle();
args.putString(ARG_PARAM1, param1);
fragment.setArguments(args);
return fragment;
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
if (getArguments() != null) {
mParam1 = getArguments().getString(ARG_PARAM1);
}
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
view = inflater.inflate(R.layout.fragment_blog, container, false);
return view;
}
#Override
public void onActivityCreated(#Nullable Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
recyclerView = (RecyclerView) view.findViewById(R.id.blog_posts_list);
setUpViews();
}
private void setUpViews() {
blogItems = new ArrayList<>();
adapter = new BlogAdapter(blogItems);
recyclerView.setAdapter(adapter);
recyclerView.setLayoutManager(new StaggeredGridLayoutManager(2, StaggeredGridLayoutManager.VERTICAL));
BlogPost();
// populateLists();
}
private void BlogPost() {
ApiClient.getInstance().blog_post().observeOn(AndroidSchedulers.mainThread())
.subscribeOn(Schedulers.newThread()).subscribe(new DisposableObserver<BlogResponse>() {
#Override
public void onNext(BlogResponse value) {
BlogItem blogItem = new BlogItem();
blogItem.setTitle(blogItem.getTitle().toString());
blogItem.setSummary(blogItem.getSummary().toString());
}
#Override
public void onError(Throwable e) {
}
#Override
public void onComplete() {
BlogItem blogItem = new BlogItem();
blogItem.setTitle("blog_title");
blogItem.setSummary("blog_content");
}
});
adapter.notifyItemRangeChanged(0, adapter.getItemCount());
}
/*
private void populateLists() {
int dummyPostArraySize = 10;
for (int i = 0; i < dummyPostArraySize; i++) {
BlogItem blogItem = new BlogItem();
blogItem.setTitle("Post title " + i+1);
blogItem.setThumbNail(isEven(i) ? R.drawable.profile_image : 0);
blogItem.setSummary(getString(isEven(i) ? R.string.summary2 : R.string.summary1));
blogItems.add(blogItem);
}
adapter.notifyItemRangeChanged(0, adapter.getItemCount());
}*/
private boolean isEven(int position) {
return (position & 1) == 0;
}
}
Adapter class
public class BlogAdapter extends RecyclerView.Adapter<BlogViewHolder> {
private List<BlogItem> blogItems;
public BlogAdapter(List<BlogItem> blogItems) {
this.blogItems = blogItems;
}
#Override
public BlogViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.blog_post_item,
parent, false);
return new BlogViewHolder(view);
}
#Override
public void onBindViewHolder(BlogViewHolder holder, int position) {
BlogItem blogItem = blogItems.get(position);
holder.bindModel(blogItem);
}
#Override
public int getItemCount() {
return blogItems == null ? (0) : blogItems.size();
}
}
View Holder class
public class BlogViewHolder extends RecyclerView.ViewHolder {
private ImageView cover;
private TextView title;
private TextView summary;
public BlogViewHolder(View itemView) {
super(itemView);
cover = (ImageView) itemView.findViewById(R.id.post_thumbnail);
title = (TextView) itemView.findViewById(R.id.post_title);
summary = (TextView) itemView.findViewById(R.id.post_summary);
}
public void bindModel(BlogItem blogItem) {
if (blogItem.getThumbNail() == 0) {
cover.setVisibility(View.GONE);
} else {
cover.setImageResource(blogItem.getThumbNail());
}
title.setText(Html.fromHtml(blogItem.getTitle()));
summary.setText(blogItem.getSummary());
}
}
What am I not doing right. Someone Please Help!!!
In the private void BlogPost() { method, you create BlogItems but then don't do anything with it. You probably forgot to add them to the blogItems list.
In addition, the call to adapter.notifyItemRangeChanged in that method happens way before the sequence receives data but you don't call that after each blogItem or when all blog items have arrived - the observer is on a complete different execution path than the outer BlogPost() method.
Edit spelled out:
#Override
public void onNext(BlogResponse value) {
for (BlogItem responseItem : value.getBlogItems()) {
BlogItem blogItem = new BlogItem();
blogItem.setTitle(responseItem.getTitle().toString());
blogItem.setSummary(responseItem.getSummary().toString());
blogItems.add(blogItem);
}
adapter.notifyItemRangeChanged(0, adapter.getItemCount());
}
#Override
public void onError(Throwable e) {
}
#Override
public void onComplete() {
BlogItem blogItem = new BlogItem();
blogItem.setTitle("blog_title");
blogItem.setSummary("blog_content");
blogItems.add(blogItem);
adapter.notifyItemRangeChanged(0, adapter.getItemCount());
}