当前位置: 动力学知识库 > 问答 > 编程问答 >

Cannot convert url to bitmap in android

问题描述:

I am developing an Android App. In my app, I need to convert url into bitmap. I searched online and I found some code in stackoverflow. I just used it. But it does not work. It is giving me error.

This is my convert method

public final class CommonHelper{

public static Bitmap ConvertUrlToBitmap(String src)

{

try {

URL url = new URL(src);

HttpURLConnection connection = (HttpURLConnection) url.openConnection();

connection.setDoInput(true);

connection.connect();

InputStream input = connection.getInputStream();

Bitmap myBitmap = BitmapFactory.decodeStream(input);

return myBitmap;

} catch (IOException e) {

e.printStackTrace();

return null;

}

}

}

So when I use that method in activity, it is giving me error. This is the error in logcat.

This is the errors

05-05 17:41:16.674 10095-10101/? E/jdwp: Failed sending reply to debugger: Broken pipe

05-05 17:41:16.674 10095-10101/? D/dalvikvm: Debugger has detached; object registry had 1 entries

05-05 17:41:16.770 10095-10095/? W/dalvikvm: VFY: unable to find class referenced in signature (Landroid/view/SearchEvent;)

05-05 17:41:16.770 10095-10095/? I/dalvikvm: Could not find method android.view.Window$Callback.onSearchRequested, referenced from method android.support.v7.view.WindowCallbackWrapper.onSearchRequested

05-05 17:41:16.770 10095-10095/? W/dalvikvm: VFY: unable to resolve interface method 18254: Landroid/view/Window$Callback;.onSearchRequested (Landroid/view/SearchEvent;)Z

05-05 17:41:16.770 10095-10095/? D/dalvikvm: VFY: replacing opcode 0x72 at 0x0002

05-05 17:41:16.770 10095-10095/? I/dalvikvm: Could not find method android.view.Window$Callback.onWindowStartingActionMode, referenced from method android.support.v7.view.WindowCallbackWrapper.onWindowStartingActionMode

05-05 17:41:16.770 10095-10095/? W/dalvikvm: VFY: unable to resolve interface method 18258: Landroid/view/Window$Callback;.onWindowStartingActionMode (Landroid/view/ActionMode$Callback;I)Landroid/view/ActionMode;

05-05 17:41:16.770 10095-10095/? D/dalvikvm: VFY: replacing opcode 0x72 at 0x0002

05-05 17:41:16.782 10095-10098/? D/dalvikvm: GC_CONCURRENT freed 169K, 12% free 2684K/3020K, paused 2ms+0ms, total 5ms

05-05 17:41:16.786 10095-10095/? I/AppCompatViewInflater: app:theme is now deprecated. Please move to using android:theme instead.

05-05 17:41:16.786 10095-10095/? I/dalvikvm: Could not find method android.content.res.TypedArray.getChangingConfigurations, referenced from method android.support.v7.widget.TintTypedArray.getChangingConfigurations

05-05 17:41:16.786 10095-10095/? W/dalvikvm: VFY: unable to resolve virtual method 522: Landroid/content/res/TypedArray;.getChangingConfigurations ()I

05-05 17:41:16.786 10095-10095/? D/dalvikvm: VFY: replacing opcode 0x6e at 0x0002

05-05 17:41:16.790 10095-10095/? I/dalvikvm: Could not find method android.content.res.TypedArray.getType, referenced from method android.support.v7.widget.TintTypedArray.getType

05-05 17:41:16.790 10095-10095/? W/dalvikvm: VFY: unable to resolve virtual method 544: Landroid/content/res/TypedArray;.getType (I)I

05-05 17:41:16.790 10095-10095/? D/dalvikvm: VFY: replacing opcode 0x6e at 0x0002

05-05 17:41:16.798 10095-10095/? D/dalvikvm: GC_FOR_ALLOC freed 37K, 10% free 2814K/3120K, paused 3ms, total 3ms

05-05 17:41:16.798 10095-10095/? I/dalvikvm-heap: Grow heap (frag case) to 3.981MB for 1127532-byte allocation

05-05 17:41:16.802 10095-10104/? D/dalvikvm: GC_FOR_ALLOC freed <1K, 8% free 3914K/4224K, paused 3ms, total 3ms

05-05 17:41:16.806 10095-10098/? D/dalvikvm: GC_CONCURRENT freed <1K, 8% free 3914K/4224K, paused 0ms+0ms, total 2ms

05-05 17:41:16.834 10095-10098/? D/dalvikvm: GC_CONCURRENT freed 159K, 8% free 4153K/4480K, paused 2ms+0ms, total 5ms

05-05 17:41:16.846 10095-10095/? I/CURRENT_LANGUAGE: 1

05-05 17:41:16.850 10095-10095/? D/AndroidRuntime: Shutting down VM

05-05 17:41:16.850 10095-10095/? W/dalvikvm: threadid=1: thread exiting with uncaught exception (group=0xa4b60648)

05-05 17:41:16.850 10095-10095/? E/AndroidRuntime: FATAL EXCEPTION: main

05-05 17:41:16.850 10095-10095/? E/AndroidRuntime: java.lang.RuntimeException: Unable to start activity ComponentInfo{com.blog.waiyanhein.mmfashion.mmfashion/com.blog.waiyanhein.mmfashion.mmfashion.MainActivity}: android.os.NetworkOnMainThreadException

05-05 17:41:16.850 10095-10095/? E/AndroidRuntime: at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2211)

05-05 17:41:16.850 10095-10095/? E/AndroidRuntime: at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2261)

05-05 17:41:16.850 10095-10095/? E/AndroidRuntime: at android.app.ActivityThread.access$600(ActivityThread.java:141)

05-05 17:41:16.850 10095-10095/? E/AndroidRuntime: at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1256)

05-05 17:41:16.850 10095-10095/? E/AndroidRuntime: at android.os.Handler.dispatchMessage(Handler.java:99)

05-05 17:41:16.850 10095-10095/? E/AndroidRuntime: at android.os.Looper.loop(Looper.java:137)

05-05 17:41:16.850 10095-10095/? E/AndroidRuntime: at android.app.ActivityThread.main(ActivityThread.java:5103)

05-05 17:41:16.850 10095-10095/? E/AndroidRuntime: at java.lang.reflect.Method.invokeNative(Native Method)

05-05 17:41:16.850 10095-10095/? E/AndroidRuntime: at java.lang.reflect.Method.invoke(Method.java:525)

05-05 17:41:16.850 10095-10095/? E/AndroidRuntime: at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:737)

05-05 17:41:16.850 10095-10095/? E/AndroidRuntime: at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:553)

05-05 17:41:16.850 10095-10095/? E/AndroidRuntime: at dalvik.system.NativeStart.main(Native Method)

05-05 17:41:16.850 10095-10095/? E/AndroidRuntime: Caused by: android.os.NetworkOnMainThreadException

05-05 17:41:16.850 10095-10095/? E/AndroidRuntime: at android.os.StrictMode$AndroidBlockGuardPolicy.onNetwork(StrictMode.java:1133)

05-05 17:41:16.850 10095-10095/? E/AndroidRuntime: at libcore.io.BlockGuardOs.connect(BlockGuardOs.java:84)

05-05 17:41:16.850 10095-10095/? E/AndroidRuntime: at libcore.io.IoBridge.connectErrno(IoBridge.java:127)

05-05 17:41:16.850 10095-10095/? E/AndroidRuntime: at libcore.io.IoBridge.connect(IoBridge.java:112)

05-05 17:41:16.850 10095-10095/? E/AndroidRuntime: at java.net.PlainSocketImpl.connect(PlainSocketImpl.java:192)

05-05 17:41:16.850 10095-10095/? E/AndroidRuntime: at java.net.PlainSocketImpl.connect(PlainSocketImpl.java:459)

05-05 17:41:16.850 10095-10095/? E/AndroidRuntime: at java.net.Socket.connect(Socket.java:842)

05-05 17:41:16.850 10095-10095/? E/AndroidRuntime: at libcore.net.http.HttpConnection.<init>(HttpConnection.java:76)

05-05 17:41:16.850 10095-10095/? E/AndroidRuntime: at libcore.net.http.HttpConnection.<init>(HttpConnection.java:50)

05-05 17:41:16.850 10095-10095/? E/AndroidRuntime: at libcore.net.http.HttpConnection$Address.connect(HttpConnection.java:340)

05-05 17:41:16.850 10095-10095/? E/AndroidRuntime: at libcore.net.http.HttpConnectionPool.get(HttpConnectionPool.java:87)

05-05 17:41:16.850 10095-10095/? E/AndroidRuntime: at libcore.net.http.HttpConnection.connect(HttpConnection.java:128)

05-05 17:41:16.850 10095-10095/? E/AndroidRuntime: at libcore.net.http.HttpEngine.openSocketConnection(HttpEngine.java:316)

05-05 17:41:16.850 10095-10095/? E/AndroidRuntime: at libcore.net.http.HttpEngine.connect(HttpEngine.java:311)

05-05 17:41:16.850 10095-10095/? E/AndroidRuntime: at libcore.net.http.HttpEngine.sendSocketRequest(HttpEngine.java:290)

05-05 17:41:16.850 10095-10095/? E/AndroidRuntime: at libcore.net.http.HttpEngine.sendRequest(HttpEngine.java:240)

05-05 17:41:16.850 10095-10095/? E/AndroidRuntime: at libcore.net.http.HttpURLConnectionImpl.connect(HttpURLConnectionImpl.java:81)

05-05 17:41:16.850 10095-10095/? E/AndroidRuntime: at com.blog.waiyanhein.mmfashion.model.CommonHelper.ConvertUrlToBitmap(CommonHelper.java:595)

05-05 17:41:16.850 10095-10095/? E/AndroidRuntime: at com.blog.waiyanhein.mmfashion.mmfashion.MainActivity.addCategoriesToMenu(MainActivity.java:345)

05-05 17:41:16.850 10095-10095/? E/AndroidRuntime: at com.blog.waiyanhein.mmfashion.mmfashion.MainActivity.bindCategoryMenu(MainActivity.java:376)

05-05 17:41:16.850 10095-10095/? E/AndroidRuntime: at com.blog.waiyanhein.mmfashion.mmfashion.MainActivity.onCreate(MainActivity.java:101)

05-05 17:41:16.850 10095-10095/? E/AndroidRuntime: at android.app.Activity.performCreate(Activity.java:5133)

05-05 17:41:16.850 10095-10095/? E/AndroidRuntime: at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1087)

05-05 17:41:16.850 10095-10095/? E/AndroidRuntime: at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2175)

05-05 17:41:16.850 10095-10095/? E/AndroidRuntime: at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2261)

05-05 17:41:16.850 10095-10095/? E/AndroidRuntime: at android.app.ActivityThread.access$600(ActivityThread.java:141)

05-05 17:41:16.850 10095-10095/? E/AndroidRuntime: at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1256)

05-05 17:41:16.850 10095-10095/? E/AndroidRuntime: at android.os.Handler.dispatchMessage(Handler.java:99)

05-05 17:41:16.850 10095-10095/? E/AndroidRuntime: at android.os.Looper.loop(Looper.java:137)

05-05 17:41:16.850 10095-10095/? E/AndroidRuntime: at android.app.ActivityThread.main(ActivityThread.java:5103)

05-05 17:41:16.850 10095-10095/? E/AndroidRuntime: at java.lang.reflect.Method.invokeNative(Native Method)

05-05 17:41:16.850 10095-10095/? E/AndroidRuntime: at java.lang.reflect.Method.invoke(Method.java:525)

05-05 17:41:16.850 10095-10095/? E/AndroidRuntime: at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:737)

05-05 17:41:16.850 10095-10095/? E/AndroidRuntime: at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:553)

05-05 17:41:16.850 10095-10095/? E/AndroidRuntime: at dalvik.system.NativeStart.main(Native Method)

So please why is that happening and how can I fix that? How can I convert url to bitmap?

I also tried this way

public static Bitmap ConvertUrlToBitmap(String src)

{

try{

URL url = new URL(src);

Bitmap image = BitmapFactory.decodeStream(url.openConnection().getInputStream());

return image;

}

catch (IOException e)

{

return null;

}

}

网友答案:

You are trying to run network-consuming task in your main thread (what may prevent UI from being refreshed - that's why Android is complaining).

You should start an AsyncTask which you can use to download your image and return in dedicated callback method.

For cases like this, personally, I am using Picasso library. With this tool you can simplify your issue to just few steps as described here.

网友答案:

You are trying to connect online and doing network task. All network tasks must be done in a separate thread.

Give this a try:

private Bitmap bitmap;

private class ConvertUrlToBitmap extends AsyncTask<String, Long, Boolean> {
    @Override
    protected Boolean doInBackground(String... params) {
        try {
            URL url = new URL(params[0]);
            bitmap = BitmapFactory.decodeStream(url.openConnection().getInputStream());
            return true;
        } catch (Exception e) {
            Log.e(TAG, e.toString());
            return false;
        }
    }

    @Override
    protected void onPostExecute(Boolean aBoolean) {
        super.onPostExecute(aBoolean);
        if(aBoolean) {
            // download was successful
            // if you want to update your UI, make sure u do it on main thread. like this:
            MyActivity.this.runOnUiThread(new Runnable() {
                @Override
                public void run() {
                    // update UI here
                }
            });
        } else {
            // download failed
        }
    }
}

Then on your button click or when you want to download it, just call this:

new ConvertUrlToBitmap().execute(src);

Hope this helps!

网友答案:

try put your code in a Thread.

And I think, you can use a WebView to display Url Image:

webView.loadUrl(urlImage)
网友答案:

Use AsyncTask for that purpose. You can give this a try.

  class GetImage extends AsyncTask<String, Void, Bitmap> {

    @Override
    protected void onPreExecute() {
        super.onPreExecute();
    }

    public Bitmap doInBackground(String... urls) {
        Bitmap map = null;
        try {
            URL url = new URL(urls[0]);
            HttpURLConnection connection =(HttpURLConnection)url.openConnection();
            connection.setDoInput(true);
            connection.connect();
            InputStream input = connection.getInputStream();
            map= BitmapFactory.decodeStream(input);


        } catch (Exception e) {

            e.printStackTrace();

        }

        return map;
    }

    protected void onPostExecute(Bitmap bMap) {


        try {
            if (!isCancelled()) {
                if (bMap != null) {
                   //set your image view here.

                }
            }
        }catch (Exception exception){
        exception.printStackTrace();
        }
    }

}
网友答案:

Write below code into your activity file after setContentView(R.layout.activity_your);

if (android.os.Build.VERSION.SDK_INT > 9) {
  StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitAll().build();
  StrictMode.setThreadPolicy(policy);
}  

And below import statement into your java file.

import android.os.StrictMode;
分享给朋友:
您可能感兴趣的文章:
随机阅读: