Warning: file_get_contents(/data/phpspider/zhask/data//catemap/5/url/2.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Android 在NetworkOnMainThreadException中将url转换为位图_Android_Url_Bitmap - Fatal编程技术网

Android 在NetworkOnMainThreadException中将url转换为位图

Android 在NetworkOnMainThreadException中将url转换为位图,android,url,bitmap,Android,Url,Bitmap,我想将某些URL中的图像动态添加到线性布局中。运行代码时,出现错误,无法启动活动 ComponentInfo:android.os.NetworkOnMainThreadException位于 com.example.star.example.CompinfoActivity.getBitmapFromURLCompinfoActivity.java:70 位于com.example.star.example.CompinfoActivity.insertPhotoCompinfoActivit

我想将某些URL中的图像动态添加到线性布局中。运行代码时,出现错误,无法启动活动


ComponentInfo:android.os.NetworkOnMainThreadException位于 com.example.star.example.CompinfoActivity.getBitmapFromURLCompinfoActivity.java:70 位于com.example.star.example.CompinfoActivity.insertPhotoCompinfoActivity.java:50 在com.example.star.example.CompinfoActivity.onCreateComInfoActivity.java:38

请帮忙。这是我下面活动的代码

public class CompinfoActivity extends AppCompatActivity {

Dialog dialog;
LinearLayout myGallery;
@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_compinfo);

    dialog = new Dialog(this);
    dialog.requestWindowFeature(Window.FEATURE_NO_TITLE);
    dialog.setContentView(R.layout.activity_compinfopopup);
    dialog.getWindow().getAttributes().width = AbsListView.LayoutParams.MATCH_PARENT;
    dialog.getWindow().getAttributes().height = AbsListView.LayoutParams.WRAP_CONTENT;
    dialog.show();

    myGallery = (LinearLayout) dialog.findViewById(R.id.mygallery);
    myGallery.addView(insertPhoto("http://example.com/a.png"));
    myGallery.addView(insertPhoto("http://example.com/b.png"));
    myGallery.addView(insertPhoto("http://example.com/c.png"));
    myGallery.addView(insertPhoto("http://example.com/d.png"));
    new MyTask().execute();



}

View insertPhoto(String path){
    Bitmap bm;
    bm =  getBitmapFromURL(path);
    LinearLayout layout = new LinearLayout(getApplicationContext());
    layout.setLayoutParams(new AbsListView.LayoutParams(250, 250));
    layout.setGravity(Gravity.CENTER);

    ImageView imageView = new ImageView(getApplicationContext());
    imageView.setLayoutParams(new AbsListView.LayoutParams(220, 220));
    imageView.setScaleType(ImageView.ScaleType.CENTER_CROP);
    imageView.setImageBitmap(bm);

    layout.addView(imageView);
    return layout;
}


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();
        Bitmap myBitmap = BitmapFactory.decodeStream(input);
        return myBitmap;
    } catch (IOException e) {
        e.printStackTrace();
        return null;
    }
}
试试这个

URL url = new URL("http://....");
Bitmap image = BitmapFactory.decodeStream(url.openConnection().getInputStream()); 
只需替换你的Url,它对我有用

试试这个

URL url = new URL("http://....");
Bitmap image = BitmapFactory.decodeStream(url.openConnection().getInputStream()); 

只要替换你的Url它对我有用

你不应该像ankit说的那样在主线程中进行任何网络调用。你用OnCreate方法编写了所有内容。请改用

我建议你用截击或射门


直接从服务器显示图像。

您不应该像ankit说的那样在主线程中进行任何网络调用。您用OnCreate方法编写了所有内容。请改用

我建议你用截击或射门


直接从服务器显示图像。

您不能在UI主线程上进行任何网络调用。实现如下所示的异步任务并调用

new LoadImage(imageView).execute()
异步任务实现::

class LoadImage extends AsyncTask<Object, Void, Bitmap>{

    private ImageView imv;
    private String path;

    public LoadImage(ImageView imv) {
         this.imv = imv;
         this.path = imv.getTag().toString();
    }

@Override
protected Bitmap doInBackground(Object... params) {
    Bitmap bitmap = null;
    File file = new File( 
            Environment.getExternalStorageDirectory().getAbsolutePath() + path);

    if(file.exists()){
        bitmap = BitmapFactory.decodeFile(file.getAbsolutePath());
    }

    return bitmap;
}
@Override
protected void onPostExecute(Bitmap result) {
    if (!imv.getTag().toString().equals(path)) {
           /* The path is not same. This means that this
              image view is handled by some other async task. 
              We don't do anything and return. */
           return;
    }

    if(result != null && imv != null){
        imv.setVisibility(View.VISIBLE);
        imv.setImageBitmap(result);
    }
}

}您不能在UI主线程上进行任何网络调用。实现如下所示的异步任务并调用

new LoadImage(imageView).execute()
异步任务实现::

class LoadImage extends AsyncTask<Object, Void, Bitmap>{

    private ImageView imv;
    private String path;

    public LoadImage(ImageView imv) {
         this.imv = imv;
         this.path = imv.getTag().toString();
    }

@Override
protected Bitmap doInBackground(Object... params) {
    Bitmap bitmap = null;
    File file = new File( 
            Environment.getExternalStorageDirectory().getAbsolutePath() + path);

    if(file.exists()){
        bitmap = BitmapFactory.decodeFile(file.getAbsolutePath());
    }

    return bitmap;
}
@Override
protected void onPostExecute(Bitmap result) {
    if (!imv.getTag().toString().equals(path)) {
           /* The path is not same. This means that this
              image view is handled by some other async task. 
              We don't do anything and return. */
           return;
    }

    if(result != null && imv != null){
        imv.setVisibility(View.VISIBLE);
        imv.setImageBitmap(result);
    }
}
}

只需执行以下操作-

public class MyAsync extends AsyncTask<Void, Void, Bitmap>{

    @Override
    protected Bitmap doInBackground(Void... params) {

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

    }
}
MyAsync obj = new MyAsync(){

        @Override
        protected void onPostExecute(Bitmap bmp) {
            super.onPostExecute(bmp);

            Bitmap bm = bmp;
            LinearLayout layout = new LinearLayout(getApplicationContext());
            layout.setLayoutParams(new AbsListView.LayoutParams(250, 250));
            layout.setGravity(Gravity.CENTER);

            ImageView imageView = new ImageView(getApplicationContext());
            imageView.setLayoutParams(new AbsListView.LayoutParams(220, 220));
            imageView.setScaleType(ImageView.ScaleType.CENTER_CROP);
            imageView.setImageBitmap(bm);

            layout.addView(imageView);
        }
    };
然后最后执行AsynTask-

obj.execute();
只需按以下步骤操作即可-

public class MyAsync extends AsyncTask<Void, Void, Bitmap>{

    @Override
    protected Bitmap doInBackground(Void... params) {

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

    }
}
MyAsync obj = new MyAsync(){

        @Override
        protected void onPostExecute(Bitmap bmp) {
            super.onPostExecute(bmp);

            Bitmap bm = bmp;
            LinearLayout layout = new LinearLayout(getApplicationContext());
            layout.setLayoutParams(new AbsListView.LayoutParams(250, 250));
            layout.setGravity(Gravity.CENTER);

            ImageView imageView = new ImageView(getApplicationContext());
            imageView.setLayoutParams(new AbsListView.LayoutParams(220, 220));
            imageView.setScaleType(ImageView.ScaleType.CENTER_CROP);
            imageView.setImageBitmap(bm);

            layout.addView(imageView);
        }
    };
然后最后执行AsynTask-

obj.execute();

要在应用程序中显示图片,请将图片下载到存储器中,然后将其显示出来

您可以通过搜索如何下载文件、编写OnDownloadCompleteListener来获得答案


并在每次下载图片时重新加载imageView。

要在应用程序中显示图片,请将图片下载到存储器中,然后再显示

您可以通过搜索如何下载文件、编写OnDownloadCompleteListener来获得答案


并在每次下载pic时重新加载imageView。

更改insertPhotoString路径方法,如下所示:

View insertPhoto(String path){   
LinearLayout layout = new LinearLayout(getApplicationContext());
layout.setLayoutParams(new AbsListView.LayoutParams(250, 250));
layout.setGravity(Gravity.CENTER);

ImageView imageView = new ImageView(getApplicationContext());
imageView.setLayoutParams(new AbsListView.LayoutParams(220, 220));
imageView.setScaleType(ImageView.ScaleType.CENTER_CROP);    

  //Download and display image
        new AsyncTask<String, Void, Bitmap>(){


            @Override
            protected Bitmap doInBackground(String... urls) {
                 String url = urls[0];

                Bitmap mIcon11 = null;
                try {


                   HttpURLConnection connection = (HttpURLConnection) url.openConnection();
                   connection.setDoInput(true);
                   connection.connect();
                   InputStream input = connection.getInputStream();
                   mIcon11 = BitmapFactory.decodeStream(input);



                } catch (Exception e) {
                    Log.e("Error for image ", e.getMessage());
                    e.printStackTrace();
                    mIcon11 = null;
                }
                return mIcon11;
            }


            protected void onPostExecute(Bitmap result) {
                if(result!= null){
                    imageView.setImageBitmap(null);
                    imageView.setImageBitmap(result);                       

                }

            }
        }.execute(path);

layout.addView(imageView);
return layout;
}


希望这有帮助。

按如下方式更改insertPhotoString路径方法:

View insertPhoto(String path){   
LinearLayout layout = new LinearLayout(getApplicationContext());
layout.setLayoutParams(new AbsListView.LayoutParams(250, 250));
layout.setGravity(Gravity.CENTER);

ImageView imageView = new ImageView(getApplicationContext());
imageView.setLayoutParams(new AbsListView.LayoutParams(220, 220));
imageView.setScaleType(ImageView.ScaleType.CENTER_CROP);    

  //Download and display image
        new AsyncTask<String, Void, Bitmap>(){


            @Override
            protected Bitmap doInBackground(String... urls) {
                 String url = urls[0];

                Bitmap mIcon11 = null;
                try {


                   HttpURLConnection connection = (HttpURLConnection) url.openConnection();
                   connection.setDoInput(true);
                   connection.connect();
                   InputStream input = connection.getInputStream();
                   mIcon11 = BitmapFactory.decodeStream(input);



                } catch (Exception e) {
                    Log.e("Error for image ", e.getMessage());
                    e.printStackTrace();
                    mIcon11 = null;
                }
                return mIcon11;
            }


            protected void onPostExecute(Bitmap result) {
                if(result!= null){
                    imageView.setImageBitmap(null);
                    imageView.setImageBitmap(result);                       

                }

            }
        }.execute(path);

layout.addView(imageView);
return layout;
}


希望这有帮助。

在android中调用此方法将Url转换为位图

public static Bitmap getBitmapFromURL(String url) {
        try {
            URL url = new URL(url);
            HttpURLConnection connection = (HttpURLConnection) url.openConnection();
            connection.setDoInput(true);
            connection.connect();
            InputStream input = connection.getInputStream();
            Bitmap bitmapFrmUrl = BitmapFactory.decodeStream(input);
            return bitmapFrmUrl;
        } catch (IOException e) {
            e.printStackTrace();
            return null;
        }
    }

别忘了在AndroidManifest.xml中添加INTERNET权限调用此方法将Url转换为android中的位图

public static Bitmap getBitmapFromURL(String url) {
        try {
            URL url = new URL(url);
            HttpURLConnection connection = (HttpURLConnection) url.openConnection();
            connection.setDoInput(true);
            connection.connect();
            InputStream input = connection.getInputStream();
            Bitmap bitmapFrmUrl = BitmapFactory.decodeStream(input);
            return bitmapFrmUrl;
        } catch (IOException e) {
            e.printStackTrace();
            return null;
        }
    }

别忘了在AndroidManifest.xml中添加INTERNET权限。您应该在bcakground线程中定义获取位图代码或使用异步任务您应该在bcakground线程中定义获取位图代码或使用异步任务task@Ashish:很高兴它帮助了你:请投票。@Ashish:很高兴它帮助了你:请投票upvote.android.os.NetworkOnMainThreadException android.os.NetworkOnMainThreadException