Hi Im trying to show a list from retrofit onResponse and I am using recyclerview inside a fragment. The list shoud show chefs but I got an error from RecyclerView
Conexion Class
public class Conexion {
public static String BASE_URL = "http://10.30.0.133:8091/Service1.asmx/";
private static Retrofit retrofit = null;
public static Retrofit getClient() {
if (retrofit==null) {
retrofit = new Retrofit.Builder()
.baseUrl(BASE_URL)
.addConverterFactory(GsonConverterFactory.create())
.build();
}
return retrofit;
}
}
EndPoint Interface
public interface EndPointsInterface {
#GET("chef/{idUser}")
Call<ChefResponse> GetChefsCercanos(#Path("idUser") Integer id_usuario);
}
Entity Usuario
public class Usuario {
#SerializedName("id_usuario")
private Integer id_usuario;
#SerializedName("NombreUsuario")
private String NombreUsuario;
#SerializedName("ApellidoUsuario")
private String ApellidoUsuario;
#SerializedName("TelefonoUsuario")
private String TelefonoUsuario;
#SerializedName("Email")
private String Email;
#SerializedName("Contraseña")
private String Contraseña;
#SerializedName("pos_x")
private Double pos_x;
#SerializedName("pos_y")
private Double pos_y;
public Usuario(){}
public Usuario(Integer id_usuario,String NombreUsuario,String ApellidoUsuario,String TelefonoUsuario,String Email,String Contraseña,Double pos_x,Double pos_y){
this.id_usuario=id_usuario;
this.NombreUsuario=NombreUsuario;
this.ApellidoUsuario=ApellidoUsuario;
this.TelefonoUsuario=TelefonoUsuario;
this.Contraseña=Contraseña;
this.pos_x=pos_x;
this.pos_y=pos_y;
}
public Integer getId_usuario() {
return id_usuario;
}
public void setId_usuario(Integer id_usuario) {
this.id_usuario = id_usuario;
}
public String getNombreUsuario() {
return NombreUsuario;
}
public void setNombreUsuario(String nombreUsuario) {
NombreUsuario = nombreUsuario;
}
public String getApellidoUsuario() {
return ApellidoUsuario;
}
public void setApellidoUsuario(String apellidoUsuario) {
ApellidoUsuario = apellidoUsuario;
}
public String getTelefonoUsuario() {
return TelefonoUsuario;
}
public void setTelefonoUsuario(String telefonoUsuario) {
TelefonoUsuario = telefonoUsuario;
}
public String getEmail() {
return Email;
}
public void setEmail(String email) {
Email = email;
}
public String getContraseña() {
return Contraseña;
}
public void setContraseña(String contraseña) {
Contraseña = contraseña;
}
public Double getPos_x() {
return pos_x;
}
public void setPos_x(Double pos_x) {
this.pos_x = pos_x;
}
public Double getPos_y() {
return pos_y;
}
public void setPos_y(Double pos_y) {
this.pos_y = pos_y;
}
}
Entity Chef
public class Chef extends Usuario{
#SerializedName("id_chef")
private Integer id_chef;
#SerializedName("TipoServicio")
private String TipoServicio;
#SerializedName("Rating")
private Double Rating;
#SerializedName("EstadoChef")
private Boolean EstadoChef;
public Chef(){}
public Chef(Integer id_usuario,String NombreUsuario,String ApellidoUsuario,String TelefonoUsuario,String Email,String Contraseña,Double pos_x,Double pos_y,Integer id_chef,String TipoServicio,Double Rating,Boolean EstadoChef){
super(id_usuario,NombreUsuario,ApellidoUsuario,TelefonoUsuario,Email,Contraseña,pos_x,pos_y);
this.id_chef=id_chef;
this.TipoServicio=TipoServicio;
this.Rating=Rating;
this.EstadoChef=EstadoChef;
}
public Integer getId_chef() {
return id_chef;
}
public void setId_chef(Integer id_chef) {
this.id_chef = id_chef;
}
public String getTipoServicio() {
return TipoServicio;
}
public void setTipoServicio(String tipoServicio) {
TipoServicio = tipoServicio;
}
public Double getRating() {
return Rating;
}
public void setRating(Double rating) {
Rating = rating;
}
public Boolean getEstadoChef() {
return EstadoChef;
}
public void setEstadoChef(Boolean estadoChef) {
EstadoChef = estadoChef;
}
}
Chef Response
public class ChefResponse {
#SerializedName("results")
private Chef[] results;
public Chef[] getresults(){
return results;
}
}
RecyclerView Adapter
public class ListaChefsCercanos extends RecyclerView.Adapter<ListaChefsCercanos.ListaChefsCercanosViewHolder> {
private List<Chef> chefs;
private List<Usuario> usuarios;
private int rowLayout;
private Context context;
#Override
public ListaChefsCercanosViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View view = LayoutInflater.from(parent.getContext()).inflate(rowLayout, parent, false);
return new ListaChefsCercanosViewHolder(view);
}
#Override
public void onBindViewHolder(ListaChefsCercanosViewHolder holder, int position) {
holder.nombreschefscerca.setText(chefs.get(position).getNombreUsuario());
holder.ratingchef.setText(chefs.get(position).getRating().toString());
}
#Override
public int getItemCount() {
return chefs.size();
}
public static class ListaChefsCercanosViewHolder extends RecyclerView.ViewHolder{
LinearLayout chefslayout;
TextView nombreschefscerca;
TextView ratingchef;
public ListaChefsCercanosViewHolder(View v){
super(v);
chefslayout=(LinearLayout) v.findViewById(R.id.cheflayoutcerca);
nombreschefscerca=(TextView) v.findViewById(R.id.tv_NombreChefCercano);
ratingchef=(TextView) v.findViewById(R.id.tv_RatingChefCercano);
}
}
public ListaChefsCercanos(ArrayList <Chef> chefs){
this.chefs=chefs;
//this.rowLayout = rowLayout;
//this.context = context;
}
}
and the fragment
public class RecomendadosFragment extends Fragment {
private RatingBar ratingBar;
//ListAdapter adapter;
ArrayList<Chef> listachef;
ListView lvLista;
String tag_json_array="jarray req";
RecyclerView recyclerviewChefsCarnos;
ListaChefsCercanos mListaChefsCercanos;
private ArrayList<Chef> data;
private ListaChefsCercanos adapter;
#Nullable
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View x = inflater.inflate(R.layout.recomendados,null);
//ratingBar = (RatingBar) x.findViewById(R.id.rb_RatingChefCercano);
recyclerviewChefsCarnos=(RecyclerView) x.findViewById(R.id.rv_chefsCernaos);
recyclerviewChefsCarnos.setLayoutManager(new LinearLayoutManager(getActivity().getApplicationContext()));
EndPointsInterface apiService = Conexion.getClient().create(EndPointsInterface.class);
Call<ChefResponse> call = apiService.GetChefsCercanos(5);
call.enqueue(new Callback<ChefResponse>() {
#Override
public void onResponse(Call<ChefResponse> call, Response<ChefResponse> response) {
int statusCode = response.code();
if (response.isSuccessful()) {
ChefResponse jsonResponse = response.body();
if(jsonResponse != null) {
data = new ArrayList<>(Arrays.asList(jsonResponse.getresults()));
adapter= new ListaChefsCercanos(data);
recyclerviewChefsCarnos.setAdapter(adapter);
}
} else {
// Do whatever you want if API is unsuccessful.
}
// List<Chef> chefs= response.body().getResults();
// recyclerviewChefsCarnos.setAdapter(new ListaChefsCercanos( chefs,R.layout.itemchefscercanos,getActivity().getApplicationContext()));
}
#Override
public void onFailure(Call<ChefResponse> call, Throwable t) {
Log.d("Error",t.getMessage());
}
});
return x;
}
this is the error I found while Im debuging
E/RecyclerView: No adapter attached; skipping layout
Update: Use a empty adapter for the RecyclerView in the OncreateView()
recyclerView.setAdapter(new YourAdapter(getCurrentActivity()));
Related
I'm stuck somewhere in between getting json array inside a object setting it to recylerview, I have to send a key to fetch data and getting response in json array inside a object. Didn't understand solutions got here, so I'm here if Somebody can help mre understand.
////Main class
public class today_doctors extends AppCompatActivity {
viewModel_doc listViewModel;
List<model_doc> datalist;
todayDoctorAdapter adapter;
TextView clinic_name;
RecyclerView recview;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_today_doctors);
recview=findViewById(R.id.rv);
recview.setLayoutManager(new LinearLayoutManager(this));
recview.addItemDecoration(new DividerItemDecoration(this, 0));
adapter=new todayDoctorAdapter(datalist);
recview.setAdapter(adapter);
clinic_name=findViewById(R.id.tvDrName);
process();
}
public void process(){
listViewModel= new ViewModelProvider(this).get(viewModel_doc.class);
listViewModel.getDatalistObserver ().observe(this, new Observer<List<model_doc>>() {
#Override
public void onChanged(List<model_doc> Models) {
if(Models!=null) {
datalist= Models;
adapter.updateList(Models);
}
else
{
recview.setVisibility(View.GONE);
Toast.makeText(today_doctors.this, "No data recieved", Toast.LENGTH_SHORT).show();
}
}
});
listViewModel.makeApiCall();
}
//////////Viewmodel class
public class viewModel_doc extends ViewModel
{
private MutableLiveData<List<model_doc>> datalist2;
public viewModel_doc(){
datalist2=new MutableLiveData<>();
}
public MutableLiveData<List<model_doc>> getDatalistObserver()
{
return datalist2;
}
public void makeApiCall()
{
apiSet apiServices= apiController.getInstance().getApi();
Call<List<model_doc>> calldoc=apiServices.getList2("ll0004");
calldoc.enqueue(new Callback<List<model_doc>>() {
#Override
public void onResponse(Call<List<model_doc>> call, Response<List<model_doc>> response) {
datalist2.postValue(response.body());
}
#Override
public void onFailure(Call<List<model_doc>> call, Throwable t) {
datalist2.postValue(null);
Log.e("Error :",t.getMessage());
}
});
}
}
///////////////////main model
public class model_doc {
String status,msg;
ArrayList<Data> data;
public model_doc(String status, String msg, ArrayList<Data> data) {
this.status = status;
this.msg = msg;
this.data = data;
}
public String getStatus() {
return status;
}
public String getMsg() {
return msg;
}
public ArrayList<Data> getData() {
return data;
}
public static class Data {
String doctor_id;
String doctor_name;
String proposed_date;
String date;
// Getters setters
public Data(String doctor_id, String doctor_name, String proposed_date, String date) {
this.doctor_id = doctor_id;
this.doctor_name = doctor_name;
this.proposed_date = proposed_date;
this.date = date;
}
public String getDoctor_id() {
return doctor_id;
}
public String getDoctor_name() {
return doctor_name;
}
public String getProposed_date() {
return proposed_date;
}
public String getDate() {
return date;
}
}
}
////api interface
#FormUrlEncoded
#POST("doctor_list")
Call<List<model_doc>>getList2(
#Field("clinic_id") String clinic_id
);
//////////////////controller
public class apiController {
private static final String url="https://xyz.in/api/";
private static apiController clientObject;
private static Retrofit retrofit;
apiController()
{
retrofit=new Retrofit.Builder()
.baseUrl(url)
.addConverterFactory(GsonConverterFactory.create())
.build();
}
public static synchronized apiController getInstance(){
if(clientObject==null)
clientObject=new apiController();
return clientObject;
}
public apiSet getApi(){
return retrofit.create(apiSet.class);
}
}
////////////recycler adapter, made some changes in main model for nested data could handle it to adapter
public class todayDoctorAdapter extends RecyclerView.Adapter<todayDoctorAdapter.viewholder>
{
List<model_doc> datalist2;
public todayDoctorAdapter(List<model_doc> list){
this.datalist2=list;}
public void updateList(List<model_doc>list){
this.datalist2=list;
notifyDataSetChanged();
}
#NonNull
#Override
public todayDoctorAdapter.viewholder onCreateViewHolder(#NonNull ViewGroup parent, int viewType){
View view= LayoutInflater.from(parent.getContext()).inflate(R.layout.list_item_doctors,parent,false);
return new todayDoctorAdapter.viewholder(view);
}
#Override
public void onBindViewHolder(#NonNull todayDoctorAdapter.viewholder holder, int position){
holder.doctor_name.setText(String.format("Dr.%s", datalist2.get(position).getDoctor_app()));
holder.proposed_date.setText(String.format("Apt: %s","TODAY"));
String doc=datalist2.get(position).getDoctor_app();
holder.cv.setOnClickListener(
new View.OnClickListener(){
#Override
public void onClick(View arg0) {
Intent intent = new Intent(arg0.getContext(), PatientsUnderDoctor.class);
intent.putExtra("doc_name", doc);
arg0.getContext().startActivity(intent);
}
});
}
#Override
public int getItemCount(){
if (this.datalist2!=null){
return this.datalist2.size();
}
return 0;
}
public static class viewholder extends RecyclerView.ViewHolder{
TextView doctor_name,proposed_date;
CardView cv;
public viewholder(#NonNull View itemView) {
super(itemView);
doctor_name=itemView.findViewById(R.id.drName);
proposed_date=itemView.findViewById(R.id.apptDate);
cv=itemView.findViewById(R.id.cv_patient);
}
}
}
//////////////////json data look like this
{
"status": "success",
"msg": "Found",
"data": [
{
"doc_code": "jhjh0001",
"app_date": "2022-09-13",
"doc_name": "kjk",
"count": 1
}
]
}
I am using Android Paging with Room Database.I am going to fetch data using retrofit.But I am getting error No adapter attached; skipping layout.I searched a lot but dont find solution for this. Base url is working, for security reason i just hide base url.
private StoreAdapter storeAdapter;
private Store_ViewModel store_viewModel;
private RecyclerView recyclerView;
private static final String URL_DATA="https://xxxx/";
//insertion
private Store_Repository store_repository;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
store_repository=new Store_Repository(getApplication());
//adapter
storeAdapter=new StoreAdapter(getApplicationContext(), this);
//recycler
recyclerView=findViewById(R.id.recycler_store);
RecyclerView.LayoutManager layoutManager = new LinearLayoutManager(getApplicationContext());
recyclerView.setLayoutManager(layoutManager);
recyclerView.setHasFixedSize(true);
store_viewModel=new ViewModelProvider(this).get(Store_ViewModel.class);
store_viewModel.pagedListLiveData.observe(this, new Observer<PagedList<StoreModel>>() {
#Override
public void onChanged(PagedList<StoreModel> storeModels) {
storeAdapter.submitList(storeModels);
recyclerView.setAdapter(storeAdapter);
}
});
getAllProducts();
}
private void getAllProducts() {
Retrofit retrofit=new Retrofit.Builder()
.baseUrl(URL_DATA)
.addConverterFactory(GsonConverterFactory.create())
.build();
//calling api
Api api=retrofit.create(Api.class);
Call<List<StoreModel>>call=api.getAllProducts();
call.enqueue(new Callback<List<StoreModel>>() {
#Override
public void onResponse(Call<List<StoreModel>> call, Response<List<StoreModel>> response) {
if (response.isSuccessful())
{
store_repository.insert(response.body());
}
}
#Override
public void onFailure(Call<List<StoreModel>> call, Throwable t) {
Toast.makeText(MainActivity.this, "Something get Wrong", Toast.LENGTH_SHORT).show();
}
});
}
This is my ViewModel Class
public class Store_ViewModel extends AndroidViewModel {
public LiveData<PagedList<StoreModel>>pagedListLiveData;
private StoreDao storeDao;
public Store_ViewModel(#NonNull Application application) {
super(application);
storeDao= StoreDatabase.getINSTANCE(application).storeDao();
pagedListLiveData=new LivePagedListBuilder<>(
storeDao.getAllItems(),5
).build();
}
}
And this is my adapter class
public class StoreAdapter extends PagedListAdapter<StoreModel,StoreAdapter.StoreViewHolder> {
private Context context;
private static Listener listener;
public StoreAdapter(Context context,Listener listener)
{
super(storeModelItemCallback);
this.context=context;
this.listener=listener;
}
#NonNull
#Override
public StoreViewHolder onCreateViewHolder(#NonNull ViewGroup parent, int viewType) {
return null;
}
#Override
public void onBindViewHolder(#NonNull StoreViewHolder holder, int position) {
StoreModel storeModel=getItem(position);
holder.Product_name.setText(storeModel.getProduct_name());
holder.Product_weight.setText(storeModel.getProduct_weight());
holder.Price.setText(storeModel.getPrice());
holder.Mrp.setText(storeModel.getMrp());
}
static class StoreViewHolder extends RecyclerView.ViewHolder
{
TextView Product_name;
TextView Product_weight;
TextView Price;
TextView Mrp;
public StoreViewHolder(#NonNull View itemView) {
super(itemView);
Product_name=itemView.findViewById(R.id.product_name);
Product_weight=itemView.findViewById(R.id.product_weight);
Price=itemView.findViewById(R.id.price);
Mrp=itemView.findViewById(R.id.mrp);
//listener
itemView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
listener.onItemCLickListener(getAdapterPosition());
}
});
}
}
static DiffUtil.ItemCallback<StoreModel> storeModelItemCallback=new DiffUtil.ItemCallback<StoreModel>() {
#Override
public boolean areItemsTheSame(#NonNull StoreModel oldItem, #NonNull StoreModel newItem) {
return oldItem.getDatabase_id()==newItem.getDatabase_id();
}
#SuppressLint("DiffUtilEquals")
#Override
public boolean areContentsTheSame(#NonNull StoreModel oldItem, #NonNull StoreModel newItem) {
return oldItem.equals(newItem);
}
};
Json Response from Server
{"status":1,"msg":"",
"paginate":{"limit":1000,"PageNo":1},
"data":
[
{
"product_id":23234,
"product_brand_id":130,
"product_name":"Xyz"
,"product_code":"1554729666482",
"mrp":5,
"price":4,
"product_weight":1,
"product_weight_unit":"PCS"
}
,{"product_id":23244,
"product_brand_id":130,
"product_name":"Abc - 100 Gms",
"product_code":"9A","mrp":38,"price":31.94,
"product_weight":100,"product_weight_unit":"GM"}
ApiInterface
public interface Api {
#GET("/get-products")
Call<List<StoreModel>>getAllProducts();
}
Below is my StoreModel in which i am using room database fro creating tables
#Entity(tableName = "store",indices = #Index(value="product_id",unique = true))
public class StoreModel {
#PrimaryKey(autoGenerate = true)
private int database_id;
#SerializedName("product_id")
private int product_id;
#SerializedName("product_brand_id")
private int product_brand_id;
#SerializedName("product_name")
private String product_name;
#SerializedName("product_code")
private int product_code;
#SerializedName("mrp")
private int mrp;
#SerializedName("price")
private int price;
#SerializedName("product_weight")
private int product_weight;
#SerializedName("product_weight_unit")
private String product_weight_unit;
public StoreModel() {
}
public StoreModel(int product_id, int product_brand_id, String product_name, int product_code, int mrp, int price, int product_weight, String product_weight_unit) {
this.product_id = product_id;
this.product_brand_id = product_brand_id;
this.product_name = product_name;
this.product_code = product_code;
this.mrp = mrp;
this.price = price;
this.product_weight = product_weight;
this.product_weight_unit = product_weight_unit;
}
public int getProduct_id() {
return product_id;
}
public void setProduct_id(int product_id) {
this.product_id = product_id;
}
public int getProduct_brand_id() {
return product_brand_id;
}
public void setProduct_brand_id(int product_brand_id) {
this.product_brand_id = product_brand_id;
}
public String getProduct_name() {
return product_name;
}
public void setProduct_name(String product_name) {
this.product_name = product_name;
}
public int getProduct_code() {
return product_code;
}
public void setProduct_code(int product_code) {
this.product_code = product_code;
}
public int getMrp() {
return mrp;
}
public void setMrp(int mrp) {
this.mrp = mrp;
}
public int getPrice() {
return price;
}
public void setPrice(int price) {
this.price = price;
}
public int getProduct_weight() {
return product_weight;
}
public void setProduct_weight(int product_weight) {
this.product_weight = product_weight;
}
public String getProduct_weight_unit() {
return product_weight_unit;
}
public void setProduct_weight_unit(String product_weight_unit) {
this.product_weight_unit = product_weight_unit;
}
public int getDatabase_id() {
return database_id;
}
public void setDatabase_id(int database_id) {
this.database_id = database_id;
}
}
Below is Dao class
#Dao
public interface StoreDao {
#Insert(onConflict = OnConflictStrategy.REPLACE)
void insert(List<StoreModel> storeModels);
#Query("DELETE FROM store")
void deleteAll();
#Query("SELECT * FROM store ORDER BY database_id ASC")
DataSource.Factory<Integer,StoreModel>getAllItems();
}
Set recyclerView.setAdapter(storeAdapter); outside of observer because each time data is observed it will set adapter. So, adapter is attached to recyclerView only once. Like
recyclerView.setAdapter(storeAdapter);
store_viewModel.pagedListLiveData.observe(this, new Observer<PagedList<StoreModel>>() {
#Override
public void onChanged(PagedList<StoreModel> storeModels) {
storeAdapter.submitList(storeModels);
//recyclerView.setAdapter(storeAdapter);
}
});
From the API you are not getting exactly the StoreModel as response. You are getting another object which is StoreModel is a child object. You have to create resposne object like below:
public class ResponseObject{
//#SerializedName("status")
//private int status;
#SerializedName("data")
private List<StoreModel> storeModelList;
//getters and setters goes here
}
And then your interface should be like below as you are expecting
ResponseObject here
public interface Api {
#GET("/get-products")
Call<ResponseObject> getAllProducts();
}
Those are categories and subcategories. There can be subcategory or not.
JsonCode to be used is as below.
categoryId is what will change to call subcategories.
E.g. If you want to see subcategories of cars
Json Code
[{"Id":1,"TitleEN":"Cars","TitleAR":"سيارات","Photo":"http://souq.hardtask.co//Files/CategoryPhotos/ce686544-9f51-4213-b5db-7c015b788e8d.png","ProductCount":"3","HaveModel":"0","SubCategories":[{"Id":6,"TitleEN":"Cat6","TitleAR":"قسم6","Photo":"http://souq.hardtask.co//Files/CategoryPhotos/ce686544-9f51-4213-b5db-7c015b788e8d.png","ProductCount":"3","HaveModel":"0","SubCategories":[]}]},{"Id":2,"TitleEN":"Cat2","TitleAR":"قسم2","Photo":"http://souq.hardtask.co//Images/no_image.png","ProductCount":"8","HaveModel":"0","SubCategories":[{"Id":13,"TitleEN":"cat1 -1 ","TitleAR":"cat1 - 1","Photo":"http://souq.hardtask.co//Images/no_image.png","ProductCount":"8","HaveModel":"0","SubCategories":[]}]},{"Id":3,"TitleEN":"Cat3","TitleAR":"قسم3","Photo":"http://souq.hardtask.co//Images/no_image.png","ProductCount":"2","HaveModel":"0","SubCategories":[]},{"Id":4,"TitleEN":"Cat4","TitleAR":"قسم4","Photo":"http://souq.hardtask.co//Images/no_image.png","ProductCount":"1","HaveModel":"0","SubCategories":[]},{"Id":5,"TitleEN":"Cat5","TitleAR":"قسم5","Photo":"http://souq.hardtask.co//Images/no_image.png","ProductCount":"0","HaveModel":"0","SubCategories":[]},{"Id":8,"TitleEN":"Cat8","TitleAR":"قسم8","Photo":"http://souq.hardtask.co//Images/no_image.png","ProductCount":"0","HaveModel":"0","SubCategories":[]},{"Id":9,"TitleEN":"Slide01","TitleAR":"Slide02","Photo":"http://souq.hardtask.co//Files/CategoryPhotos/2ba07cb2-49a0-47e4-aba6-ef10a916fb12.png","ProductCount":"0","HaveModel":"0","SubCategories":[]}]
ImageAdapter
public class ImageAdapter extends BaseAdapter {
private Context mContext;
public ImageAdapter(Context c){
mContext = c;
}
#Override
public int getCount(){
return images.size();
}
#Override
public Object getItem(int position){
return images.get(position);
}
public long getItemId(int position){
return 0;
}
public View getView(int position, View convertView, ViewGroup parent){
ImageView imageview;
if (convertView == null){
imageview = new ImageView(mContext);
imageview.setPadding(0, 0, 0, 0);
//imageview.setLayoutParams(new GridLayout.MarginLayoutParams(ViewGroup.LayoutParams.FILL_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT));
imageview.setScaleType(ImageView.ScaleType.CENTER_INSIDE);
imageview.setAdjustViewBounds(true);
} else {
imageview = (ImageView) convertView;
}
Picasso.with(mContext).load(images.get(position)).placeholder(R.mipmap.ic_launcher).into(imageview);
return imageview;
}
/*
Custom methods
*/
public void addItem(String url){
images.add(url);
}
public void clearItems() {
images.clear();
}
public ArrayList<String> images = new ArrayList<String>();
}
Movie Model
public class Movie implements Parcelable {
public String TitleEN;
public String TitleAR;
public String Photo;
public int id;
public Movie(){
}
protected Movie(Parcel in) {
TitleEN = in.readString();
TitleAR = in.readString();
Photo = in.readString();
id = in.readInt();
}
#Override
public int describeContents() {
return 0;
}
#Override
public void writeToParcel(Parcel dest, int flags) {
dest.writeString(TitleEN);
dest.writeString(TitleAR);
dest.writeString(Photo);
dest.writeInt(id);
}
#SuppressWarnings("unused")
public static final Parcelable.Creator<Movie> CREATOR = new Parcelable.Creator<Movie>() {
#Override
public Movie createFromParcel(Parcel in) {
return new Movie(in);
}
#Override
public Movie[] newArray(int size) {
return new Movie[size];
}
};
}
Fragament_main
public class Fragament_main extends Fragment {
public View mainFragmentView;
public String LOG_TAG = "ShowcaseFragment";
public ArrayList<Movie> movies = new ArrayList<Movie>();
private RequestQueue mRequestQueue;
public ImageAdapter imageAdapter;
public static Fragament_main instance;
GridView gridview;
public boolean isDualPane = false;
// static to preserve sorting over orientation changes (activity restart)
public static String sortOrder = "popularity.desc", moreParams = "";
public static boolean setting_cached = false;
public int gridPos = -1;
public Fragament_main() {
// Required empty public constructor
instance = this;
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
mainFragmentView = inflater.inflate(R.layout.fragment_main, container, false);
mRequestQueue = Volley.newRequestQueue(getContext());
// setup adapters
imageAdapter = new ImageAdapter(getContext());
gridview = (GridView) mainFragmentView.findViewById(R.id.gridView);
gridview.setAdapter(imageAdapter);
//updateUI(setting_cached);
//gridview.setOnItemClickListener(new GridClickListener());
// manage grid col count wrt Orientation
if (this.getResources().getConfiguration().orientation == Configuration.ORIENTATION_LANDSCAPE)
setGridColCount(3);
else
setGridColCount(2);
return mainFragmentView;
}
#Override
public void onActivityCreated(Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
}
#Override
public void onSaveInstanceState(Bundle outState) {
super.onSaveInstanceState(outState);
outState.putInt("GRIDVIEW_POSITION", gridview.getFirstVisiblePosition());
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
if (savedInstanceState != null)
gridPos = savedInstanceState.getInt("GRIDVIEW_POSITION");
}
#Override
public void onDestroyView() {
super.onDestroyView();
mRequestQueue.cancelAll(new RequestQueue.RequestFilter() {
#Override
public boolean apply(Request<?> request) {
return true;
}
});
}
/*class GridClickListener implements AdapterView.OnItemClickListener {
#Override
public void onItemClick(AdapterView<?> adapterView, View view, int position, long id) {
if (isDualPane){
android.support.v4.app.FragmentTransaction ft = getActivity().getSupportFragmentManager().beginTransaction();
DetailActivityFragment detailActivityFragment = DetailActivityFragment.newInstance(movies.get(position));
ft.replace(R.id.detailContainer, detailActivityFragment);
ft.commit();
} else {
Intent intent = new Intent(getContext(), DetailActivity.class);
intent.putExtra(Intent.EXTRA_TEXT, (Parcelable) movies.get(position));
startActivity(intent);
}
}
}*/
/* public void updateUI(boolean cached){
movies.clear();
imageAdapter.clearItems();
setting_cached = cached;
if (!cached)
getMovies(sortOrder, moreParams);
else
getFavorites();
}
*/
public void getMovies(String sortOrder, String moreParams){
String url = "http://souq.hardtask.co/app/app.asmx/GetCategories?categoryId=0&countryId=1";
JsonObjectRequest req = new JsonObjectRequest(url, null,
new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject response) {
try {
JSONArray items = response.getJSONArray("results");
JSONObject movieObj;
for (int i=0; i<items.length(); i++){
movieObj = items.getJSONObject(i);
Movie movie = new Movie();
movie.id = movieObj.getInt("id");
movie.TitleEN = movieObj.getString("original_title");
movie.TitleAR = movieObj.getString("overview");
movie.Photo = "http://souq.hardtask.co/app/app.asmx/GetCategories?categoryId=0&countryId=1" + movieObj.getString("poster_path");
movies.add(movie);
// Add image to adapter
imageAdapter.addItem(movie.Photo);
}
} catch (JSONException e){
e.printStackTrace();
}
getActivity().runOnUiThread(new Runnable() {
#Override
public void run() {
gridview.setAdapter(imageAdapter);
if (gridPos > -1)
gridview.setSelection(gridPos);
gridPos = -1;
}
});
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Log.d(LOG_TAG, "Error in JSON Parsing");
}
});
mRequestQueue.add(req);
}
/* public void getFavorites(){
movies.addAll((new MoviesDB()).getFavoriteMovies(getContext().getContentResolver()));
for (Movie movie : movies){
imageAdapter.addItem(movie.Photo);
}
gridview.setAdapter(imageAdapter);
if (gridPos > -1)
gridview.setSelection(gridPos);
gridPos = -1;
}*/
public void updateFavoritesGrid(){
if (setting_cached) {
int p = gridview.getLastVisiblePosition();
///updateUI(true);
gridview.smoothScrollToPosition(p);
}
}
public void setGridColCount(int n){
((GridView) mainFragmentView.findViewById(R.id.gridView)).setNumColumns(n);
}
}
I don't know how to add Json data into GridView.
Could you help me?
Go through this example to view images in grid,
Convert your jsonArray into an ArrayList by using,
ArrayList<Cars> carsList = new Gson().fromJson(jsonArrayYouHave.toString(),new TypeToken<List<Cars>>() {
}.getType());
Pass this Array to your Adapter.
Use this POJO,
public class Cars {
private String TitleAR;
private String HaveModel;
private String TitleEN;
private String Id;
private ArrayList<SubCategories> SubCategories;
private String Photo;
private String ProductCount;
//Todo please add getter/setters for class Cars variables here
public class SubCategories {
private String TitleAR;
private String HaveModel;
private String TitleEN;
private String Id;
private ArrayList<String> SubCategories;
private String Photo;
private String ProductCount;
//Todo please add getter/setters for class SubCategories variables here
}
I'll suggest to use Retrofit as it'll provide you parsed arraylist which is converted into Response POJO you have provided. You can find many examples for Retrofit.
Step 1
Add the following dependencies in your app level gradle file.Dependencies are for retrofit, gsonConvertor butterknife and glide.
implementation 'com.squareup.retrofit2:retrofit:2.1.0'
implementation 'com.google.code.gson:gson:2.6.2'
implementation 'com.squareup.retrofit2:converter-gson:2.1.0'
implementation('com.squareup.retrofit2:retrofit:2.1.0') {
// exclude Retrofit’s OkHttp dependency module and define your own module import
exclude module: 'okhttp'
}
implementation 'com.google.code.gson:gson:2.6.2'
implementation 'com.squareup.retrofit2:converter-gson:2.1.0'
implementation 'com.squareup.okhttp3:logging-interceptor:3.4.1'
implementation 'com.squareup.okhttp3:okhttp:3.4.1'
implementation 'com.android.support:design:28.0.0'
implementation 'com.android.support:recyclerview-v7:28.0.0'
implementation "com.jakewharton:butterknife:$BUTTER_KNIFE_VERSION"
annotationProcessor "com.jakewharton:butterknife-compiler:$BUTTER_KNIFE_VERSION"
implementation 'com.github.bumptech.glide:glide:4.8.0'
annotationProcessor 'com.github.bumptech.glide:compiler:4.8.0'
Step 2 Create a class by name ApiClient and paste the following code in this class
public class ApiClient {
private static Retrofit retrofit = null;
public static Retrofit getRetrofit() {
HttpLoggingInterceptor interceptor = new HttpLoggingInterceptor();
interceptor.setLevel(HttpLoggingInterceptor.Level.BODY);
OkHttpClient client = new OkHttpClient.Builder().addInterceptor(interceptor).build();
retrofit = new Retrofit.Builder()
.baseUrl("http://souq.hardtask.co")
.addConverterFactory(GsonConverterFactory.create())
.client(client)
.build();
return retrofit;
}
}
Step 3 Create a new Interface class by name APIInterface and paste the following code in this class
#GET("/app/app.asmx/GetCategories")
Call<List<Product>> getProducts(#QueryMap Map<String, String> params);
Step 4 Create POJO classes according to json response. We have two classes Products and their subcategory.So I am creating first class by name Product
public class Product {
#SerializedName("Id")
#Expose
private Integer id;
#SerializedName("TitleEN")
#Expose
private String titleEN;
#SerializedName("TitleAR")
#Expose
private String titleAR;
#SerializedName("Photo")
#Expose
private String photo;
#SerializedName("ProductCount")
#Expose
private String productCount;
#SerializedName("HaveModel")
#Expose
private String haveModel;
#SerializedName("SubCategories")
#Expose
private List<SubCategory> subCategories = null;
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public String getTitleEN() {
return titleEN;
}
public void setTitleEN(String titleEN) {
this.titleEN = titleEN;
}
public String getTitleAR() {
return titleAR;
}
public void setTitleAR(String titleAR) {
this.titleAR = titleAR;
}
public String getPhoto() {
return photo;
}
public void setPhoto(String photo) {
this.photo = photo;
}
public String getProductCount() {
return productCount;
}
public void setProductCount(String productCount) {
this.productCount = productCount;
}
public String getHaveModel() {
return haveModel;
}
public void setHaveModel(String haveModel) {
this.haveModel = haveModel;
}
public List<SubCategory> getSubCategories() {
return subCategories;
}
public void setSubCategories(List<SubCategory> subCategories) {
this.subCategories = subCategories;
}
}
And SubCategory
public class SubCategory {
#SerializedName("Id")
#Expose
private Integer id;
#SerializedName("TitleEN")
#Expose
private String titleEN;
#SerializedName("TitleAR")
#Expose
private String titleAR;
#SerializedName("Photo")
#Expose
private String photo;
#SerializedName("ProductCount")
#Expose
private String productCount;
#SerializedName("HaveModel")
#Expose
private String haveModel;
#SerializedName("SubCategories")
#Expose
private List<Object> subCategories = null;
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public String getTitleEN() {
return titleEN;
}
public void setTitleEN(String titleEN) {
this.titleEN = titleEN;
}
public String getTitleAR() {
return titleAR;
}
public void setTitleAR(String titleAR) {
this.titleAR = titleAR;
}
public String getPhoto() {
return photo;
}
public void setPhoto(String photo) {
this.photo = photo;
}
public String getProductCount() {
return productCount;
}
public void setProductCount(String productCount) {
this.productCount = productCount;
}
public String getHaveModel() {
return haveModel;
}
public void setHaveModel(String haveModel) {
this.haveModel = haveModel;
}
public List<Object> getSubCategories() {
return subCategories;
}
public void setSubCategories(List<Object> subCategories) {
this.subCategories = subCategories;
}
}
Step 5 now we need a view for recyclerview holder(in your case gridview layout). For that we need to create a new layout file inside layout folder. you can name it li_product_view
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="wrap_content">
<RelativeLayout
android:layout_width="200dp"
android:layout_height="200dp">
<ImageView
android:id="#+id/ImageView"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:src="#mipmap/ic_launcher" />
<TextView
android:id="#+id/tv_title"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignLeft="#id/ImageView"
android:layout_alignTop="#id/ImageView"
android:layout_alignRight="#id/ImageView"
android:layout_alignBottom="#id/ImageView"
android:text="#string/app_name"
android:gravity="bottom|right" />
</RelativeLayout>
</RelativeLayout>
Step 6 Now we need itemHolder to hold the view for that purpose we will create a new class by name ProductsItemHolderand will have the following code
public class ProductsItemHolder extends RecyclerView.ViewHolder {
#BindView(R.id.ImageView)
ImageView imageView;
#BindView(R.id.tv_title)
TextView textView;
public ProductsItemHolder(#NonNull View itemView) {
super(itemView);
ButterKnife.bind(this,itemView);
}
public void bindData(Product datum, int position, int size) {
Glide.with(itemView)
.asBitmap()
.load(datum.getPhoto())
.into(imageView);
textView.setText(datum.getTitleAR());
}
}
Step 7 Now we need adapter which contains the data to present inside recyclerview. Create a new class by name ProductsAdapter and paste the following code inside this class
public class ProductsAdapter extends RecyclerView.Adapter<RecyclerView.ViewHolder> {
private List<Product> mList;
#NonNull
#Override
public RecyclerView.ViewHolder onCreateViewHolder(#NonNull ViewGroup viewGroup, int i) {
View view = LayoutInflater.from(viewGroup.getContext()).inflate(R.layout.li_product_view, viewGroup, false);
return new ProductsItemHolder(view);
}
#Override
public void onBindViewHolder(#NonNull RecyclerView.ViewHolder viewHolder, int position) {
int size= mList.size();
((ProductsItemHolder) viewHolder).bindData(mList.get(position), position,size);
}
#Override
public int getItemCount() {
return mList.size();
}
public void setData(List<Product> userLists) {
this.mList = userLists;
notifyDataSetChanged();
}
}
Step 8 now inside the activity or fragment we need to get response from json and pass this response to recyclerview.
public class MainActivity extends AppCompatActivity {
APIInterface apiInterfacePages;
RecyclerView recyclerView;
List<MultipleResource.Datum> datumList= new ArrayList<>();
ProgressDialog dialog;
ProductsAdapter productsAdapter;
private List<Product> dataArrayList;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
apiInterfacePages= PageApiClient.getRetrofit().create(APIInterface.class);
recyclerView= findViewById(R.id.recyclerView);
productsAdapter= new ProductsAdapter();
StaggeredGridLayoutManager staggeredGridLayoutManager = new StaggeredGridLayoutManager(2, LinearLayoutManager.VERTICAL);
recyclerView.setLayoutManager(staggeredGridLayoutManager);
getData();
}
private void getData() {
dataArrayList = new ArrayList<>();
Map<String, String> params = new HashMap<String, String>();
params.put("categoryId", "0");
params.put("countryId", "1");
Call<List<Product>> call= apiInterfacePages.getProducts(params);
call.enqueue(new Callback<List<Product>>() {
#Override
public void onResponse(Call<List<Product>> call, Response<List<Product>> response) {
dataArrayList = response.body();
productsAdapter.setData(dataArrayList);
recyclerView.setAdapter(productsAdapter);
}
#Override
public void onFailure(Call<List<Product>> call, Throwable t) {
Log.i("Call response",t.getMessage());
}
});
}
}
I am trying to make a call to this api and am having difficulty as the response.body() is returning null.
http://demo.museum.vebrary.vn/api/stuff/getall
I want to get stuff name of list and show to my recyclerview.
My model:
public class SOAnswersResponse {
#SerializedName("StuffModels")
#Expose
private List<StuffModel> stuffModels = null;
public List<StuffModel> getStuffModels() {
return stuffModels;
}
public void setStuffModels(List<StuffModel> stuffModels) {
this.stuffModels = stuffModels;
}
and
public class StuffModel {
#SerializedName("STUFFID")
#Expose
private Integer sTUFFID;
#SerializedName("STUFFCODE")
#Expose
private String sTUFFCODE;
#SerializedName("STUFFNAME")
#Expose
private String sTUFFNAME;
#SerializedName("STUFFNOTE")
#Expose
private String sTUFFNOTE;
#SerializedName("STUFFORDER")
#Expose
private Integer sTUFFORDER;
#SerializedName("CUSTOMERID")
#Expose
private String cUSTOMERID;
#SerializedName("EXHIBITS")
#Expose
private List<Object> eXHIBITS = null;
Json response
{
"StuffModels":[
{
"STUFFID":2,
"STUFFCODE":"Gi",
"STUFFNAME":"Giấy",
"STUFFNOTE":"",
"STUFFORDER":2,
"CUSTOMERID":"CAMAU",
"EXHIBITS":[
]
},
ApiUtils Class
public class ApiUtils {
private ApiUtils() {
}
public static final String BASE_URL = "http://demo.museum.vebrary.vn/api/";
public static SOService getSOService() {
return RetrofitClient.getClient(BASE_URL).create(SOService.class);
}
}
Service interface
public interface SOService {
#GET("/stuff/getall")
Call<SOAnswersResponse> getAnswers();
}
RetrofitClient Class
public class RetrofitClient {
private static Retrofit retrofit = null;
public static Retrofit getClient(String baseUrl) {
if (retrofit==null) {
retrofit = new Retrofit.Builder()
.baseUrl(baseUrl)
.addConverterFactory(GsonConverterFactory.create())
.build();
}
return retrofit;
}
}
My RecyclerView adapter
public class CategogyNameRecyclerViewAdapter extends RecyclerView.Adapter<CategogyNameRecyclerViewAdapter.ViewHolder> {
private List<StuffModel> mItems;
private Context mContext;
private PostItemListener mItemListener;
public class ViewHolder extends RecyclerView.ViewHolder implements View.OnClickListener{
public TextView titleTv;
PostItemListener mItemListener;
public ViewHolder(View itemView, PostItemListener postItemListener) {
super(itemView);
titleTv = itemView.findViewById(R.id.tvListMenuCategogy);
this.mItemListener = postItemListener;
itemView.setOnClickListener(this);
}
#Override
public void onClick(View view) {
StuffModel item = getItem(getAdapterPosition());
this.mItemListener.onPostClick(item.getSTUFFID());
notifyDataSetChanged();
}
}
public CategogyNameRecyclerViewAdapter(Context context, List<StuffModel> posts, PostItemListener itemListener) {
mItems = posts;
mContext = context;
mItemListener = itemListener;
}
#Override
public CategogyNameRecyclerViewAdapter.ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
Context context = parent.getContext();
LayoutInflater inflater = LayoutInflater.from(context);
View postView = inflater.inflate(R.layout.item_list_text, parent, false);
ViewHolder viewHolder = new ViewHolder(postView, this.mItemListener);
return viewHolder;
}
#Override
public void onBindViewHolder(CategogyNameRecyclerViewAdapter.ViewHolder holder, int position) {
StuffModel item = mItems.get(position);
TextView textView = holder.titleTv;
textView.setText(item.getSTUFFNAME());
}
#Override
public int getItemCount() {
return mItems.size();
}
public void updateAnswers(List<StuffModel> items) {
mItems = items;
notifyDataSetChanged();
}
private StuffModel getItem(int adapterPosition) {
return mItems.get(adapterPosition);
}
public interface PostItemListener {
void onPostClick(long id);
}
}
And my main activity
public class Testttt extends AppCompatActivity {
private CategogyNameRecyclerViewAdapter mAdapter;
private RecyclerView mRecyclerView;
private SOService mService;
#Override
protected void onCreate (Bundle savedInstanceState) {
super.onCreate( savedInstanceState );
setContentView(R.layout.test );
mService = ApiUtils.getSOService();
mRecyclerView = (RecyclerView) findViewById(R.id.rcvCategogyNameMenuTest);
mAdapter = new CategogyNameRecyclerViewAdapter(this, new ArrayList<StuffModel>(0), new CategogyNameRecyclerViewAdapter.PostItemListener() {
#Override
public void onPostClick(long id) {
Toast.makeText(Testttt.this, "Post id is" + id, Toast.LENGTH_SHORT).show();
}
});
RecyclerView.LayoutManager layoutManager = new LinearLayoutManager(this);
mRecyclerView.setLayoutManager(layoutManager);
mRecyclerView.setAdapter(mAdapter);
mRecyclerView.setHasFixedSize(true);
RecyclerView.ItemDecoration itemDecoration = new DividerItemDecoration(this, DividerItemDecoration.VERTICAL_LIST);
mRecyclerView.addItemDecoration(itemDecoration);
loadAnswers();
}
public void loadAnswers() {
mService.getAnswers().enqueue(new Callback<SOAnswersResponse>() {
#Override
public void onResponse(Call<SOAnswersResponse> call, Response<SOAnswersResponse> response) {
Toast.makeText(Testttt.this, "333333333333333333"+response.body(), Toast.LENGTH_SHORT).show();
if(response.isSuccessful()) {
mAdapter.updateAnswers(response.body().getStuffModels());
Log.d("AnswersPresenter", "posts loaded from API");
}else {
int statusCode = response.code();
}
}
#Override
public void onFailure(Call<SOAnswersResponse> call, Throwable t) {
showErrorMessage();
Log.d("AnswersPresenter", "error loading from API");
}
});
}
public void showErrorMessage() {
Toast.makeText(this, "Error loading posts", Toast.LENGTH_SHORT).show();
}
}
The first thing that came in my mind:
Your
public static final String BASE_URL = "http://demo.museum.vebrary.vn/api/";
has a "/" at the the end and your
#GET("/stuff/getall")
Call<SOAnswersResponse> getAnswers();
starts with a "/". So there is a double backslash in the url that might leads to the 404 code. Does this solve the problem?
When i call your URL i receive XML. Maybe the API is not configured correctly?
Change your Service interface
public interface SOService {
#GET("stuff/getall")
Call<SOAnswersResponse> getAnswers();
}
it occurred because you have use start with backslash it already added in your base url
please help me..
i have 10 policy data on my PHP to show on recyclerview android studio using retrofit..but, when i run my emulator, the emulator just show 1 data..my plan just show PolicyNo..when i running emulator and check my log, they've said : my Number Policy Received: 10
sorry for my bad english :(
here is my policyActivity :
public class PolicyActivity extends AppCompatActivity {
private static final String TAG = PolicyActivity.class.getSimpleName();
private String policyno;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_policy);
final RecyclerView recyclerView = (RecyclerView) findViewById(R.id.policy_recycler_view);
recyclerView.setLayoutManager(new LinearLayoutManager(this));
ApiEndPoint apiEndPoint =
ApiClient.getClient(this).create(ApiEndPoint.class);
Call<PolicyStatus> call = apiEndPoint.getPolicyNo(policyno);
call.enqueue(new Callback<PolicyStatus>() {
#Override
public void onResponse(Call<PolicyStatus> call, Response<PolicyStatus> response) {
List<PolicyNo> policyNo = response.body().getPolicyNo();
Log.d(TAG, "Number Policy Received: " + policyNo.size());
recyclerView.setAdapter(new PolicyAdapter(policyNo, R.layout.list_item_policy, getApplicationContext()));
}
#Override
public void onFailure (Call <PolicyStatus> call, Throwable t){
Log.e(TAG, t.toString());
}
});
}
}
and this is my policyadapter:
public class PolicyAdapter extends RecyclerView.Adapter<PolicyAdapter.PolicyViewHolder> {
private List<PolicyNo> policyNo;
private int rowLayout;
private Context context;
public static class PolicyViewHolder extends RecyclerView.ViewHolder{
LinearLayout policyLayout;
TextView nomorpolis;
public PolicyViewHolder (View v){
super(v);
policyLayout = (LinearLayout) v.findViewById(R.id.policy_layout);
nomorpolis = (TextView)v.findViewById(R.id.nomorpolis);
}
}
public PolicyAdapter (List<PolicyNo>policyNo, int rowLayout, Context context){
this.policyNo = policyNo;
this.context = context;
this.rowLayout = rowLayout;
}
#Override
public PolicyAdapter.PolicyViewHolder onCreateViewHolder(ViewGroup parent, int viewType){
View view= LayoutInflater.from(parent.getContext()).inflate(rowLayout, parent, false);
return new PolicyViewHolder(view);
}
#Override
public void onBindViewHolder (PolicyViewHolder holder, final int position){
holder.nomorpolis.setText(policyNo.get(position).getPolicyNo());
}
#Override
public int getItemCount() {return policyNo.size();}
}
PolicyStatus :
public class PolicyStatus {
#SerializedName("success")
#Expose
private Boolean success;
#SerializedName("PolicyNo")
#Expose
private List<PolicyNo> policyNo = null;
public Boolean getSuccess() {
return success;
}
public void setSuccess(Boolean success) {
this.success = success;
}
public List<PolicyNo> getPolicyNo() {
return policyNo;
}
public void setPolicyNo(List<PolicyNo> policyNo) {
this.policyNo = policyNo;
}
PolicyNo :
public class PolicyNo {
#SerializedName("ANO")
#Expose
private Integer aNO;
#SerializedName("PolicyNo")
#Expose
private String policyNo;
#SerializedName("ADate")
#Expose
private ADate aDate;
#SerializedName("ADATE")
#Expose
private String aDATE;
public Integer getANO() {
return aNO;
}
public void setANO(Integer aNO) {
this.aNO = aNO;
}
public String getPolicyNo() {
return policyNo;
}
public void setPolicyNo(String policyNo) {
this.policyNo = policyNo;
}
public ADate getADate() {
return aDate;
}
public void setADate(ADate aDate) {
this.aDate = aDate;
}
public String getADATE() {
return aDATE;
}
public void setADATE(String aDATE) {
this.aDATE = aDATE;
}
public PolicyNo (String policyNo){
this.policyNo = policyNo;
}
}
api endpoint :
#GET ("policy.php")
Call<PolicyStatus> getPolicyNo (#Query("PolicyNo") String policyNo);
I think you have given list_item_policy to match_parent. as you are saying you are getting 10 size in log. then this can be only reason. may be you will find items on scroll. So just change this to wrap_content.
Also check your recyclerView getting full height check in the preview.
Code looks fine except one thing which I noticed :-
Do this :-
LinearLayoutManager layoutManager
= new LinearLayoutManager(this, LinearLayoutManager.VERTICAL, false);
myList.setLayoutManager(layoutManager);
instead of :-
recyclerView.setLayoutManager(new LinearLayoutManager(this));