android.os.NetworkOnMainThreadException

*爱你&永不变心* 提交于 2019-12-17 20:29:45

问题


In my application am getting android.os.NetworkOnMainThreadException. I am trying to get images from url at that time i am getting this Exception. If i run application in 2.2 it is working fine but if i run in 4.0 am getting exception.

public static Bitmap getBitmap(String url)
{
    Bitmap bitmap = null;

    try
    {
        // replace space with url encoded character.
        url = url.replace(" ", "%20");
        // System.out.println("url : " + url);
        URL urll = new URL(url);
        InputStream in = (InputStream) urll.getContent();
        bitmap = BitmapFactory.decodeStream(in);
    }
    catch ( MalformedURLException e )
    {
        e.printStackTrace();
    }
    catch ( IOException e )
    {
        e.printStackTrace();
    }

    if ( bitmap == null )
        bitmap = BitmapFactory.decodeResource(resources, R.drawable.noimage);

    return bitmap;
}

I'm getting error in

  InputStream in = (InputStream) urll.getContent(); 

in this line please help me to solve this issue

I used AsyncTask

private class RecipeDetail1Task extends AsyncTask<Long, Void, RecipeDetailBean>
{
    @Override
    protected void onPreExecute()
    {
        Log.i(TAG, "<<<<<<<<<<<<<onPreExecute>>>>>>>>>>>>>>>>>>>");

        btnViewRecipe.setEnabled(false);
        imgFree.setVisibility(View.GONE);
    }
    @Override
    protected RecipeDetailBean doInBackground(Long... params)
    {
        Log.i(TAG, "<<<<<<<<<<<<<doInBackground>>>>>>>>>>>>>>>>>>>");

        RecipeDetailBean bean = null;
        try
        {
            ParserUtil pu = new ParserUtil(ParserUtil.ResultControl.LIMITED);
            bean = pu.getRecipeDetail(params[0]);               
        }
        catch ( ParserConfigurationException e )
        {
            e.printStackTrace();
        }
        catch ( SAXException e )
        {
            e.printStackTrace();
        }

        return bean;
    }

    protected void onPostExecute(RecipeDetailBean result)
    {
        Log.i(TAG, "<<<<<<<<<<<<<onPostExecute>>>>>>>>>>>>>>>>>>>");



        Constant.recipeDetail = result; 
        if ( result == null )
        {
            Log.i(TAG, "<<<<<<<<<<<<<result == null>>>>>>>>>>>>>>>>>>>");
            toast.setText(getString(R.string.recipe_detail_not_present_message));
            toast.setDuration(Toast.LENGTH_LONG);
            toast.show();
            Constant.recipeDetail = new RecipeDetailBean();
            btnViewRecipe.setEnabled(false);
        }
        else
        {
            Log.i(TAG, "<<<<<<<<<<<<<result |= null>>>>>>>>>>>>>>>>>>>");
            //pb.setVisibility(View.INVISIBLE);
            btnViewRecipe.setEnabled(true);
            lblRecipeName.setText(result.getName());
            lblRecipeDesc.setText(result.getDescription());
            lblRecipeBy.setText(result.getAuthor());
            lblPostedOn.setText(result.getCreatedDate());

            String d=Integer.toString(result.getServedNumber());
            if(d==null)
            {
                lblServesNumber.setText("N/A");
                lblServesNumber1.setText("");
            }

            else if(result.getServedNumber()==0)
            {
                lblServesNumber.setText("N/A");
                lblServesNumber1.setText("");
            }
            else
            {
                lblServesNumber.setText(d);
                lblServesNumber1.setText(" Adult(s)");
            }
            if(Constant.recipeDetail.getFreeYN() == 1)
                imgFree.setVisibility(View.VISIBLE);

            //rbRecipeRating.setProgress((int) result.getRating());
            rbRecipeRating.setRating((float) ( (result.getRating() * 5) / 100 ));
            //Log.d("rating2", "" + (float) ( (result.getRating() * 5) / 100.0f ));
            result.setRecipeBitmap(Constant.getBitmap(result.getImageURL()));
            imgRecipe.setImageBitmap(result.getRecipeBitmap());
            imgRecipe.setVisibility(View.VISIBLE);
            //ImageLoader imageLoader = new ImageLoader(imgRecipe, pb, null);
            //imageLoader.execute(result.getImageURL());
        }

        btnViewRecipe.requestFocus();
    }
}

I'm getting error in this line:

 result.setRecipeBitmap(Constant.getBitmap(result.getImageURL()));

Logcat :

09-27 13:14:11.445: E/AndroidRuntime(1014): FATAL EXCEPTION: main
09-27 13:14:11.445: E/AndroidRuntime(1014): android.os.NetworkOnMainThreadException
09-27 13:14:11.445: E/AndroidRuntime(1014):     at android.os.StrictMode$AndroidBlockGuardPolicy.onNetwork(StrictMode.java:1084)
09-27 13:14:11.445: E/AndroidRuntime(1014):     at java.net.InetAddress.lookupHostByName(InetAddress.java:391)
09-27 13:14:11.445: E/AndroidRuntime(1014):     at java.net.InetAddress.getAllByNameImpl(InetAddress.java:242)
09-27 13:14:11.445: E/AndroidRuntime(1014):     at java.net.InetAddress.getAllByName(InetAddress.java:220)
09-27 13:14:11.445: E/AndroidRuntime(1014):     at libcore.net.http.HttpConnection.<init>(HttpConnection.java:71)
09-27 13:14:11.445: E/AndroidRuntime(1014):     at libcore.net.http.HttpConnection.<init>(HttpConnection.java:50)
09-27 13:14:11.445: E/AndroidRuntime(1014):     at libcore.net.http.HttpConnection$Address.connect(HttpConnection.java:351)
09-27 13:14:11.445: E/AndroidRuntime(1014):     at libcore.net.http.HttpConnectionPool.get(HttpConnectionPool.java:86)
09-27 13:14:11.445: E/AndroidRuntime(1014):     at libcore.net.http.HttpConnection.connect(HttpConnection.java:128)
09-27 13:14:11.445: E/AndroidRuntime(1014):     at libcore.net.http.HttpEngine.openSocketConnection(HttpEngine.java:308)
09-27 13:14:11.445: E/AndroidRuntime(1014):     at libcore.net.http.HttpEngine.connect(HttpEngine.java:303)
09-27 13:14:11.445: E/AndroidRuntime(1014):     at libcore.net.http.HttpEngine.sendSocketRequest(HttpEngine.java:282)
09-27 13:14:11.445: E/AndroidRuntime(1014):     at libcore.net.http.HttpEngine.sendRequest(HttpEngine.java:232)
09-27 13:14:11.445: E/AndroidRuntime(1014):     at libcore.net.http.HttpURLConnectionImpl.getResponse(HttpURLConnectionImpl.java:273)
09-27 13:14:11.445: E/AndroidRuntime(1014):     at libcore.net.http.HttpURLConnectionImpl.getInputStream(HttpURLConnectionImpl.java:168)
09-27 13:14:11.445: E/AndroidRuntime(1014):     at com.indianrecipes.beans.Constant.getBitmap(Constant.java:239)
09-27 13:14:11.445: E/AndroidRuntime(1014):     at com.indianrecipes.activities.RecipeDetail1Activity$RecipeDetail1Task.onPostExecute(RecipeDetail1Activity.java:376)
09-27 13:14:11.445: E/AndroidRuntime(1014):     at com.indianrecipes.activities.RecipeDetail1Activity$RecipeDetail1Task.onPostExecute(RecipeDetail1Activity.java:1)
09-27 13:14:11.445: E/AndroidRuntime(1014):     at android.os.AsyncTask.finish(AsyncTask.java:602)
09-27 13:14:11.445: E/AndroidRuntime(1014):     at android.os.AsyncTask.access$600(AsyncTask.java:156)
09-27 13:14:11.445: E/AndroidRuntime(1014):     at android.os.AsyncTask$InternalHandler.handleMessage(AsyncTask.java:615)
09-27 13:14:11.445: E/AndroidRuntime(1014):     at android.os.Handler.dispatchMessage(Handler.java:99)
09-27 13:14:11.445: E/AndroidRuntime(1014):     at android.os.Looper.loop(Looper.java:137)
09-27 13:14:11.445: E/AndroidRuntime(1014):     at android.app.ActivityThread.main(ActivityThread.java:4340)
09-27 13:14:11.445: E/AndroidRuntime(1014):     at java.lang.reflect.Method.invokeNative(Native Method)
09-27 13:14:11.445: E/AndroidRuntime(1014):     at java.lang.reflect.Method.invoke(Method.java:511)
09-27 13:14:11.445: E/AndroidRuntime(1014):     at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:784)
09-27 13:14:11.445: E/AndroidRuntime(1014):     at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:551)
09-27 13:14:11.445: E/AndroidRuntime(1014):     at dalvik.system.NativeStart.main(Native Method)

回答1:


onPostExecute and onPreExecute methods of Asynctask runs into main thread of application. doInBackground method runs into another thread, which means that you should download your image into doInBackground method.

For example if you want to download image from some URL and then put that image into ImageView:

call:

new DownloadImageTask(yourImageView).execute(yourURL);

where asynctask class is:

    private class DownloadImageTask extends AsyncTask<String, Void, Bitmap> {

    private ProgressDialog mDialog;
    private ImageView bmImage;

    public DownloadImageTask(ImageView bmImage) {
        this.bmImage = bmImage;
    }

    protected void onPreExecute() {

        mDialog = ProgressDialog.show(ChartActivity.this,"Please wait...", "Retrieving data ...", true);
    }

    protected Bitmap doInBackground(String... urls) {
        String urldisplay = urls[0];
        Bitmap mIcon11 = null;
        try {
            InputStream in = new java.net.URL(urldisplay).openStream();
            mIcon11 = BitmapFactory.decodeStream(in);
        } catch (Exception e) {
            Log.e("Error", "image download error");
            Log.e("Error", e.getMessage());
            e.printStackTrace();
        }
        return mIcon11;
    }

    protected void onPostExecute(Bitmap result) {
        //set image of your imageview
        bmImage.setImageBitmap(result);
        //close
        mDialog.dismiss();
    }
}



回答2:


Also getting the image should be done somehow in the doInBackground method..as doing it in the onPostExecute is like doing it in the main thread not in background..




回答3:


try this code

URL urll = new URL(url);
InputStream in = (InputStream) urll.openConnection().getInputStream();
bitmap = BitmapFactory.decodeStream(in);



回答4:


Try this:

AQuery aq = new AQuery(getActivity());
aq.id(view.findViewById(R.id.image)).image(imageUrl, true, true, 0,  0,
    new BitmapAjaxCallback() {
        @Override
        public void callback(String url, ImageView iv, Bitmap bm, AjaxStatus status) {
            iv.setImageBitmap(bm);
        }
    }.header("User-Agent", "android"));


来源:https://stackoverflow.com/questions/12615607/android-os-networkonmainthreadexception

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!