Search code examples
javaandroidmultithreadinghandlerpicasso

Android Picasso not loading img to view from handler


I trying to get pic url in Thread and load in Picasso, but image not shows. Url is valid. Picasso not load placeholder and error img. Without Thread and Handler works fine.

     final String[] sss = {""};
    final Handler hh = new Handler(){
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            Picasso.with(context).load(sss[0]).resize(500, 281).centerCrop().into(mainHolder.ivPreview);
        }
    };
    Thread th = new Thread(new Runnable() {
        @Override
        public void run() {
            sss[0] = getUrl();
            hh.sendEmptyMessage(0);

        }
    });
    th.start();

Solution

  • You Check again getUrl() and context. This code work for me.

     public class MainActivity extends AppCompatActivity {
    
        @Override
        protected void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
            setContentView(R.layout.activity_main);
            final ImageView imageView= (ImageView) findViewById(R.id.imageView);
    
            final Context context=this;
            final String[] sss = {""};
            final Handler hh = new Handler(){
                @Override
                public void handleMessage(Message msg) {
                    super.handleMessage(msg);
                    Picasso.with(context).load(sss[0]).resize(500, 281).centerCrop().into(imageView);
                }
            };
            Thread th = new Thread(new Runnable() {
                @Override
                public void run() {
                    sss[0] = "http://teleflora.edgesuite.net/images/products/HW0_706075.jpg";
                    hh.sendEmptyMessage(0);
    
                }
            });
            th.start();
        }
    }