I have a recycler view in which I am trying to load data from a url using retrofit and loading images in recycler view using Picasso library. I don't know everything looks fine to me, I logged the incoming data it is showing in logcat, but it is not inflating in UI views. URL links are working fine, I tried to load images without the retrofit to check it is working or not, but it was fine. Please let me know what could be the issue.
APIInterface.java
@Headers("Content-Type: application/json")
@GET("products/category")
Call<ArrayList<CategoryGridModel>> getCategories();
WebReq.java
private static Retrofit retrofit = null;
private static ProgressDialog pDialog;
public static Retrofit getRetrofit() {
if (retrofit == null) {
Gson gson = new GsonBuilder()
.setLenient()
.create();
HttpLoggingInterceptor httpLoggingInterceptor= new HttpLoggingInterceptor();
httpLoggingInterceptor.setLevel(HttpLoggingInterceptor.Level.BODY);
OkHttpClient okHttpClient = new OkHttpClient.Builder().addInterceptor(httpLoggingInterceptor).build();
retrofit = new Retrofit.Builder()
.baseUrl(GlobalClass.BASE_URL)
.addConverterFactory(GsonConverterFactory.create(gson))
.client(okHttpClient)
.build();
}
return retrofit;
}
private WebReq() {
}
public static APIInterface getApiInterface(){
APIInterface apiInterface= getRetrofit().create(APIInterface.class);
return apiInterface;
}
//concatenation of base url and file name
public static String getAbsoluteUrl(String relativeUrl) {
Log.d("response URL: ", GlobalClass.BASE_URL + relativeUrl + " ");
return GlobalClass.BASE_URL + relativeUrl;
}
public static void showDialog() {
if(pDialog != null && !pDialog.isShowing()) {
pDialog.setIndeterminate(true);
pDialog.setMessage("Loading...");
pDialog.setCanceledOnTouchOutside(false);
pDialog.show();
}
}
public static void hideDialog() {
if(pDialog != null && pDialog.isShowing())
pDialog.dismiss();
}
CategoryAdapter.java
public class CategoryAdapter extends RecyclerView.Adapter<CategoryAdapter.ViewHolder> {
ArrayList<CategoryGridModel> listData;
//CategoryGridModel listData;
Context context;
int resource;
protected ItemListener itemListener;
public CategoryAdapter(Context context, ArrayList<CategoryGridModel> listData, ItemListener itemListener) {
//this.listData = listData;
this.context = context;
this.itemListener=itemListener;
}
public CategoryAdapter(Context context, ArrayList<CategoryGridModel> listData) {
this.listData = listData;
this.context = context;
}
@NonNull
@Override
public ViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
View v= LayoutInflater.from(parent.getContext()).inflate(R.layout.categortlist_items,parent,false);
return new ViewHolder(v);
}
@Override
public void onBindViewHolder(ViewHolder viewHolder, int position) {
CategoryGridModel categoryGridModel = listData.get(position);
//viewHolder.icon.setImageResource(listData.get(position).getCat_image_link());
Picasso.with(context)
.load(listData.get(position).getCat_image_link())
.placeholder(R.drawable.searchbox)
.into(viewHolder.icon, new Callback() {
@Override
public void onSuccess() {
Toast.makeText(context,"Loaded Successfully", Toast.LENGTH_SHORT).show();
}
@Override
public void onError() {
Toast.makeText(context,"Load failed", Toast.LENGTH_SHORT).show();
}
});
viewHolder.iconName.setText(listData.get(position).getCat_name());
}
public class ViewHolder extends RecyclerView.ViewHolder{
ImageView icon;
TextView iconName;
public ViewHolder(View itemView) {
super(itemView);
icon = (ImageView) itemView.findViewById(R.id.catimg);
iconName = (TextView) itemView.findViewById(R.id.catname);
}
}
@Override
public int getItemCount() {
return listData.size();
}
public interface ItemListener {
void onItemClick(CategoryGridModel item);
}
}
CategoryGridModel
public class CategoryGridModel {
private String id;
private String cat_name;
private String cat_img_1;
private String cat_image_link;
public String getCat_img_1() {
return cat_img_1;
}
public void setCat_img_1(String cat_img_1) {
this.cat_img_1 = cat_img_1;
}
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public String getCat_name() {
return cat_name;
}
public void setCat_name(String cat_name) {
this.cat_name = cat_name;
}
public String getCat_image_link() {
return cat_image_link;
}
public void setCat_image_link(String cat_image_link) {
this.cat_image_link = cat_image_link;
}
}
HomePage.java
public class HomePage extends AppCompatActivity implements BaseSliderView.OnSliderClickListener,
ViewPagerEx.OnPageChangeListener {
private RecyclerView categoryRV;
private AppBarConfiguration mAppBarConfiguration;
HashMap<String, String> HashMapForURL;
HashMap<String, Integer> HashMapForLocalRes ;
//slider
private SliderLayout sliderLayout ;
//gridview
private GridView gridView;
CategoryAdapter categoryAdapter;
ArrayList<CategoryGridModel> categoryGridModels;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_home_page);
Toolbar toolbar = findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
DrawerLayout drawer = findViewById(R.id.drawer_layout);
NavigationView navigationView = findViewById(R.id.nav_view);
// Passing each menu ID as a set of Ids because each
// menu should be considered as top level destinations.
mAppBarConfiguration = new AppBarConfiguration.Builder(
R.id.nav_home, R.id.nav_gallery, R.id.nav_slideshow)
.setDrawerLayout(drawer)
.build();
NavController navController = Navigation.findNavController(this, R.id.nav_host_fragment);
NavigationUI.setupActionBarWithNavController(this, navController, mAppBarConfiguration);
NavigationUI.setupWithNavController(navigationView, navController);
//slider
sliderLayout = (SliderLayout)findViewById(R.id.pslider);
//images urls
//Call this method if you want to add images from URL .
getSliderImagesUrl();
//Call this method to add images from local drawable folder .
//AddImageUrlFormLocalRes();
//Call this method to stop automatic sliding.
//sliderLayout.stopAutoCycle();
for(String name : HashMapForURL.keySet()){
Log.d("SLiderlist---",name);
Toast.makeText(this,name, Toast.LENGTH_SHORT).show();
TextSliderView textSliderView = new TextSliderView(HomePage.this);
textSliderView
.description(name)
.image(HashMapForURL.get(name))
.setScaleType(BaseSliderView.ScaleType.Fit)
.setOnSliderClickListener(this);
textSliderView.bundle(new Bundle());
textSliderView.getBundle()
.putString("extra",name);
sliderLayout.addSlider(textSliderView);
}
sliderLayout.setPresetTransformer(SliderLayout.Transformer.DepthPage);
sliderLayout.setPresetIndicator(SliderLayout.PresetIndicators.Center_Bottom);
sliderLayout.setCustomAnimation(new DescriptionAnimation());
sliderLayout.setDuration(10000);
sliderLayout.addOnPageChangeListener(HomePage.this);
//loading categories
getCategoriesFromURL();
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.home_page, menu);
return true;
}
@Override
public boolean onSupportNavigateUp() {
NavController navController = Navigation.findNavController(this, R.id.nav_host_fragment);
return NavigationUI.navigateUp(navController, mAppBarConfiguration)
|| super.onSupportNavigateUp();
}
public void AddImagesUrlOnline(){
HashMapForURL = new HashMap<String, String>();
}
@Override
public void onSliderClick(BaseSliderView slider) {
Toast.makeText(this,slider.getBundle().get("extra") + "", Toast.LENGTH_SHORT).show();
}
@Override
public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {}
@Override
public void onPageSelected(int position) {
Log.d("Slider Demo", "Page Changed: " + position);
}
@Override
public void onPageScrollStateChanged(int state) {
}
@Override
protected void onStop() {
sliderLayout.stopAutoCycle();
super.onStop();
}
/**
* Load images from url
*/
public void getSliderImagesUrl(){
Call<List<SliderModel>> call =WebReq.getApiInterface().getSliderImages();
HashMapForURL = new HashMap<String, String>();
//SliderModel sliderModel;
call.enqueue(new Callback<List<SliderModel>>() {
@Override
public void onResponse(Call<List<SliderModel>> call, Response<List<SliderModel>> response) {
for(SliderModel sliderModel: response.body()) {
Log.d("Slider obj--",sliderModel.getS_name()+" URL : "+sliderModel.getImage_link());
HashMapForURL.put(sliderModel.getS_name(), sliderModel.getImage_link());
}
}
@Override
public void onFailure(Call<List<SliderModel>> call, Throwable t) {
Toast.makeText(getApplicationContext()
, "Error while loading slider", Toast.LENGTH_SHORT).show();
}
});
//load images
//HashMapForURL.put(sliderModel.getS_name(), sliderModel.getImage_link());
}
/**
* get categories from url
*/
public void getCategoriesFromURL(){
//grid view
categoryRV=(RecyclerView)findViewById(R.id.catrecycler_view);
categoryRV.setHasFixedSize(true);
categoryRV.setLayoutManager(new LinearLayoutManager(this));
//GridLayoutManager manager = new GridLayoutManager(this, 2, GridLayoutManager.VERTICAL, false);
//categoryRV.setLayoutManager(manager);
Call<ArrayList<CategoryGridModel>> call =WebReq.getApiInterface().getCategories();
call.enqueue(new Callback<ArrayList<CategoryGridModel>>() {
@Override
public void onResponse(Call<ArrayList<CategoryGridModel>> call, Response<ArrayList<CategoryGridModel>> response) {
categoryGridModels = response.body();
categoryAdapter=new CategoryAdapter(HomePage.this,categoryGridModels);
categoryRV.setAdapter(categoryAdapter);
for(CategoryGridModel categoryGridModel: response.body()) {
Log.d("Slider obj--",categoryGridModel.getCat_name()+" URL: "+categoryGridModel.getCat_image_link());
}
categoryAdapter.notifyDataSetChanged();
//categoryRV.setRefreshing(false);
}
@Override
public void onFailure(Call<ArrayList<CategoryGridModel>> call, Throwable t) {
Toast.makeText(getApplicationContext()
, "Error while loading slider", Toast.LENGTH_SHORT).show();
}
});
}
}
Response that I am capturing
[
{
"id": "3",
"cat_name": "Apparel",
"cat_img_1": "clothes1.png",
"cat_image_link": "https:\/\/xyz.com\/uploads\/cat_images\/clothes1.png"
},
{
"id": "2",
"cat_name": "Fresh Vegetables",
"cat_img_1": "choco.jpg",
"cat_image_link": "https:\/\/xyz.com\/uploads\/cat_images\/choco.jpg"
}
]
I have a navigation drawer, so I am using here.
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
app:layout_behavior="@string/appbar_scrolling_view_behavior"
tools:showIn="@layout/app_bar_main">
<ScrollView
android:layout_width="fill_parent"
android:layout_height="fill_parent" >
<RelativeLayout
android:layout_width="wrap_content"
android:layout_height="wrap_content">
<fragment
android:id="@+id/nav_host_fragment"
android:name="androidx.navigation.fragment.NavHostFragment"
android:layout_width="match_parent"
android:layout_height="match_parent"
app:defaultNavHost="true"
app:layout_constraintLeft_toLeftOf="parent"
app:layout_constraintRight_toRightOf="parent"
app:layout_constraintTop_toTopOf="parent"
app:navGraph="@navigation/mobile_navigation" />
<com.daimajia.slider.library.SliderLayout
android:id="@+id/pslider"
android:layout_marginTop="0dp"
android:background="@drawable/searchbox"
android:layout_width="fill_parent"
android:layout_height="170dp"/>
<RelativeLayout
android:id="@+id/featuredTitle"
android:layout_below="@id/pslider"
android:layout_marginLeft="20dp"
android:layout_marginRight="20dp"
android:layout_marginTop="20dp"
android:layout_width="match_parent"
android:layout_height="30dp">
<TextView
android:id="@+id/cattitle"
android:text="Product Category"
android:layout_alignParentLeft="true"
android:textSize="18sp"
android:layout_width="wrap_content"
android:fontFamily="sans-serif-condensed-medium"
android:layout_height="30dp"/>
<!--<TextView
android:id="@+id/seeAlltext"
android:text="See All"
android:layout_alignParentRight="true"
android:layout_width="wrap_content"
android:fontFamily="sans-serif-condensed-medium"
android:layout_height="20dp"/>-->
<RelativeLayout
android:layout_width="match_parent"
android:layout_below="@id/cattitle"
android:layout_height="match_parent">
<androidx.recyclerview.widget.RecyclerView
android:id="@+id/catrecycler_view"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:scrollbars="vertical"
app:layout_behavior="@string/appbar_scrolling_view_behavior" />
</RelativeLayout>
</RelativeLayout>
</RelativeLayout>
</ScrollView>
</RelativeLayout>
Finally got the solution here : Here
The problem is retrofit seems to do Async task , so my data was arriving at the moment I was doing operation on it, but there was lag.