Interface:
public interface BabService {
#GET("bab.php")
Call<Respon> tampil(#Query("imam") String imam);
}
Respon:
public class Respon {
private String value;
private List<BabResult> resultBab;
public String getValue() {
return value;
}
public List<BabResult> getResultBab() { return resultBab; }
}
Result:
public class BabResult {
private String id_bab;
private String id_kitab;
private String bab;
public String getId_bab() { return id_bab; }
public String getId_kitab() {
return id_kitab;
}
public String getBab() {
return bab;
}
}
Adapter:
public class BabAdapter extends RecyclerView.Adapter<BabAdapter.ViewHolder>
{
private Context context;
private List<BabResult> results;
private String idBab, judulBab;
private int no;
public BabAdapter(Context context, List<BabResult> results) {
this.context = context;
this.results = results;
}
#Override
public ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View v = LayoutInflater.from(parent.getContext()).inflate(R.layout.item_bab, parent, false);
ViewHolder holder = new ViewHolder(v);
return holder;
}
#Override
public void onBindViewHolder(ViewHolder holder, int position) {
if(position % 2 != 0){
holder.vBab.setBackgroundResource(R.color.ijo);
}else{
holder.vBab.setBackgroundResource(R.color.oren);
}
no = position + 1;
BabResult result = results.get(position);
idBab = result.getId_bab();
judulBab = result.getBab();
holder.tvNo.setText(no);
holder.tvBab.setText(judulBab);
}
#Override
public int getItemCount() {
if(results == null){
return 4;
}
return results.size();
}
public class ViewHolder extends RecyclerView.ViewHolder {
private View vBab;
private TextView tvBab, tvNo;
public ViewHolder(View itemView) {
super(itemView);
vBab = (View) itemView.findViewById(R.id.v_bab);
tvNo = (TextView) itemView.findViewById(R.id.tv_no);
tvBab = (TextView) itemView.findViewById(R.id.tv_bab);
itemView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Intent i = new Intent(context, HadisList.class);
i.putExtra("id", idBab);
i.putExtra("bab", judulBab);
i.putExtra("no", no);
context.startActivity(i);
}
});
}
}
}
Activity:
public class MenuBab extends AppCompatActivity {
public static final String URL = "http://mi3bpolinema.000webhostapp.com/";
private List<BabResult> results = new ArrayList<>();
private BabAdapter babAdapter;
private ProgressBar pbLoading;
private RecyclerView rvBab;
private TextView tvImam;
private String imam, namaImam;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_menu_bab);
if(getSupportActionBar() != null){
getSupportActionBar().hide();
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
}
Intent intent = getIntent();
if(intent != null){
if(intent.getStringExtra("imam") != null){
imam = intent.getStringExtra("imam");
namaImam = intent.getStringExtra("nama");
}
}
pbLoading = (ProgressBar) findViewById(R.id.pb_loading);
rvBab = (RecyclerView) findViewById(R.id.rv_bab);
tvImam = (TextView) findViewById(R.id.tv_imam);
tvImam.setText(namaImam);
babAdapter = new BabAdapter(this, results);
RecyclerView.LayoutManager mLayoutManager = new LinearLayoutManager(getApplicationContext());
rvBab.setLayoutManager(mLayoutManager);
rvBab.setItemAnimator(new DefaultItemAnimator());
rvBab.setAdapter(babAdapter);
loadDataBab();
}
#Override
protected void onResume() {
super.onResume();
loadDataBab();
}
private void loadDataBab() {
Retrofit retrofit = new Retrofit
.Builder()
.baseUrl(URL)
.addConverterFactory(GsonConverterFactory.create())
.build();
BabService api = retrofit.create(BabService.class);
Call<Respon> call = api.tampil(imam);
call.enqueue(new Callback<Respon>() {
#Override
public void onResponse(Call<Respon> call, Response<Respon> response) {
String value = response.body().getValue();
pbLoading.setVisibility(View.GONE);
if (value.equals("1")) {
results = response.body().getResultBab();
babAdapter = new BabAdapter(MenuBab.this, results);
rvBab.setAdapter(babAdapter);
}
}
#Override
public void onFailure(Call<Respon> call, Throwable t) {
}
});
}
}
On retrofit get result null, but when I run in website get result like this:
{"value":1,"result":[{"id_bab":"4","id_kitab":"1","bab":"Wudhu"},
{"id_bab":"8","id_kitab":"1","bab":"Shalat"},
{"id_bab":"15","id_kitab":"1","bab":"Puasa"}]}
using this link.
You need to use Model class in this way
now you can get API Result
Response Model Class
import com.google.gson.annotations.SerializedName;
import java.io.Serializable;
import java.util.ArrayList;
public class Response implements Serializable{
#SerializedName("value")
private String value;
#SerializedName("result")
private ArrayList<BabResult> resultBab;
public String getValue() {
return value;
}
public ArrayList<BabResult> getResultBab() {
return resultBab;
}
public void setValue(String value) {
this.value = value;
}
public void setResultBab(ArrayList<BabResult> resultBab) {
this.resultBab = resultBab;
}
public class BabResult {
#SerializedName("id_bab")
private String id_bab;
#SerializedName("id_kitab")
private String id_kitab;
#SerializedName("bab")
private String bab;
public String getId_bab() {
return id_bab;
}
public void setId_bab(String id_bab) {
this.id_bab = id_bab;
}
public String getId_kitab() {
return id_kitab;
}
public void setId_kitab(String id_kitab) {
this.id_kitab = id_kitab;
}
public String getBab() {
return bab;
}
public void setBab(String bab) {
this.bab = bab;
}
}
}
Respon class
public class Respon
{
private ArrayList<Result> result;
private String value;
public ArrayList<Result> getResult ()
{
return result;
}
public void setResult ( ArrayList<Result> result)
{
this.result = result;
}
public String getValue ()
{
return value;
}
public void setValue (String value)
{
this.value = value;
}
#Override
public String toString()
{
return "ClassPojo [result = "+result+", value = "+value+"]";
}
public class Result
{
private String id_kitab;
private String bab;
private String id_bab;
public String getId_kitab ()
{
return id_kitab;
}
public void setId_kitab (String id_kitab)
{
this.id_kitab = id_kitab;
}
public String getBab ()
{
return bab;
}
public void setBab (String bab)
{
this.bab = bab;
}
public String getId_bab ()
{
return id_bab;
}
public void setId_bab (String id_bab)
{
this.id_bab = id_bab;
}
#Override
public String toString()
{
return "ClassPojo [id_kitab = "+id_kitab+", bab = "+bab+", id_bab =
"+id_bab+"]";
}
}
}
Check this way data null or not and add arraylist
private void loadDataBab() {
Retrofit retrofit = new Retrofit
.Builder()
.baseUrl(URL)
.addConverterFactory(GsonConverterFactory.create())
.build();
BabService api = retrofit.create(BabService.class);
Call<Respon> call = api.tampil(imam);
call.enqueue(new Callback<Respon>() {
#Override
public void onResponse(Call<Respon> call, Response<Respon> response) {
if (response.isSuccessful())
if (response.body() != null)
pbLoading.setVisibility(View.GONE);
if (response.body().getValue().equalsIgnoreCase("1")) {
results.addAll(response.body().getResult());
babAdapter = new BabAdapter(MenuBab.this, results);
rvBab.setAdapter(babAdapter);
}
}
#Override
public void onFailure(Call<Respon> call, Throwable t) {
}
});
}
Pass the array in your Respon class like this ..
public class Respon {
private String value;
private BabResult [] result;
public String getValue() {
return value;
}
public BabResult [] getResultBab() { return result; }
}
and in your loadDataBab method ..
private List<BabResult> results = new ArrayList<>();
private void loadDataBab() {
Retrofit retrofit = new Retrofit
.Builder()
.baseUrl(URL)
.addConverterFactory(GsonConverterFactory.create())
.build();
RequestInterface api = retrofit.create(RequestInterface.class);
Call<Respon> call = api.tampil("1");
call.enqueue(new Callback<Respon>() {
#Override
public void onResponse(Call<Respon> call, Response<Respon> response) {
String value = response.body().getValue();
if (value.equals("1")) {
results = new ArrayList<>(Arrays.asList(response.body().getResultBab()));
}
}
#Override
public void onFailure(Call<Respon> call, Throwable t) {
}
});
}
I change Respon to :
public class Respon {
private String value;
private List<BabResult> result;
public String getValue() { return value; }
public List<BabResult> getResult() { return result; }
}
and it works. Thx :))
Related
I have tough problem with my project. Its hard to explain. I have two different model but, I should compare these two model. Should I make a new model for this two models?
Here is Cart.java. There is Voyage.java as a Model. This class differentiate if type_voyage not equals each other. I have another model named Bus.java. I should compare if it equals together with model.
Cart.java
boolean cartContainsDifferentTypeVoyage(final String type_voyage) {
ArrayList<Voyage> list = Lists.newArrayList(Collections2.filter(voyages, new Predicate<Voyage>() {
#Override
public boolean apply(Voyage voyage) {
return !voyage.getType_voyage().equals(type_voyage);
}
}));
return list.size() > 0 ? true : false;
}
Bus.java
public class Bus {
private static Bus instance;
private String BROADCAST_TAG = "com.bss.hepsi.bus";
public int hotel_counter = 5;
public int car_counter = 5;
private String logo_link;
private String voyage_code;
private String from_port;
private String from_port_label;
private String from_city;
private String to_port;
private String to_port_label;
private String to_city;
private String company_name;
private boolean has_transfer;
private String telephone_number;
Calendar departureTime = Calendar.getInstance();
private Calendar arrivalTime = Calendar.getInstance();
long departure_time;
long arrival_time;
float price;
ArrayList<Leg> legs = new ArrayList<>();
public ArrayList<BusPassenger> busPasengers = new ArrayList<>();
int direction = MyConstants.DIRECTION_GOING;
private String type_bus;
private boolean has_return;
private Calendar selected_date;
private String goingDate;
private String returnDate;
private Context context;
public boolean in_Cart = false;
public String type;
private String passengerNumber;
boolean isExpanded;
boolean isShowProgress;
public Bus() {
}
public static synchronized Bus getInstance() {
if (instance == null) {
instance = new Bus();
}
instance.setPassengerNumber(ResultActivity.passengerNumber);
instance.setFrom_city(ResultActivity.fromCity);
instance.setTo_city(ResultActivity.toCity);
instance.setGoingDate(ResultActivity.strGoingDate);
instance.setReturnDate(ResultActivity.strReturnDate);
instance.setHas_return(ResultActivity.hasReturn);
return instance;
}
public String getPassengerNumber() {
return passengerNumber;
}
public void setPassengerNumber(String passengerNumber) {
this.passengerNumber = passengerNumber;
}
public boolean isExpanded() {
return this.isExpanded;
}
public void setExpanded(boolean expanded) {
this.isExpanded = expanded;
}
public boolean isShowProgress() {
return this.isShowProgress;
}
public void setShowProgress(boolean showProgress) {
this.isShowProgress = showProgress;
}
public static synchronized void clearInstance() {
instance = null;
}
public String getCompany_name() {
return company_name;
}
public void setCompany_name(String company_name) {
this.company_name = company_name;
}
public String getFrom_port() {
return from_port;
}
public void setFrom_port(String from_port) {
this.from_port = from_port;
}
public String getTo_port() {
return to_port;
}
public void setTo_port(String to_port) {
this.to_port = to_port;
}
public Calendar getSelected_date() {
return selected_date;
}
public void setSelected_date(Calendar selected_date) {
this.selected_date = selected_date;
}
public String getFrom_city() {
return from_city;
}
public void setFrom_city(String from_city) {
this.from_city = from_city;
}
public String getTo_city() {
return to_city;
}
public void setTo_city(String to_city) {
this.to_city = to_city;
}
public String getLogo_link() {
return logo_link;
}
public void setLogo_link(String logo_link) {
this.logo_link = logo_link;
}
public float getPrice() {
return price;
}
public void setPrice(float price) {
this.price = price;
}
public String getTelephone_number() {
return telephone_number;
}
public void setTelephone_number(String telephone_number) {
this.telephone_number = telephone_number;
}
public String getVoyage_code() {
return voyage_code;
}
public void setVoyage_code(String voyage_code) {
this.voyage_code = voyage_code;
}
public String getFrom_port_label() {
return from_port_label;
}
public void setFrom_port_label(String from_port_label) {
this.from_port_label = from_port_label;
}
public String getTo_port_label() {
return to_port_label;
}
public void setTo_port_label(String to_port_label) {
this.to_port_label = to_port_label;
}
public Boolean getHas_transfer() {
return has_transfer;
}
public void setHas_transfer(Boolean has_transfer) {
this.has_transfer = has_transfer;
}
public Calendar getDepartureTime() {
return departureTime;
}
public void setDepartureTime(long departure_time_in_milliseconds) {
this.departureTime.setTimeInMillis(departure_time_in_milliseconds);
}
public Calendar getArrivalTime() {
return arrivalTime;
}
public void setArrivalTime(long return_time_in_milliseconds) {
this.arrivalTime.setTimeInMillis(return_time_in_milliseconds);
}
public int getDirection() {
return direction;
}
public void setDirection(int direction) {
this.direction = direction;
}
public String getGoingDate() {
return goingDate;
}
public void setGoingDate(String goingDate) {
this.goingDate = goingDate;
}
public String getReturnDate() {
return returnDate;
}
public void setReturnDate(String returnDate) {
this.returnDate = returnDate;
}
public boolean getHas_return() {
return has_return;
}
public void setHas_return(boolean has_return) {
this.has_return = has_return;
}
public ArrayList<Leg> getLegs() {
return legs;
}
public void setLegs(ArrayList<Leg> legs) {
this.legs = legs;
}
public long getDeparture_time() {
return departure_time;
}
public void setDeparture_time(long departure_time) {
this.departure_time = departure_time;
}
public long getArrival_time() {
return arrival_time;
}
public void setArrival_time(long arrival_time) {
this.arrival_time = arrival_time;
}
public String getType_bus() {
return type_bus;
}
public void setType_voyage(String type_bus) {
this.type_bus = type_bus;
}
private void sendRequest(final String owner, final Map<String, String> header) {
StringRequest stringRequest = new StringRequest(Request.Method.POST, MyConstants.URL + owner,
new Response.Listener<String>() {
#Override
public void onResponse(String response) {
try {
JSONObject object = new JSONObject(response);
if (object.getString(MyConstants.SERVICE_STATUS).equals(MyConstants.SERVICE_RESPONSE_STATUS_NOTAVAILABLE)) {
sendVoyagesErrorBroadcast(owner, MyConstants.ERROR_NOTAVAILABLE);
} else if (object.getString(MyConstants.SERVICE_STATUS).equals(MyConstants.SERVICE_RESPONSE_STATUS_SUCCESS)) {
JSONArray result = object.getJSONArray(MyConstants.SERVICE_RESULT);
if (result.length()>0) {
JSONArray resultGoing = result.getJSONObject(0).getJSONArray("going");
sendVoyagesArrayBroadcast(owner + MyConstants.DIRECTION_GOING, resultGoing);
}
if (has_return) {
if (result.length() > 1) {
JSONArray resultReturn = result.getJSONObject(1).getJSONArray("round");
if (resultReturn.length()<1){
busReturnIsEmpty();}
else{
busReturnIsNotEmpty();
}
sendVoyagesArrayBroadcast(owner + MyConstants.DIRECTION_RETURN, resultReturn);
}
}
} else if (object.getString(MyConstants.SERVICE_STATUS).equals(MyConstants.SERVICE_RESPONSE_STATUS_FAILURE)) {
sendVoyagesErrorBroadcast(owner, MyConstants.ERROR_SERVER);
}
} catch (JSONException e) {
}
}
},new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
sendVoyagesErrorBroadcast(owner, getErrorType(error));
}
}) {
#Override
public Map<String, String> getHeaders() {
return header;
}
};
stringRequest.setRetryPolicy(new DefaultRetryPolicy(600 * 1000, 0, DefaultRetryPolicy.DEFAULT_BACKOFF_MULT));
MySingleton.getInstance(context).addToRequestQueue(stringRequest);
}
private void sendVoyagesArrayBroadcast(String target, JSONArray resultArray) {
Intent intent = new Intent();
intent.setAction(BROADCAST_TAG + target);
intent.putExtra("data", resultArray.toString());
context.sendBroadcast(intent);
}
public static Bus setJsonToClass(JSONObject jsonObject, int direction, String owner) {
Bus bus = new Gson().fromJson(String.valueOf(jsonObject), Bus.class);
bus.setDirection(direction);
bus.setType_voyage(owner);
bus.setDepartureTime(bus.departure_time);
bus.setArrivalTime(bus.arrival_time);
for (Leg leg :
bus.legs) {
leg.setDepartureTime(leg.departure_time);
leg.setArrivalTime(leg.arrival_time);
}
bus.type = owner;
return bus;
}
Voyage.java
public class Voyage {
private static Voyage instance;
//private static String url="http://78.186.57.167:3000/";
//private static String url="http://10.0.0.27:1337/";
/////public static final String BROADCAST_TAG = "com.bss.hepsi.voyage"; ///bunu kaldırdım static oldugu için
private String BROADCAST_TAG = "com.bss.hepsi.voyage"; ///onun yerine bunu koydum
//private static String url="http://185.122.203.104:3002/";
// private static String url="http://10.0.0.25:1337/";
public int checkCart; // Result activity'de veri gelip gelmediğini kontrol edip kullanıcıyı uyarmak için
public int hotel_counter = 5;
public int car_counter = 5;
private String logo_link;
private String voyage_code;
private String from_port;
private String from_port_label;
private String from_city;
private String to_port;
private String to_port_label;
private String to_city;
private String company_name;
private boolean has_transfer;
private String telephone_number;
Calendar departureTime = Calendar.getInstance();
private Calendar arrivalTime = Calendar.getInstance();
long departure_time;
long arrival_time;
float price;
ArrayList<Leg> legs = new ArrayList<>();
public ArrayList<FlightPassenger> flightPassengers = new ArrayList<>();
int direction = MyConstants.DIRECTION_GOING;
private String type_voyage;
private boolean has_return;
private Calendar selected_date;
private String goingDate;
private String returnDate;
private Context context;
public boolean in_Cart = false;
public String type;
private String passengerNumber;
public Voyage() {
}
public static synchronized Voyage getInstance() {
if (instance == null) {
instance = new Voyage();
}
instance.setPassengerNumber(ResultActivity.passengerNumber);
instance.setFrom_city(ResultActivity.fromCity);
instance.setTo_city(ResultActivity.toCity);
instance.setGoingDate(ResultActivity.strGoingDate);
instance.setReturnDate(ResultActivity.strReturnDate);
instance.setHas_return(ResultActivity.hasReturn);
return instance;
}
public String getPassengerNumber() {
return passengerNumber;
}
public void setPassengerNumber(String passengerNumber) {
this.passengerNumber = passengerNumber;
}
public static synchronized void clearInstance() {
instance = null;
}
public String getCompany_name() {
return company_name;
}
public void setCompany_name(String company_name) {
this.company_name = company_name;
}
public String getFrom_port() {
return from_port;
}
public void setFrom_port(String from_port) {
this.from_port = from_port;
}
public String getTo_port() {
return to_port;
}
public void setTo_port(String to_port) {
this.to_port = to_port;
}
/*public static String getUrl() {
return url;
}*/
public Calendar getSelected_date() {
return selected_date;
}
public void setSelected_date(Calendar selected_date) {
this.selected_date = selected_date;
}
public String getFrom_city() {
return from_city;
}
public void setFrom_city(String from_city) {
this.from_city = from_city;
}
public String getTo_city() {
return to_city;
}
public void setTo_city(String to_city) {
this.to_city = to_city;
}
public String getLogo_link() {
return logo_link;
}
public void setLogo_link(String logo_link) {
this.logo_link = logo_link;
}
public float getPrice() {
return price;
}
public void setPrice(float price) {
this.price = price;
}
public String getTelephone_number() {
return telephone_number;
}
public void setTelephone_number(String telephone_number) {
this.telephone_number = telephone_number;
}
public String getVoyage_code() {
return voyage_code;
}
public void setVoyage_code(String voyage_code) {
this.voyage_code = voyage_code;
}
public String getFrom_port_label() {
return from_port_label;
}
public void setFrom_port_label(String from_port_label) {
this.from_port_label = from_port_label;
}
public String getTo_port_label() {
return to_port_label;
}
public void setTo_port_label(String to_port_label) {
this.to_port_label = to_port_label;
}
public Boolean getHas_transfer() {
return has_transfer;
}
public void setHas_transfer(Boolean has_transfer) {
this.has_transfer = has_transfer;
}
public Calendar getDepartureTime() {
return departureTime;
}
public void setDepartureTime(long departure_time_in_milliseconds) {
this.departureTime.setTimeInMillis(departure_time_in_milliseconds);
}
public Calendar getArrivalTime() {
return arrivalTime;
}
public void setArrivalTime(long return_time_in_milliseconds) {
this.arrivalTime.setTimeInMillis(return_time_in_milliseconds);
}
public int getDirection() {
return direction;
}
public void setDirection(int direction) {
this.direction = direction;
}
public String getGoingDate() {
return goingDate;
}
public void setGoingDate(String goingDate) {
this.goingDate = goingDate;
}
public String getReturnDate() {
return returnDate;
}
public void setReturnDate(String returnDate) {
this.returnDate = returnDate;
}
public boolean getHas_return() {
return has_return;
}
public void setHas_return(boolean has_return) {
this.has_return = has_return;
}
public ArrayList<Leg> getLegs() {
return legs;
}
public void setLegs(ArrayList<Leg> legs) {
this.legs = legs;
}
public long getDeparture_time() {
return departure_time;
}
public void setDeparture_time(long departure_time) {
this.departure_time = departure_time;
}
public long getArrival_time() {
return arrival_time;
}
public void setArrival_time(long arrival_time) {
this.arrival_time = arrival_time;
}
public String getType_voyage() {
return type_voyage;
}
public void setType_voyage(String type_voyage) {
this.type_voyage = type_voyage;
}
public void searchFlightVoyages(Context context) {
this.context = context;
cancelRequest("flight/search", context);
Map<String, String> header = prepareVoyageSearchHeaderForFlight();
sendRequest("flight/search", header);
}
public void searchTrainVoyages(Context context) {
this.context = context;
cancelRequest("train/search", context);
Map<String, String> header = prepareVoyageSearchHeader();
sendRequest("train/search", header);
}
public void searchBoatVoyages(Context context) {
this.context = context;
cancelRequest("seaway/boat/search", context);
Map<String, String> header = prepareVoyageSearchHeader();
sendRequest("seaway/boat/search", header);
}
public void searchFerryVoyages(Context context) {
this.context = context;
cancelRequest("seaway/ferry/search", context);
Map<String, String> header = prepareVoyageSearchHeader();
sendRequest("seaway/ferry/search", header);
}
private void sendRequest(final String owner, final Map<String, String> header) {
StringRequest stringRequest = new StringRequest(Request.Method.POST, MyConstants.URL + owner,
new Response.Listener<String>() {
#Override
public void onResponse(String response) {
Log.e("AAAA" + owner, response);
try {
JSONObject object = new JSONObject(response);
if (object.getString(MyConstants.SERVICE_STATUS).equals(MyConstants.SERVICE_RESPONSE_STATUS_NOTAVAILABLE)) {
// servisten gelen cevap not_available ise
//// owner
sendVoyagesErrorBroadcast(owner, MyConstants.ERROR_NOTAVAILABLE);
} else if (object.getString(MyConstants.SERVICE_STATUS).equals(MyConstants.SERVICE_RESPONSE_STATUS_SUCCESS)) {
// servisten gösterilebilecek bir sonuç geldiyse
JSONArray result = object.getJSONArray(MyConstants.SERVICE_RESULT);
if (result.length()>0) {
// checkCart=0;
// sendCheckCart();
JSONArray resultGoing = result.getJSONObject(0).getJSONArray("going");
sendVoyagesArrayBroadcast(owner + MyConstants.DIRECTION_GOING, resultGoing);
}
if (has_return) {
if (result.length() > 1) {
JSONArray resultReturn = result.getJSONObject(1).getJSONArray("round");
sendVoyagesArrayBroadcast(owner + MyConstants.DIRECTION_RETURN, resultReturn);
}
}
} else if (object.getString(MyConstants.SERVICE_STATUS).equals(MyConstants.SERVICE_RESPONSE_STATUS_FAILURE)) {
sendVoyagesErrorBroadcast(owner, MyConstants.ERROR_SERVER);
}
} catch (JSONException e) {
Log.e("search" + owner + "VoyagesErr1", e.toString());
e.printStackTrace();
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Log.e("AAAA" + owner, String.valueOf(error.getCause()));
sendVoyagesErrorBroadcast(owner, getErrorType(error));
}
}) {
#Override
public Map<String, String> getHeaders() {
return header;
}
};
stringRequest.setTag(owner);
stringRequest.setRetryPolicy(new DefaultRetryPolicy(60 * 1000, 0, DefaultRetryPolicy.DEFAULT_BACKOFF_MULT));
MySingleton.getInstance(context).addToRequestQueue(stringRequest);
}
public static Voyage setJsonToClass(JSONObject jsonObject, int direction, String owner) {
//Log.e("jsonobj", String.valueOf(jsonObject));
Voyage voyage = new Gson().fromJson(String.valueOf(jsonObject), Voyage.class);
voyage.setDirection(direction);
voyage.setType_voyage(owner);
voyage.setDepartureTime(voyage.departure_time);
voyage.setArrivalTime(voyage.arrival_time);
for (Leg leg :
voyage.legs) {
leg.setDepartureTime(leg.departure_time);
leg.setArrivalTime(leg.arrival_time);
}
voyage.type = owner;
return voyage;
}
When you remove all the code from your question that is superfluous, it makes the problem more obvious.
First I simplified your comparison method:
Cart.java
boolean cartContainsDifferentTypeVoyage(final String type_voyage) {
for(Voyage voyage : voyages) {
if(!type_voyage.equals(voyage.getType_voyage()) {
return true;
}
}
}
Then created an interface
interface Voyage {
String getType_voyage();
}
Bus.java
public class Bus implements Voyage {
...
private String type_voyage;
#Override
public String getType_voyage() {
return type_voyage;
}
...
}
And changed Voyage.java to Ferry.java
public class Ferry implements Voyage {
...
private String type_voyage;
...
#Override
public String getType_voyage() {
return type_voyage;
}
...
}
You may want to look at creating some more classes so that your 'model' classes are not doing to much / have so many responsibilities.
The above image is a simple design that I want to develop.
I have four type of different data with different view type like the below image enter image description here. but that is not a problem. problem is the data will come from different API with lazy loading like when user scroll the list from recycle view it will grab the data from the server. My question is how to combine them in a single adapter because I need to use lazy loading .so I can't load whole data at a time so I need to call the different type of API like goal-list API, appraisal API, post API etc. When user scroll. anyone can give me an idea with example. How can I handle that? Also when user will scroll it will call another api likeCount and comment count also. Currently, In my, I am calling single API and show that in the single recycle view. Currently, I am using android architecture component LiveData
Fragment :
public class NewsFeedFragment extends FcaFragment {
private View view;
private RecyclerView postRecyclerView;
private PostsAdapter postsAdapter;
private List<Post> posts;
private TimelineViewModel timelineViewModel;
private ImageView addPostView;
private View addPostPanel;
private long lastApiCallTime;
private SwipyRefreshLayout swipeRefresh;
private long lastScroolItemInPost= 0;
public NewsFeedFragment() {
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
if(lastScroolItemInPost < 1) {
initViewModel(1 , 0 , true);
lastScroolItemInPost = 1;
}else {
initViewModel(((int) lastScroolItemInPost + 5), lastScroolItemInPost , true);
lastScroolItemInPost += 5;
}
final LinearLayoutManager linearLayoutManager = new LinearLayoutManager(ownerActivity);
view = inflater.inflate(R.layout.fragment_news_feed, container, false);
postRecyclerView = (RecyclerView) view.findViewById(R.id.postRecyclerView);
postRecyclerView.addOnScrollListener(new RecyclerView.OnScrollListener() {
#Override
public void onScrollStateChanged(RecyclerView recyclerView, int newState) {
super.onScrollStateChanged(recyclerView, newState);
}
#Override
public void onScrolled(RecyclerView postRecyclerView, int dx, int dy) {
super.onScrolled(postRecyclerView, dx, dy);
int lastVisiableItemInPostList = linearLayoutManager.findLastVisibleItemPosition();
if(lastScroolItemInPost < lastVisiableItemInPostList)
{
if(lastScroolItemInPost == 1)
{
initViewModel((int) (lastScroolItemInPost + 2), ( lastScroolItemInPost - 2 ) , false);
lastScroolItemInPost += 2;
}else{
initViewModel((int) (lastScroolItemInPost + 2), ( lastScroolItemInPost - 2 ) , false );
lastScroolItemInPost += 2;
}
}
}
});
posts = new ArrayList<>();
postRecyclerView.setLayoutManager(linearLayoutManager);
postsAdapter = new PostsAdapter(ownerActivity,posts,timelineViewModel);
postRecyclerView.setAdapter(postsAdapter);
swipeRefresh = (SwipyRefreshLayout) view.findViewById(R.id.swipeRefresh);
swipeRefresh.setOnRefreshListener(new SwipyRefreshLayout.OnRefreshListener() {
#Override
public void onRefresh(SwipyRefreshLayoutDirection direction) {
if(direction == SwipyRefreshLayoutDirection.TOP){
timelineViewModel.fetchPosts2();
}
if(direction == SwipyRefreshLayoutDirection.BOTTOM){
timelineViewModel.fetchPosts();
}
}
});
return view;
}
private void initViewModel(int lastVisiableItemInPostList , long lastScroolItemInPost , boolean isFirstTimeOpenFeedFragment) {
TimelineViewModel.Factory factory = new TimelineViewModel.Factory(UserPreferences.getToken(ownerActivity), TaskUtils.getMySelfContact(ownerActivity));
timelineViewModel = ViewModelProviders.of(this,factory).get(TimelineViewModel.class);
timelineViewModel.getPostList().observe(this, new Observer<List<Post>>() {
#Override
public void onChanged(#Nullable List<Post> posts) {
postsAdapter.setPostList(posts);
swipeRefresh.setRefreshing(false);
}
});
timelineViewModel.getPostDeleted().observe(this, new Observer<Boolean>() {
#Override
public void onChanged(#Nullable Boolean aBoolean) {
if(aBoolean){
postsAdapter.setPostList(Post.getAll());
}
}
});
timelineViewModel.init( lastVisiableItemInPostList , lastScroolItemInPost ,isFirstTimeOpenFeedFragment);
}
}
ViewModel :
public class TimelineViewModel extends FCViewModel implements PostDetailsDownloadManager.PostDetailDownloadedListener,OnContactReceivedListner{
public TimelineViewModel(String token,Contact user){
super(token);
this.user = user;
post = new MutableLiveData<>();
postDeleted = new MutableLiveData<>();
}
public void init(int lastVisiableItemInPostList , long lastScroolItemInPost , boolean isFirstTimeOpenFeedFragment){
repository =
//postDetailsDownloadManager = ServiceLocator.getServiceLocator().postDetailsDownloadManager;
likePostDownloadManager = ServiceLocator.getServiceLocator().likePostDownloadManager;
likePostDownloadManager.setPostDetailDownloadedListener(new DataDownloadManager.DataDownloadedListener<LikePostTouple>() {
#Override
public void onDataDownloaded(List<LikePostTouple> dataTouple) {
TimelineViewModel.this.post.setValue(Post.getAll());
}
#Override
public void onSingleDataDownloaded(LikePostTouple dataTouple) {
}
});
postDetailDownloadManager = ServiceLocator.getServiceLocator().postDetailDownloadManager;
postDetailDownloadManager.setPostDetailDownloadedListener(new DataDownloadManager.DataDownloadedListener<PostTouple>() {
#Override
public void onDataDownloaded(List<PostTouple> dataTouple) {
TimelineViewModel.this.post.setValue(Post.getAll());
}
#Override
public void onSingleDataDownloaded(PostTouple dataTouple) {
}
});
post.setValue(Post.getAll());
if(isFirstTimeOpenFeedFragment)
{
fetchPosts2();
}
try {
if(Post.getAll().size() > 0)
{
List<Post> tempPosts = Post.getAll();
List<Post> passList = tempPosts.subList( (int) lastScroolItemInPost ,lastVisiableItemInPostList);
fetchLikesOfPosts(passList);
}else{
fetchLikesOfPosts(Post.getAll());
}
} catch (Exception e) {
e.printStackTrace();
}
Log.d("Testing Injecting", repository.toString());
}
public LiveData<List<Post>> getPostList() {
return post;
}
public MutableLiveData<Boolean> getPostDeleted() {
return postDeleted;
}
boolean isContactFetched = false;
public void fetchPosts(){
if(Contact.getAll().size() < 1){
fetchContacts();
return;
}
Map<String,Object> requestData = new HashMap<>();
requestData.put("type",1);
requestData.put("cpid",Post.getLastPid());
isDataLoading = true;
repository.getData(new Repository.DataFetchedListener<List<Post>>() {
#Override
public void onDataFetched(List<Post> posts) {
isDataLoading = false;
Log.d("fetched posts",""+posts.size());
post.setValue(Post.getAll());
fetchPostDetails(posts);
if(posts.size() > 0){
fetchLikesOfPosts(posts);
}
}
},requestData);
}
private boolean isDataLoading = false;
public void fetchPosts2(){
if(Contact.getAll().size() < 1){
fetchContacts();
return;
}
Map<String,Object> requestData = new HashMap<>();
requestData.put("type",2);
requestData.put("cpid", Post.getFirstPid()); // cpid means cursor pid
isDataLoading = true;
repository.getData(new Repository.DataFetchedListener<List<Post>>() {
#Override
public void onDataFetched(List<Post> posts) {
isDataLoading = false;
Log.d("fetched posts",""+posts.size());
post.setValue(Post.getAll());
fetchPostDetails(posts);
if(posts.size() > 0){
fetchLikesOfPosts(posts);
}
}
},requestData);
}
public boolean isDataLoading() {
return isDataLoading;
}
private void fetchContacts() {
contactRepository.getData(new Repository.DataFetchedListener<List<Contact>>() {
#Override
public void onDataFetched(List<Contact> data) {
if(data.size()>0 && !isContactFetched) {
fetchPosts2();
isContactFetched = true;
}
}
},null);
}
#NonNull
private PostTouple getPostToubleFromPost(Post post) throws JSONException {
Gson gson = new GsonBuilder().excludeFieldsWithoutExposeAnnotation().create();
String json = gson.toJson(post);
JSONObject postJson = new JSONObject(json);
return new PostTouple(postJson,post.getPid());
}
#NonNull
private LikePostTouple getLkePostToupleFromPost(Post post) throws JSONException {
Gson gson = new GsonBuilder().excludeFieldsWithoutExposeAnnotation().create();
String json = gson.toJson(post);
JSONObject postJson = new JSONObject(json);
return new LikePostTouple(postJson,post.getPid());
}
public void giveLike(String token, final long pid){
Map<String,Object> requestData = new HashMap<>();
requestData.put("token",token);
requestData.put("pid",Long.toString(pid));
likeRepository.postData(new Repository.DataFetchedListener<Post>() {
#Override
public void onDataFetched(Post data) {
Log.d("Like post", data.toString());
Post post = getPostById(pid);
post.setLikes(data.getLikes());
post.setComments(data.getComments());
TimelineViewModel.this.post.setValue(TimelineViewModel.this.post.getValue());
fetchLikesOfLikedPost(data);
}
},requestData);
}
private void fetchLikesOfLikedPost(Post data) {
try {
likePostDownloadManager.addItemInQueue(getLkePostToupleFromPost(data));
likePostDownloadManager.startDownload();
} catch (JSONException e) {
e.printStackTrace();
}
}
private Post getPostById(long pid){
List<Post> posts = post.getValue();
for(Post post : posts){
if(post.getPid()==pid){
return post;
}
}
return null;
}
public Contact getSenderContactFromComment(Post post) {
if(post.getPqrc().equals(user.getUserId())){
return user;
}
Contact contact = Contact.getByUserId(post.getPqrc());
return contact;
}
public String getDescriptionForType5(Post post,String message){
try {
PostDetail postDetail = PostDetail.getByPostId(post.getPid());
if(postDetail!=null) {
String qrc = JSonUtils.qrcFromCntOfPostDetails(postDetail.getContent());
int sid = JSonUtils.skillidFromCntOfPostDetails(postDetail.getContent());
if (qrc == null || sid == 0) {
return "";
}
SkillDb skill = SkillDb.getBySId(Integer.toString(sid));
Contact contact = getPosterContact(post.getPqrc());
return contact.getName() + " " + message + " " + skill.getSkillName() + ".";
}
return "";
} catch (Exception e) {
e.printStackTrace();
}
return "";
}
public String getDescriptionForPost(Post post, String message){
if(post.getCtype()==1){
return post.getDescr();
}
if(post.getCtype() == 2){
String postDetail = getContent(post);
if (postDetail != null) return Html.fromHtml(""+postDetail+"").toString();
}
if(post.getCtype()==5){
return getDescriptionForType5(post, message);
}
return "";
}
#Nullable
public String getContent(Post post) {
PostDetail postDetail = PostDetail.getByPostId(post.getPid());
if(postDetail!=null){
return postDetail.getContent();
}
return null;
}
public Contact getPosterContact(String qrc){
try {
String userqrc = user.getUserId();
if (userqrc.equals(qrc)) {
return user;
}
}catch (Exception e){
e.printStackTrace();
}
try {
return Contact.getByUserId(qrc);
}catch (Exception e){
e.printStackTrace();
}
return null;
}
public void fetchUrlPreview(String url, final UrlMetaDataFetchListener metaDataFetchListener){
String modifiedUrl = !url.contains("http://")&&!url.contains("https://")? "http://"+url : url;
TextCrawler textCrawler = new TextCrawler();
LinkPreviewCallback linkPreviewCallback = new LinkPreviewCallback() {
#Override
public void onPre() {
}
#Override
public void onPos(SourceContent sourceContent, boolean b) {
String imageUrl = sourceContent.getImages().isEmpty()? "" : sourceContent.getImages().get(0);
metaDataFetchListener.onMetaDataFetched(sourceContent.getTitle(),sourceContent.getDescription(), imageUrl);
}
};
textCrawler.makePreview(linkPreviewCallback, modifiedUrl,1);
}
public interface UrlMetaDataFetchListener{
void onMetaDataFetched(String title, String description, String imageUrl);
}
#Override
public void onPostDownloaded(PostTouple postTouple) {
this.post.setValue(Post.getAll());
}
#Override
public void onContactsReceived() {
fetchPosts();
}
public void deletePost(long pid) {
Map<String, Object> requestData = new HashMap<>();
requestData.put("token",token);
requestData.put("pid",pid);
repository.postData(new Repository.DataFetchedListener<Post>() {
#Override
public void onDataFetched(Post data) {
postDeleted.setValue(data!=null);
}
},requestData);
}
public boolean isMyPost(Post post){
return user.getUserId().equals(post.getPqrc());
}
public static class Factory extends ViewModelProvider.NewInstanceFactory {
private String token;
private Contact user;
public Factory(String token,Contact user) {
this.token = token;
this.user = user;
}
#Override
public <T extends ViewModel> T create(Class<T> modelClass) {
return (T) new TimelineViewModel(token,user);
}
}
}
Adapter :
public class PostsAdapter extends RecyclerView.Adapter {
private Context context;
private List<Post> postList;
private int[] badges = {R.drawable.badge1, R.drawable.badge2, R.drawable.badge3};
private List<Integer> randomNumbers = Utils.getRandomNumberList(2,true);
private ArrayDeque<Integer> randomQueue = new ArrayDeque<>(randomNumbers);
private static Map<Long,URLPreview> urlPreviewMap = new HashMap<>();
private TimelineViewModel timelineViewModel;
public PostsAdapter(Context context, List<Post> postList, TimelineViewModel timelineViewModel){
super();
this.context = context;
this.postList = postList;
this.timelineViewModel = timelineViewModel;
}
#Override
public RecyclerView.ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
LayoutInflater inflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
View view = inflater.inflate(R.layout.post_item_layout, null);
PostViewHolder postViewHolder = new PostViewHolder(view);
postViewHolder.setIsRecyclable(false);
return postViewHolder;
}
#Override
public void onBindViewHolder(RecyclerView.ViewHolder holder, final int position) {
final Post post = postList.get(position);
final PostViewHolder postViewHolder = (PostViewHolder) holder;
final String postDetail = timelineViewModel.getDescriptionForPost(post,context.getResources().getString(R.string.postType5message));
setPostDescription(post, postViewHolder, postDetail);
handlePreviewVisibility(post, postViewHolder);
postViewHolder.setLikes(""+post.getLikes()+" Likes");
postViewHolder.setCommentCount("" + post.getComments() + " Comments");
postViewHolder.setSupDescription("Posted By System");
int randomNumber = getRandomNumber();
postViewHolder.setBadgeIcon(badges[randomNumber]);
setPostLikedIndicator(post, postViewHolder);
postViewHolder.getLikeButtonWrapper().setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
giveLikeToPost(post);
if(post.getIsLiked() == 0) {
post.setLikes(post.getLikes() + 1);
postViewHolder.setLikes("" + post.getLikes() + " Likes");
post.setIsLiked(1);
setPostLikedIndicator(post, postViewHolder);
}
}
});
postViewHolder.getCommentPanel().setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
CommentPostFragment fragment = CommentPostFragment.GetInstance(post.getPid());
ViewUtils.launchFragmentKeepingInBackStack(context,fragment);
}
});
Contact contact = timelineViewModel.getPosterContact(post.getPqrc());
if(contact!=null && TaskUtils.isNotEmpty(contact.getImageToken())){
Utils.setImageToImageView(postViewHolder.getPosterImage(),timelineViewModel.getToken(),contact.getImageToken());
postViewHolder.getPosterNameTextView().setText(contact.getName());
}
postViewHolder.getPostingDate().setText(Utils.getDateFromMilliseconds(post.getdC()));
if(post.getCtype() != 3)
{
postViewHolder.contentImage.setVisibility(View.GONE);
postViewHolder.fullScreenIndicatorIcon.setVisibility(View.GONE);
}
if(post.getCtype() == 3){
setContentOfType3(post, postViewHolder);
}
}
#Override
public void onViewRecycled(RecyclerView.ViewHolder holder) {
super.onViewRecycled(holder);
PostViewHolder viewHolder = (PostViewHolder) holder;
viewHolder.pTitle.setText("");
viewHolder.pDescription.setText("");
viewHolder.pImage.setImageDrawable(null);
}
private void handlePreviewVisibility(Post post, PostViewHolder postViewHolder) {
if(post.getCtype()==2){
postViewHolder.preview.setVisibility(View.VISIBLE);
}else{
postViewHolder.preview.setVisibility(View.GONE);
}
}
private void handleShowingOptionsIcon(Post post, PostViewHolder postViewHolder) {
if(post.getCtype()!=5 && timelineViewModel.isMyPost(post)){
postViewHolder.options.setVisibility(View.VISIBLE);
}else{
postViewHolder.options.setVisibility(View.GONE);
}
}
private void giveLikeToPost(Post post) {
post.setLikes(post.getLikes()+1);
post.setIsLiked(1);
//notifyDataSetChanged();
timelineViewModel.giveLike(UserPreferences.getToken(context),post.getPid());
}
private void setPostLikedIndicator(Post post, PostViewHolder postViewHolder) {
if(post.getIsLiked()==1) {
postViewHolder.getLikeButton().setImageDrawable(ResourcesCompat.getDrawable(context.getResources(), R.drawable.ic_like_red, null));
}else{
postViewHolder.getLikeButton().setImageDrawable(ResourcesCompat.getDrawable(context.getResources(), R.drawable.ic_like_filled, null));
}
}
private void setPostDescription(final Post post, final PostViewHolder postViewHolder, final String postDetail) {
if(post.getCtype()==2){
String postDescription = "<p>"+ post.getDescr()+"</p>";
postViewHolder.description.setText( Html.fromHtml(postDescription +""+postDetail+"") );
postViewHolder.descriptionContainer.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
String url = !postDetail.contains("http://")&&!postDetail.contains("https://")? "http://"+postDetail : postDetail;
Uri uri = Uri.parse(url);
context.startActivity(new Intent(Intent.ACTION_VIEW,uri));
}
});
URLPreview urlPreview = null;
if((urlPreview=urlPreviewMap.get(post.getPid()))==null) {
timelineViewModel.fetchUrlPreview(postDetail, new TimelineViewModel.UrlMetaDataFetchListener() {
#Override
public void onMetaDataFetched(String title, String description, String imageUrl) {
showURLPreview(title, description, imageUrl, postViewHolder);
urlPreviewMap.put(post.getPid(),new URLPreview(title,description,imageUrl));
}
});
}else {
showURLPreview(urlPreview.getTitle(),urlPreview.getDescription(),urlPreview.getImageUrl(),postViewHolder);
}
}else if(post.getCtype() == 3)
{
String postDescription = post.getDescr();
postViewHolder.description.setText(postDescription);
}
else {
postViewHolder.setDescription(postDetail);
}
}
private void initImageClickListener(final ImageView imageView, final String pictureLink) {
imageView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
List<String> pictureLinks = new ArrayList<String>();
pictureLinks.add(pictureLink);
int[] screenLocation = new int[2];
imageView.getLocationOnScreen(screenLocation);
ImagePagerFragment imagePagerFragment = ImagePagerFragment.newInstance(pictureLinks, 0, screenLocation, imageView.getWidth(), imageView.getHeight());
ViewUtils.launchPopUpFragmentUpdated(context, imagePagerFragment);
}
});
}
private void showURLPreview(String title, String description, String imageUrl, PostViewHolder postViewHolder) {
context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
if(!TaskUtils.isEmpty(imageUrl)) {
Picasso.with(context)
.load(imageUrl)
.into(postViewHolder.pImage);
}
view.findViewById(R.id.description);
postViewHolder.pTitle.setText(title);
postViewHolder.pDescription.setText(description);
}
#Override
public int getItemCount() {
return postList.size();
}
private int getRandomNumber(){
if(!randomQueue.isEmpty()){
return randomQueue.poll();
}
randomQueue = new ArrayDeque<>(randomNumbers);
return randomQueue.poll();
}
public void setPostList(List<Post> postList) {
this.postList = postList;
notifyDataSetChanged();
Log.d("Data rec", postList.size()+"");
}
class PostViewHolder extends RecyclerView.ViewHolder implements PopupMenu.OnMenuItemClickListener {
}
public void setLikes(String likes) {
this.likes.setText(likes);
}
public void setCommentCount(String commentCount)
{
this.commentCount.setText(commentCount);
}
public void setDescription(String description){
this.description.setText(description);
}
public void setSupDescription(String subDescription){
this.supDescription.setText(subDescription);
}
public void setBadgeIcon(int resID){
Utils.setImageViewFromResource(badgeIcon,resID);
}
public ImageView getLikeButton() {
return likeButton;
}
public RelativeLayout getLikeButtonWrapper()
{
return likeButtonWrapper;
}
public ImageView getCommentButton() {
return commentButton;
}
public ImageView getPosterImage() {
return posterImage;
}
public TextView getPosterNameTextView() {
return posterNameTextView;
}
public TextView getPostingDate() {
return postingDate;
}
public RelativeLayout getCommentPanel() {
return commentPanel;
}
#Override
public boolean onMenuItemClick(MenuItem item) {
timelineViewModel.deletePost(postList.get(getAdapterPosition()).getPid());
return false;
}
}
}
I'm trying to use blog id to get JSON object from server. At the moment I'm getting this error
java.lang.NullPointerException: Attempt to invoke interface method 'java.util.Iterator java.util.List.iterator()
on a null object reference`.How do I use the post Id to get the full content what am I doing wrong. Please help!!!
MyBlog Adapter:
public class MyBlogAdapter extends RecyclerView.Adapter<BlogViewHolder> {
List<BlogResponse> postsList;
Context context;
public static String blog_Id, blogID;
private LayoutInflater inflater;
public MyBlogAdapter(Context context, List<BlogResponse> postsList){
this.context = context;
this.inflater = LayoutInflater.from(context);
this.postsList = postsList;
}
#Override
public BlogViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View view = inflater.inflate(R.layout.custom_view,parent, false);
return new BlogViewHolder(view);
}
#Override
public void onBindViewHolder(BlogViewHolder holder, int position) {
final BlogResponse posts= postsList.get(position);
holder.summary.setText(posts.getBlogExcerpt().trim().toString());
holder.title.setText(posts.getBlogTitle().trim().toString());
// Glide.with(context).load(posts.getBlogThumbnail()).into(holder.cover);
holder.blogHolder.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Intent intent = new Intent(context, AnotherSingleView.class);
blog_Id = posts.getBlogId();
intent.putExtra(blogID,blog_Id);
Log.d("MyblogAdapter","Please check blog Id: "+blog_Id);
context.startActivity(intent);
}
});
}
#Override
public int getItemCount() {
Log.d("MyBlogAdapter,","getItemCount"+postsList.size());
return postsList == null ? (0) : postsList.size();
}
}
SecondActivity:
public class AnotherSingleView extends AppCompatActivity {
String postID;
int position;
public TextView blogTitle,blogSub,blogContent;
public ImageView blogPic;
List<SingleBlogPost> singleBlogPosts;
SingleBlogPost singleBlogPost;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_another_single_view);
Intent intent = getIntent();
Bundle showBlogId = intent.getExtras();
postID = showBlogId.getString(blogID);
Log.d("AnotherSingleView","Please check blog Id: "+postID);
singleBlogPosts = new ArrayList<>();
blogContent = (TextView)findViewById(R.id.blog_content);
blogSub = (TextView) findViewById(R.id.blog_subtitle);
blogTitle =(TextView) findViewById(R.id.blog_title);
blogPic =(ImageView) findViewById(R.id.blog_pix);
singlePostDisplay();
}
private void singlePostDisplay() {
BlogaPI api = ApiClient.getBlogInterface();
Call<List<SingleBlogPost>> call = api.postResponse(postID);
call.enqueue(new Callback<List<SingleBlogPost>>() {
#Override
public void onResponse(Call<List<SingleBlogPost>> call, Response<List<SingleBlogPost>> response) {
singleBlogPosts = response.body();
if (singleBlogPosts != null && !singleBlogPosts.isEmpty() ){
for (SingleBlogPost posts : singleBlogPosts){
Log.d("AnotherSingleView","Please check RESPONSE: "+response.body().toString());
blogTitle.setText(posts.getBlogTitle());
blogSub.setText(posts.getBlogSubtitle());
blogContent.setText(posts.getBlogContent());
// Glide.with(AnotherSingleView.this).load(singlepost.getBlogMedimg()).into(blogPic);
}
}
else{
Toast.makeText(AnotherSingleView.this, "Something is empty", Toast.LENGTH_SHORT).show();
} }
#Override
public void onFailure(Call<List<SingleBlogPost>> call, Throwable t) {
Toast.makeText(AnotherSingleView.this, "check again: "+t.toString(), Toast.LENGTH_SHORT).show();
}
});
}
}
Interface:
public interface BlogaPI {
#GET("blog")
Call<BlogList> response();
#GET("post/{blog_id}")
Call<List<SingleBlogPost>> postResponse(#Path("blog_id") String blog_id);
//Call<List<SingleBlogPost>> postResponse();
}
SingleBlogPost:
public class SingleBlogPost {
#SerializedName("blog_id")
#Expose
private String blogId;
#SerializedName("blog_title")
#Expose
private String blogTitle;
#SerializedName("blog_subtitle")
#Expose
private String blogSubtitle;
#SerializedName("blog_excerpt")
#Expose
private String blogExcerpt;
#SerializedName("blog_content")
#Expose
private String blogContent;
#SerializedName("blog_thumbnail")
#Expose
private String blogThumbnail;
#SerializedName("blog_medimg")
#Expose
private String blogMedimg;
#SerializedName("category_title")
#Expose
private String categoryTitle;
public SingleBlogPost(String blogId,String blogTitle, String blogSubtitle, String blogExcerpt,
String blogContent, String blogThumbnail, String blogMedimg, String categoryTitle){
this.blogId = blogId;
this.blogTitle = blogTitle;
this.blogSubtitle = blogSubtitle;
this.blogExcerpt = blogExcerpt;
this.blogContent = blogContent;
this.blogThumbnail = blogThumbnail;
this.blogMedimg = blogMedimg;
this.categoryTitle = categoryTitle;
}
public String getBlogId() {
return blogId;
}
public void setBlogId(String blogId) {
this.blogId = blogId;
}
public String getBlogTitle() {
return blogTitle;
}
public void setBlogTitle(String blogTitle) {
this.blogTitle = blogTitle;
}
public String getBlogSubtitle() {
return blogSubtitle;
}
public void setBlogSubtitle(String blogSubtitle) {
this.blogSubtitle = blogSubtitle;
}
public String getBlogExcerpt() {
return blogExcerpt;
}
public void setBlogExcerpt(String blogExcerpt) {
this.blogExcerpt = blogExcerpt;
}
public String getBlogContent() {
return blogContent;
}
public void setBlogContent(String blogContent) {
this.blogContent = blogContent;
}
public String getBlogThumbnail() {
return blogThumbnail;
}
public void setBlogThumbnail(String blogThumbnail) {
this.blogThumbnail = blogThumbnail;
}
public String getBlogMedimg() {
return blogMedimg;
}
public void setBlogMedimg(String blogMedimg) {
this.blogMedimg = blogMedimg;
}
public String getCategoryTitle() {
return categoryTitle;
}
public void setCategoryTitle(String categoryTitle) {
this.categoryTitle = categoryTitle;
}
}
Check if the server response is different then null before you do a enhanced for like this:
if(singleBlogPosts!= null) {
for (SingleBlogPosts posts : singleBlogPosts){
Log.d("AnotherSingleView","Please check RESPONSE: "+response.body().toString());
blogTitle.setText(posts.getBlogTitle());
blogSub.setText(posts.getBlogSubtitle());
blogContent.setText(posts.getBlogContent());
// Glide.with(AnotherSingleView.this).load(singlepost.getBlogMedimg()).into(blogPic);
}
}
you question was list iterator,but we can`t see you list use on anywhere,i guess you may be use recyclerView on you data has not get,because get data was asynchronous.try to use data if you can sure it is existing.
I have this JSON data and I'm trying to display "measurements" part, but it doesn't work.
(I'm getting this: java.lang.IllegalStateException: Expected BEGIN_OBJECT but was BEGIN_ARRAY at line 1 column 2 path $).
I'm beginner at Android developing, this is my first app and I just don't know how to fix this.
Here JSON:
[{
"id":1,
"type":"TEMPERATURE",
"measurements":[
{
"value":"22.58",
"time":"2017-01-11T12:20:44.701"
}]
},{
"id":2,
"type":"HUMIDITY",
"measurements":[
{
"value":"52.366",
"time":"2017-01-11T12:20:44.731"
}]
},{
"id":3,
"type":"LUMINOSITY",
"measurements":[
{
"value":"1.0",
"time":"2017-01-11T12:20:44.742"
}]
}]
Adapter:
public class SenzoriAdapter extends RecyclerView.Adapter < SenzoriAdapter.ViewHolder > {
private ArrayList < Measurement > mSenzori;
public SenzoriAdapter(ArrayList < Measurement > senzori) {
this.mSenzori = senzori;
}
#Override
public SenzoriAdapter.ViewHolder onCreateViewHolder(ViewGroup viewGroup, int i) {
View view = LayoutInflater.from(viewGroup.getContext()).inflate(R.layout.main_item, viewGroup, false);
return new ViewHolder(view);
}
#Override
public void onBindViewHolder(SenzoriAdapter.ViewHolder viewHolder, int i) {
String datum = mSenzori.get(i).getTime().replace("T", " ");
viewHolder.senzoriLastAlive.setText(datum);
String stringdouble = Double.toString(mSenzori.get(i).getValue());
viewHolder.senzoriMeasurement.setText(stringdouble);
}
#Override
public int getItemCount() {
return mSenzori.size();
}
public class ViewHolder extends RecyclerView.ViewHolder {
private TextView senzoriLastAlive, senzoriMeasurement;
public ViewHolder(View itemView) {
super(itemView);
senzoriLastAlive = (TextView) itemView.findViewById(R.id.senzoriLastAlive);
senzoriMeasurement = (TextView) itemView.findViewById(R.id.senzoriMeasurement);
}
}
}
Model Senzori:
public class Senzori {
#Expose
private Integer id;
#Expose
private String type;
#Expose
private Measurement[] measurements;
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public String getType() {
return type;
}
public void setType(String type) {
this.type = type;
}
public Measurement[] getMeasurement() {
return measurements;
}
}
Model Measurement:
public class Measurement {
#Expose
private Double value;
#Expose
private String time;
public Double getValue() {
return value;
}
public void setValue(Double value) {
this.value = value;
}
public String getTime() {
return time;
}
public void setTime(String time) {
this.time = time;
}
}
and usage in Activity:
public void configViews() {
mRecyclerView = (RecyclerView) findViewById(recyclerView);
mRecyclerView.setHasFixedSize(true);
RecyclerView.LayoutManager layoutManager = new LinearLayoutManager(getApplicationContext());
mRecyclerView.setLayoutManager(layoutManager);
loadJSON();
}
public void loadJSON() {
Retrofit retrofit = new Retrofit.Builder()
.baseUrl(MainActivity.BASE_URL)
.addConverterFactory(GsonConverterFactory.create())
.build();
SenzoriInterface request = retrofit.create(SenzoriInterface.class);
Call < Senzori > call = request.getAllSenzori(MainActivity.BASE_URL + "/sensors/");
call.enqueue(new Callback < Senzori > () {
#Override
public void onResponse(Call < Senzori > call, Response < Senzori > response) {
Senzori jsonResponse = response.body();
senzori = new ArrayList < > (Arrays.asList(jsonResponse.getMeasurement()));
senzoriAdapter = new SenzoriAdapter(senzori);
mRecyclerView.setAdapter(senzoriAdapter);
}
#Override
public void onFailure(Call < Senzori > call, Throwable t) {
Log.d("Error", t.getMessage());
}
});
}
You are expecting a single object, but response is giving you an array of objects.
Change
Call<Senzori> call = request.getAllSenzori(MainActivity.BASE_URL+"/sensors/");
To
Call<List<Senzori>> call = request.getAllSenzori(MainActivity.BASE_URL+"/sensors/");
And update your code accordingly.
call.enqueue(new Callback<List<Senzori>>() {
#Override
public void onResponse(Call<List<Senzori>> call, Response<List<Senzori>> response) {
senzori = response.body();
senzoriAdapter = new SenzoriAdapter(senzori.getMeasurement());
mRecyclerView.setAdapter(senzoriAdapter);
}
#Override
public void onFailure(Call<List<Senzori>> call, Throwable t) {
Log.d("Error",t.getMessage());
}
});
In the below android activity, trying to display data in a view pager and it is working as expected.
But in loadItemsForSuppliers method, when i am adding SupplierAndItemList object to it's arraylist, value returned from getInventoriesByItemDetails method is not updating properly rather takes last value always.
Can some body assist me what's wrong here ?
public class ScreenSlidePagerActivity extends BaseActivity {
private ViewPager mPager;
private PagerAdapter mPagerAdapter;
private Dealer dealerObject;
private ArrayList<ItemDetail> itemDetails;
private List<Dealer> supplierList;
private ArrayList<SupplierAndItemList> supplierAndItemLists = new ArrayList<>();
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_screen_slide);
dealerObject = getIntent().getParcelableExtra(UiConstants.DEALER_OBJECT);
itemDetails = getIntent().getParcelableArrayListExtra("itemDetails");
supplierList = dealerObject.getParentSalesPoints(this,dealerObject.getServerId());
loadItemsForSuppliers();
mPager = (ViewPager) findViewById(R.id.pager);
mPagerAdapter = new ScreenSlidePagerAdapter(getSupportFragmentManager(),supplierAndItemLists);
mPager.setAdapter(mPagerAdapter);
}
private void loadItemsForSuppliers() {
for (Dealer dealer : supplierList) {
ArrayList<ItemDetail> inventories = new ArrayList<>();
SupplierAndItemList supplierAndItem = new SupplierAndItemList();
supplierAndItem.setDealerName(dealer.getDealerName());
supplierAndItem.setSelectedItemList(getInventoriesByItemDetails(dealer, inventories));
supplierAndItemLists.add(supplierAndItem);
}
}
private ArrayList<ItemDetail> getInventoriesByItemDetails(Dealer dealer, ArrayList<ItemDetail> inventories) {
for (ItemDetail id : itemDetails) {
DealerInventory dealerInventory = new DealerInventory();
dealerInventory = dealerInventory.getLastModifiedInventory(this, id.getItemId(), dealer.getId());
if (dealerInventory != null) {
if (dealerInventory.getQuantity() >= 0) {
id.setParentSalesPointLastStock(String.valueOf(dealerInventory.getQuantity()));
id.setParentSalesPointLastStockTakingDate(dealerInventory.getStockTakingDate());
}
} else {
id.setParentSalesPointLastStock(UiConstants.NA);
id.setParentSalesPointLastStockTakingDate(UiConstants.NA);
}
inventories.add(id);
}
return inventories;
}
private class ScreenSlidePagerAdapter extends FragmentStatePagerAdapter {
private final ArrayList<SupplierAndItemList> supplierAndItemList;
public ScreenSlidePagerAdapter(FragmentManager fm, ArrayList<SupplierAndItemList> supplierAndItemList) {
super(fm);
this.supplierAndItemList = supplierAndItemList;
}
#Override
public Fragment getItem(int position) {
SupplierAndItemList supplierAndItems = supplierAndItemList.get(position);
ScreenSlidePageFragment f = new ScreenSlidePageFragment();
Bundle bundle = new Bundle();
bundle.putParcelableArrayList("supplierAndItems",supplierAndItems.getSelectedItemList());
bundle.putString("supplierName",supplierAndItems.getDealerName());
f.setArguments(bundle);
return f;
}
#Override
public int getCount() {
return supplierAndItemList.size();
}
}
}
SupplierAndItemList class
public class SupplierAndItemList implements Parcelable {
public String dealerName;
public ArrayList<ItemDetail> selectedItemList;
public SupplierAndItemList() {
selectedItemList = new ArrayList<>();
}
public String getDealerName() {
return dealerName;
}
public void setDealerName(String dealerName) {
this.dealerName = dealerName;
}
public ArrayList<ItemDetail> getSelectedItemList() {
return selectedItemList;
}
public void setSelectedItemList(ArrayList<ItemDetail> itemList) {
this.selectedItemList = itemList;
}
protected SupplierAndItemList(Parcel in) {
dealerName = in.readString();
selectedItemList = in.readArrayList(ItemDetail.class.getClassLoader());
}
#Override
public int describeContents() {
return 0;
}
#Override
public void writeToParcel(Parcel dest, int flags) {
dest.writeString(dealerName);
dest.writeList(selectedItemList);
}
#SuppressWarnings("unused")
public static final Parcelable.Creator<SupplierAndItemList> CREATOR = new Parcelable.Creator<SupplierAndItemList>() {
#Override
public SupplierAndItemList createFromParcel(Parcel in) {
return new SupplierAndItemList(in);
}
#Override
public SupplierAndItemList[] newArray(int size) {
return new SupplierAndItemList[size];
}
};
}
ItemDetail class
public class ItemDetail implements Parcelable {
public int itemId;
public String itemName;
public String salesPointLastStock;
public String salesPointLastStockTakingDate;
public String parentSalesPointLastStock;
public String parentSalesPointLastStockTakingDate;
public IDStockInput idStockInput;
public IDReturnInput idReturnInput;
public IDOrderInput idOrderInput;
public boolean isSelected;
public boolean isSelected() {
return isSelected;
}
public void setIsSelected(boolean isUpdated) {
this.isSelected = isUpdated;
}
public String getParentSalesPointLastStockTakingDate() {
return parentSalesPointLastStockTakingDate;
}
public void setParentSalesPointLastStockTakingDate(String parentSalesPointLastStockTakingDate) {
this.parentSalesPointLastStockTakingDate = parentSalesPointLastStockTakingDate;
}
public String getParentSalesPointLastStock() {
return parentSalesPointLastStock;
}
public void setParentSalesPointLastStock(String parentSalesPointLastStock) {
this.parentSalesPointLastStock = parentSalesPointLastStock;
}
#NonNull
public int getItemId() {
return itemId;
}
public void setItemId(int itemId) {
this.itemId = itemId;
}
#NonNull
public String getItemName() {
return itemName;
}
public void setItemName(String itemName) {
this.itemName = itemName;
}
#NonNull
public String getSalesPointLastStock() {
return salesPointLastStock;
}
public void setSalesPointLastStock(String salesPointLastStock) {
this.salesPointLastStock = salesPointLastStock;
}
#NonNull
public String getSalesPointLastStockTakingDate() {
return salesPointLastStockTakingDate;
}
public void setSalesPointLastStockTakingDate(String salesPointLastStockTakingDate) {
this.salesPointLastStockTakingDate = salesPointLastStockTakingDate;
}
public IDStockInput getIdStockInput() {
return idStockInput;
}
public void setIdStockInput(IDStockInput idStockInput) {
this.idStockInput = idStockInput;
}
public IDReturnInput getIdReturnInput() {
return idReturnInput;
}
public void setIdReturnInput(IDReturnInput idReturnInput) {
this.idReturnInput = idReturnInput;
}
public IDOrderInput getIdOrderInput() {
return idOrderInput;
}
public void setIdOrderInput(IDOrderInput idOrderInput) {
this.idOrderInput = idOrderInput;
}
public ItemDetail() {
idStockInput = new IDStockInput();
idReturnInput = new IDReturnInput();
idOrderInput = new IDOrderInput();
}
protected ItemDetail(Parcel in) {
itemId = in.readInt();
itemName = in.readString();
salesPointLastStock = in.readString();
salesPointLastStockTakingDate = in.readString();
parentSalesPointLastStock = in.readString();
parentSalesPointLastStockTakingDate = in.readString();
isSelected =in.readInt()==1;
idStockInput = (IDStockInput) in.readValue(IDStockInput.class.getClassLoader());
idReturnInput = (IDReturnInput) in.readValue(IDReturnInput.class.getClassLoader());
idOrderInput = (IDOrderInput) in.readValue(IDOrderInput.class.getClassLoader());
}
#Override
public int describeContents() {
return 0;
}
#Override
public void writeToParcel(Parcel dest, int flags) {
dest.writeInt(itemId);
dest.writeString(itemName);
dest.writeString(salesPointLastStock);
dest.writeString(salesPointLastStockTakingDate);
dest.writeString(parentSalesPointLastStock);
dest.writeString(parentSalesPointLastStockTakingDate);
dest.writeInt(isSelected ? 1 : 0);
dest.writeValue(idStockInput);
dest.writeValue(idReturnInput);
dest.writeValue(idOrderInput);
}
#SuppressWarnings("unused")
public static final Parcelable.Creator<ItemDetail> CREATOR = new Parcelable.Creator<ItemDetail>() {
#Override
public ItemDetail createFromParcel(Parcel in) {
return new ItemDetail(in);
}
#Override
public ItemDetail[] newArray(int size) {
return new ItemDetail[size];
}
};
}
I have go through your method I have found some assigning value issue
private void loadItemsForSuppliers() {
for (Dealer dealer : supplierList) {
ArrayList<ItemDetail> inventories = new ArrayList<>();
SupplierAndItemList supplierAndItem = new SupplierAndItemList();
supplierAndItem.setDealerName(dealer.getDealerName());
supplierAndItem.setSelectedItemList(getInventoriesByItemDetails(dealer, inventories));
supplierAndItemLists.add(supplierAndItem);
}
}
private ArrayList<ItemDetail> getInventoriesByItemDetails(Dealer dealer, ArrayList<ItemDetail> inventories) {
for (ItemDetail id : itemDetails) {
DealerInventory dealerInventory = new DealerInventory();
dealerInventory = dealerInventory.getLastModifiedInventory(this, id.getItemId(), dealer.getId());
if (dealerInventory != null) {
if (dealerInventory.getQuantity() >= 0) {
id.setParentSalesPointLastStock(String.valueOf(dealerInventory.getQuantity()));
id.setParentSalesPointLastStockTakingDate(dealerInventory.getStockTakingDate());
}
} else {
id.setParentSalesPointLastStock(UiConstants.NA);
id.setParentSalesPointLastStockTakingDate(UiConstants.NA);
}
inventories.add(id); // do this
}
return inventories; // you are not assigning value anywhere;
}
You are not assigning value to the inventories in getInventoriesByItemDetails. I think you should add item through inventories.add(id);
Check it , Hope this help
Set
mPager.setOffscreenPageLimit(1);