0

im hosting a webservice on my RPi, i have a .png image which i can access through the network from my android device. This is my code to get that image :

// Write image to image view
public static Bitmap getBitmapFromURL(String src) {
    try {
        URL url = new URL(src);
        HttpURLConnection connection = (HttpURLConnection) url.openConnection();
        connection.setDoInput(true);
        connection.connect();
        InputStream input = connection.getInputStream();
        return BitmapFactory.decodeStream(input);

    } catch (IOException e) {
        e.getMessage();
        return null;
    }
}

and here i display the image to a Image View when a button is clicked (in the Oncreate event):

Button picturebutton = (Button) findViewById(R.id.btngetpic);
    final ImageView myview = (ImageView) findViewById(R.id.imgview1);

    assert picturebutton != null;
    picturebutton.setOnClickListener(
            new Button.OnClickListener() {
                public void onClick(View v) {
                    TextView mytext = (TextView) findViewById(R.id.mytext);
                    mytext.setText("done");
                    myview.setImageBitmap(getBitmapFromURL("http://169.254.XXX.XXX/Images/Itworks.png"));
                }
            }
    );

I have INTERNET in my uses manifest but whenever i run the application it force closes. I have a feeling it has something to do with my listener but i cant fix it. Any help appreciated because i am super confused. (Im still new to Android development although i have experience in java desktop)

EDIT: My exception stack from where it Force closes

07-13 18:14:00.718 4077-4077/? E/AndroidRuntime: FATAL EXCEPTION: main
                                             Process: com.example.neil.access_control, PID: 4077
                                             android.os.NetworkOnMainThreadException
                                                 at android.os.StrictMode$AndroidBlockGuardPolicy.onNetwork(StrictMode.java:1273)
                                                 at libcore.io.BlockGuardOs.connect(BlockGuardOs.java:110)
                                                 at libcore.io.IoBridge.connectErrno(IoBridge.java:137)
                                                 at libcore.io.IoBridge.connect(IoBridge.java:122)
                                                 at java.net.PlainSocketImpl.connect(PlainSocketImpl.java:183)
                                                 at java.net.PlainSocketImpl.connect(PlainSocketImpl.java:452)
                                                 at java.net.Socket.connect(Socket.java:884)
                                                 at com.android.okhttp.internal.Platform.connectSocket(Platform.java:117)
                                                 at com.android.okhttp.internal.http.SocketConnector.connectRawSocket(SocketConnector.java:160)
                                                 at com.android.okhttp.internal.http.SocketConnector.connectCleartext(SocketConnector.java:67)
                                                 at com.android.okhttp.Connection.connect(Connection.java:152)
                                                 at com.android.okhttp.Connection.connectAndSetOwner(Connection.java:185)
                                                 at com.android.okhttp.OkHttpClient$1.connectAndSetOwner(OkHttpClient.java:128)
                                                 at com.android.okhttp.internal.http.HttpEngine.nextConnection(HttpEngine.java:341)
                                                 at com.android.okhttp.internal.http.HttpEngine.connect(HttpEngine.java:330)
                                                 at com.android.okhttp.internal.http.HttpEngine.sendRequest(HttpEngine.java:248)
                                                 at com.android.okhttp.internal.huc.HttpURLConnectionImpl.execute(HttpURLConnectionImpl.java:433)
                                                 at com.android.okhttp.internal.huc.HttpURLConnectionImpl.connect(HttpURLConnectionImpl.java:114)
                                                 at com.example.neil.access_control.MainActivity.getBitmapFromURL(MainActivity.java:71)
                                                 at com.example.neil.access_control.MainActivity$1.onClick(MainActivity.java:54)
                                                 at android.view.View.performClick(View.java:5198)
                                                 at android.view.View$PerformClick.run(View.java:21147)
                                                 at android.os.Handler.handleCallback(Handler.java:739)
                                                 at android.os.Handler.dispatchMessage(Handler.java:95)
                                                 at android.os.Looper.loop(Looper.java:148)
                                                 at android.app.ActivityThread.main(ActivityThread.java:5417)
                                                 at java.lang.reflect.Method.invoke(Native Method)
                                                 at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:726)
                                                 at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:616)

07-13 18:14:00.727 1283-3180/? W/ActivityManager: Force finishing activity com.example.neil.access_control/.MainActivity

MADJAR
  • 67
  • 10
  • If you can paste the exception stack, that helps. Do you have access to the log? – kosa Jul 13 '16 at 16:20
  • Take a look at this answer, http://stackoverflow.com/questions/22395417/error-strictmodeandroidblockguardpolicy-onnetwork , specially Arshad Ali answer. – Álvaro Pérez Soria Jul 13 '16 at 16:27

2 Answers2

1

I am aware that this is an "alternative" solution to you problem, but I thought of posting it as it was a help for me too when I came across it trying to resolve my set of problems.

I'd suggest you use Picasso as your image loader as it can load images from URLs plus it provides you also with:

  • caching mechanism
  • image transformation utilities

It is as simple as

Picasso.with(context).load("http://i.imgur.com/DvpvklR.png").into(imageView);

On the other hand to load only the bitmap you could do something like (as outlined in this SO answer):

    Target target = new Target() {
        @Override
        public void onBitmapLoaded(Bitmap bitmap, Picasso.LoadedFrom from) {
            /* Do something with the bitmap*/
        }

        @Override
        public void onBitmapFailed(Drawable errorDrawable) {
            /* handle failure */
        }

        @Override
        public void onPrepareLoad(Drawable placeHolderDrawable) {
            /* you may execute some logic before loading*/
        }
    };
    Picasso.with(context).load(imageURL).into(target);

Note: I am not affiliated in any way with Picasso

Community
  • 1
  • 1
Matyas
  • 13,473
  • 3
  • 60
  • 73
1

Your problem is: NetworkOnMainThreadException, you can read the documentation here, but the important part is that the Android cannot have "blocking operations" on the Main thread (the Graphical User Interface one).

Use an AsynkTask or another Thread to query the internet/network for the data.

While Picasso is a good "image library", I also higly suggest Volley (from Google), it has an excelent documentation, as well as several examples. Not only that, Volley will also "micromanage" the best library to use network available on the device).

note that HttpURLConnection is deprecated IIRC on API 19 KitKat

Bonatti
  • 2,778
  • 5
  • 23
  • 42
  • So my GetBitmapfromUrl method should execute inside a AsyncTask thread? and what would you recommend in place of HttpURLConnection ? Thanks in advance – MADJAR Jul 13 '16 at 16:41
  • `So my GetBitmapfromUrl method should execute inside a AsyncTask thread? ` Yes. `what would you recommend in place of HttpURLConnection ?` If this is a learning application, then keep using HttpURLConnection. If you intend on creating a product, then please, [check Volley](https://developer.android.com/training/volley/index.html) I have been using it, and been very happy with the results. Its fast, can handle a lot of situation, does cache, etc etc. On a final note, [please read this document](https://developer.android.com/reference/android/app/Activity.html). I believe it to be the best start – Bonatti Jul 13 '16 at 16:47