在安卓中从URL加载图库图片?

5

我想创建一个图片库,从url获取图片..这是我的代码,但不工作..

 public class ImagesActivity extends Activity
 {    

private String[] imageIDs= {"http://lh5.ggpht.com/_mrb7w4gF8Ds/TCpetKSqM1I/AAAAAAAAD2c/Qef6Gsqf12Y/s144-c/_DSC4374%20copy.jpg",  
"http://lh5.ggpht.com/_Z6tbBnE-swM/TB0CryLkiLI/AAAAAAAAVSo/n6B78hsDUz4/s144-c/_DSC3454.jpg",  
"http://lh3.ggpht.com/_GEnSvSHk4iE/TDSfmyCfn0I/AAAAAAAAF8Y/cqmhEoxbwys/s144-c/_MG_3675.jpg",  
"http://lh6.ggpht.com/_Nsxc889y6hY/TBp7jfx-cgI/AAAAAAAAHAg/Rr7jX44r2Gc/s144-c/IMGP9775a.jpg"
};

@Override    
public void onCreate(Bundle savedInstanceState) 
{
    super.onCreate(savedInstanceState);
    setContentView(R.layout.displayview);

    Gallery gallery = (Gallery) findViewById(R.id.gallery1);

    gallery.setAdapter(new ImageAdapter(this));        
    gallery.setOnItemClickListener(new OnItemClickListener() 
    {
        public void onItemClick(AdapterView parent, View v, int position, long id) 
        {                
 //                             Toast.makeText(getBaseContext(), "pic" + (position + 1) + " selected", Toast.LENGTH_SHORT).show();
                          //---display the images selected---
                            ImageView imageView = (ImageView) findViewById(R.id.image1);                
                            imageView.setImageResource(imageIDs[position]);
        }
    });

}


public class ImageAdapter extends BaseAdapter 
{
    private Context context;
    private int itemBackground;

    public ImageAdapter(Context c) 
    {
        context = c;
        //---setting the style---
        TypedArray a = obtainStyledAttributes(R.styleable.Gallery1);
        itemBackground = a.getResourceId(
            R.styleable.Gallery1_android_galleryItemBackground, 0);
        a.recycle();                    
    }

    //---returns the number of images---
    public int getCount() {
        return imageIDs.length;
    }

    //---returns the ID of an item--- 
    public Object getItem(int position) {
        return position;
    }            

    public long getItemId(int position) {
        return position;
    }

    //---returns an ImageView view---
    public View getView(int position, View convertView, ViewGroup parent) {
        ImageView imageView = new ImageView(context);
        imageView.setImageResource(imageIDs[position]);
        imageView.setScaleType(ImageView.ScaleType.FIT_XY);
        imageView.setLayoutParams(new Gallery.LayoutParams(150, 120));
        imageView.setBackgroundResource(itemBackground);
        return imageView;
    }
}    

}

ViewsActivity.java

 public class ViewsActivity extends Activity 
 {
/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
 //        setContentView(R.layout.main);

    startActivity(new Intent(this, ImagesActivity.class));

  }
 }

错误在于我无法将imageView.setImageResource(imageIDs [position])用于字符串...请帮忙解决?

1
你需要从URL获取图像,然后将该图像设置为“ImageResource”吗? - IAmGroot
无法从URL获取图像。 - Kumar
3个回答

9

您需要解码来自链接的图像,例如:

URL url = new URL("load your URL");
Bitmap bmp = BitmapFactory.decodeStream(url.openConnection().getInputStream());
img_downloaded.setImageBitmap(bmp);

更新:

我修改了您的代码,您可以尝试使用下面这个:

public class MainActivity extends Activity {

    private String[] imageIDs = {
            "http://lh5.ggpht.com/_mrb7w4gF8Ds/TCpetKSqM1I/AAAAAAAAD2c/Qef6Gsqf12Y/s144-c/_DSC4374%20copy.jpg",
            "http://lh5.ggpht.com/_Z6tbBnE-swM/TB0CryLkiLI/AAAAAAAAVSo/n6B78hsDUz4/s144-c/_DSC3454.jpg",
            "http://lh3.ggpht.com/_GEnSvSHk4iE/TDSfmyCfn0I/AAAAAAAAF8Y/cqmhEoxbwys/s144-c/_MG_3675.jpg",
            "http://lh6.ggpht.com/_Nsxc889y6hY/TBp7jfx-cgI/AAAAAAAAHAg/Rr7jX44r2Gc/s144-c/IMGP9775a.jpg" };

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        Gallery gallery = (Gallery) findViewById(R.id.gallery1);

        gallery.setAdapter(new ImageAdapter(this));
        gallery.setOnItemClickListener(new OnItemClickListener() {
            public void onItemClick(AdapterView parent, View v, int position,
                    long id) {
                // Toast.makeText(getBaseContext(), "pic" + (position + 1) +
                // " selected", Toast.LENGTH_SHORT).show();
                // ---display the images selected---
                ImageView imageView = (ImageView) findViewById(R.id.imageview1);
                URL url = null;
                try {
                    url = new URL(imageIDs[position]);
                    Bitmap bmp = null;
                    try {
                        bmp = BitmapFactory.decodeStream(url
                                .openConnection().getInputStream());
                    } catch (IOException e) {
                        // TODO Auto-generated catch block
                        e.printStackTrace();
                    }
                    imageView.setImageBitmap(bmp);
                } catch (MalformedURLException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                }

            }
        });

    }

    public class ImageAdapter extends BaseAdapter {
        private Context context;
        private int itemBackground;

        public ImageAdapter(Context c) {
            context = c;
            // ---setting the style---
             TypedArray a = obtainStyledAttributes(R.styleable.Gallery1);
            itemBackground = a.getResourceId(
             R.styleable.Gallery1_android_galleryItemBackground, 0);
             a.recycle();
        }

        // ---returns the number of images---
        public int getCount() {
            return imageIDs.length;
        }

        // ---returns the ID of an item---
        public Object getItem(int position) {
            return position;
        }

        public long getItemId(int position) {
            return position;
        }

        // ---returns an ImageView view---
        public View getView(int position, View convertView, ViewGroup parent) {
            ImageView imageView = new ImageView(context);
            // imageView.setImageResource(imageIDs[position]);
            URL url;
            try {
                url = new URL(imageIDs[position]);
                Bitmap bmp = BitmapFactory.decodeStream(url.openConnection()
                        .getInputStream());
                imageView.setImageBitmap(bmp);
                imageView.setScaleType(ImageView.ScaleType.FIT_XY);
                imageView.setLayoutParams(new Gallery.LayoutParams(150, 120));
                imageView.setBackgroundResource(itemBackground);

            } catch (MalformedURLException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            } catch (IOException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
            return imageView;
        }
    }

}

activity_main.xml

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent" >

    <Gallery
        android:id="@+id/gallery1"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content" />

    <ImageView
        android:id="@+id/imageview1"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_below="@+id/gallery1" />


</RelativeLayout>

嗯,我们的答案看起来完全一样!+1 - IAmGroot
我使用了这段代码,我的布局包含了画廊和图像视图。它运行良好。 - Aerrow
它将显示空白页面。 - Kumar
@user1597835:请查看已编辑的答案,我在这里添加了我的布局。您可以单独运行此代码,并告诉我代码中是否有任何问题。 - Aerrow
大家好, 我尝试了提出的解决方案,但是在以下代码行中出现了android.os.NetworkOnMainThreadException异常:url = new URL(imageIDs[position]);Bitmap bmp = BitmapFactory.decodeStream(url.openConnection() .getInputStream());有什么帮助吗? - Rana Osama
显示剩余5条评论

5
在 getView 方法中:
URL newurl = new URL(imageIDs[position]); //Your URL String.
Bitmap image = BitmapFactory.decodeStream(newurl.openConnection().getInputStream());  
imageView.setImageBitmap(image); 

使用try/catch包围异常的请求 - Kumar
然后将其包装在try和catch子句中。 :) 请参阅Aerrow对您的代码的修改,其中包括此内容。 - IAmGroot
那已经结束了,但问题是它会显示空白页面。 - Kumar
你在 Android Manifest 中设置了互联网权限吗?进行调试,看看你到了哪一步。你成功获取了图片吗?有任何 logcat 消息吗? - IAmGroot
感谢您的回答,我很抱歉。 - Kumar
@user1597835 不用担心。 :) 很高兴一切都解决了。 - IAmGroot

3

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接