Skip to content
Advertisement

Using Viewpager to display images from web but it is not showing me, Someone help me to solve this issue

I don’t have any errors but still my data is not showing in android emulator, I passed it in mainactivity but still it displays blank screen,Someone help me to solve this issue. I gave internet permission to display images. Is this androidx jetpack problem because it is happening for me many times while getting information from web .Check out the code below

MainActivity

public class MainActivity extends AppCompatActivity {
    private static final String TAG = "MainActivity";
    private String[] imageUrls = {"https://picsum.photos/seed/picsum/200/300","https://picsum.photos/id/237/200/300"};

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        Log.d(TAG, "onCreate: onCreate method executing");
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        ViewPager viewPager = findViewById(R.id.viewpager);
        ViewAdapter adapter = new ViewAdapter(this,imageUrls);
        viewPager.setAdapter(adapter);
    }
}

ViewAdapter

public class ViewAdapter extends PagerAdapter {
    private static final String TAG = "ViewAdapter";
    private Context mContext;
    private String[] imageUrls;

    public ViewAdapter(Context context, String[] imageUrls) {
        mContext = context;
        this.imageUrls = imageUrls;
    }
    @Override
    public int getCount() {
        return imageUrls.length;
    }
    @Override
    public boolean isViewFromObject(@NonNull View view, @NonNull Object object) {
        return view==object;
    }
    @NonNull
    @Override
    public Object instantiateItem(@NonNull ViewGroup container, int position) {
        ImageView imageView = new ImageView(mContext);
        Picasso.get().load(imageUrls[position]).fit().centerCrop().into(imageView);
        Log.d(TAG, "instantiateItem: returning view");
        return imageView;
    }
    @Override
    public void destroyItem(@NonNull ViewGroup container, int position, @NonNull Object object) {
      container.removeView((View) object);
    }
}

 Android manifest

 <uses-permission android:name="android.permission.INTERNET" />

Thank you!!

Advertisement

Answer

Root cause: You forgot to add the imageView into the containing View in which the imageView will be shown.

Solution: Change your code to

@NonNull
@Override
public Object instantiateItem(@NonNull ViewGroup container, int position) {
    ImageView imageView = new ImageView(mContext);
    Picasso.get()
            .load(imageUrls[position])
            .fit()
            .centerCrop()
            .into(imageView);
    
    // Add this line
    container.addView(imageView);
    
    Log.d(TAG, "instantiateItem: returning view");
    return imageView;
}
User contributions licensed under: CC BY-SA
1 People found this is helpful
Advertisement