I am trying to download image using url and set it as TextView background.
Bitmap bmImg;
URL myfileurl =null;
try{
myfileurl= new URL("https://www.vegetables.co.nz/assets/vegetables/_resampled/FillWyI0MDAiLCIzMDAiXQ/carrots.png");
}
catch (MalformedURLException e){
e.printStackTrace();
}
try{
HttpURLConnection conn= (HttpURLConnection)myfileurl.openConnection();
conn.setDoInput(true);
conn.connect();
InputStream is = conn.getInputStream();
BitmapFactory.Options options = new BitmapFactory.Options();
bmImg = BitmapFactory.decodeStream(is,null,options);
Drawable dr = new BitmapDrawable(bmImg);
tv.setBackgroundDrawable(dr);
tv.setImageBitmap(bmImg);
}
catch(IOException e){
// TODO Auto-generated catch block
e.printStackTrace();
Toast.makeText(PhotoRating.this, "Connection Problem. Try Again.", Toast.LENGTH_SHORT).show();
}
I getting error -->
AndroidRuntime: FATAL EXCEPTION: main Process: com.example.android.architecture.blueprints.tododatabinding.mock, PID: 20288 android.os.NetworkOnMainThreadException at android.os.StrictMode$AndroidBlockGuardPolicy.onNetwork(StrictMode.java:1303) at java.net.Inet6AddressImpl.lookupHostByName(Inet6AddressImpl.java:86) at java.net.Inet6AddressImpl.lookupAllHostAddr(Inet6AddressImpl.java:74) at java.net.InetAddress.getAllByName(InetAddress.java:752) at com.android.okhttp.internal.Network$1.resolveInetAddresses(Network.java:29) at com.android.okhttp.internal.http.RouteSelector.resetNextInetSocketAddress(RouteSelector.java:209) at com.android.okhttp.internal.http.RouteSelector.nextProxy(RouteSelector.java:163) at com.android.okhttp.internal.http.RouteSelector.next(RouteSelector.java:105) at com.android.okhttp.internal.http.HttpEngine.createNextConnection(HttpEngine.java:489) at com.android.okhttp.internal.http.HttpEngine.connect(HttpEngine.java:465) at com.android.okhttp.internal.http.HttpEngine.sendRequest(HttpEngine.java:371) at com.android.okhttp.internal.huc.HttpURLConnectionImpl.execute(HttpURLConnectionImpl.java:503) at com.android.okhttp.internal.huc.HttpURLConnectionImpl.connect(HttpURLConnectionImpl.java:130) at com.example.android.architecture.blueprints.todoapp.productlist.ProductlistFragment$2.getView(ProductlistFragment.java:200) at android.widget.AbsListView.obtainView(AbsListView.java:3170) at android.widget.GridView.onMeasure(GridView.java:1104)
I have provided INTERNET Permission
in Manifest.xml
file. I don't know what the error is.
Option 2:
I have also tried Picasso
, adding dependency compile com.squareup.picasso:picasso:2.4.0
to app/build.gradle
TextView tv = (TextView) findViewById(R.id.textView1);
Picasso.with(this) .load("https://www.vegetables.co.nz/assets/vegetables/_resampled/FillWyI0MDAiLCIzMDAiXQ/carrots.png").into(tv);
It shows
cannot find symbol variable Picasso