2

在我的应用程序中得到android.os.NetworkOnMainThreadException. 我正在尝试从 url 获取图像,当时我得到了这个Exception。如果我在 2.2 中运行应用程序,它工作正常,但如果我在 4.0 中运行,则会出现异常。

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;
}

我收到错误

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

在这一行请帮我解决这个问题

我使用了 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();
    }
}

我在这一行遇到错误:

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

日志猫:

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)
4

4 回答 4

16

onPostExecute和应用程序的运行onPreExecute方法。方法运行到另一个线程中,这意味着您应该将图像下载到方法中。Asynctaskmain threaddoInBackgrounddoInBackground

例如,如果您想从某个 URL 下载图像,然后将该图像放入ImageView

称呼:

new DownloadImageTask(yourImageView).execute(yourURL);

其中 asynctask 类是:

    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();
    }
}
于 2012-09-27T06:53:00.323 回答
0

获取图像也应该在方法中以某种方式完成doInBackground......onPostExecute就像在主线程中而不是在背景中一样。

于 2012-09-27T06:49:54.537 回答
0

试试这个代码

URL urll = new URL(url);
InputStream in = (InputStream) urll.openConnection().getInputStream();
bitmap = BitmapFactory.decodeStream(in);
于 2012-09-27T06:50:14.507 回答
0

尝试这个:

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"));
于 2013-08-28T05:54:40.033 回答