如何解析此URL以将其正确设置为imageview的源?

时间:2012-07-16 18:17:56

标签: android imageview

如何解析此网址

http://ioe.edu.np/exam/notices/8560Result%20Diploma%20I_I.jpg

正确,以便它可以用作imageview的来源。我尝试使用Uri.encode()对其进行编码,但这没有帮助。

以下是我所指的从url加载图片的代码。从Android, Make an image at a URL equal to ImageView's image

获得
public class MainActivity extends Activity {

//  String imageUrl1 = "http://java.sogeti.nl/JavaBlog/wp-content/uploads/2009/04/android_icon_256.png";

String imageUrl = Uri.encode("http://ioe.edu.np/exam/notices/8560Result Diploma I_I.jpg");

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

    try {
        ImageView i = (ImageView) findViewById(R.id.imageView1);
        Bitmap bitmap = BitmapFactory.decodeStream((InputStream) new URL(
                imageUrl).getContent());
        i.setImageBitmap(bitmap);
    } catch (MalformedURLException e) {
        e.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
    }

}

}

请帮助我,还要注意我无法控制图像文件的名称,因此我必须找到一种方法,以便在imageview中正确加载。如果我用imageUrl1替换imageUrl,那么图像就会加载。但是对于imageUrl,似乎是空间被编码为html实体的问题。请帮帮我。

谢谢。

2 个答案:

答案 0 :(得分:1)

使用

String imageUrl ="http://ioe.edu.np/exam/notices/8560Result Diploma I_I.jpg";
    imageUrl =imageUrl .replaceAll(" ", "%20");

示例代码

String imageUrl ="http://ioe.edu.np/exam/notices/8560Result Diploma I_I.jpg";
    imageUrl =imageUrl .replaceAll(" ", "%20");
    try {
        Bitmap bitmap = BitmapFactory.decodeStream((InputStream) new URL(
                imageUrl).getContent());

        ImageView im=new ImageView(this);
        im.setImageBitmap(bitmap);
        setContentView(im);
    } catch (MalformedURLException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    } catch (IOException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }

答案 1 :(得分:0)

此代码适用于我的情况,

ImageView i = (ImageView) findViewById(R.id.imageView1);

try {
        URL url = new URL("http://ioe.edu.np/exam/notices/8560Result%20Diploma%20I_I.jpg");
        HttpURLConnection connection = (HttpURLConnection) url.openConnection();
        connection.setDoInput(true);
        connection.connect();
        InputStream input = connection.getInputStream();
        Bitmap myBitmap = BitmapFactory.decodeStream(input);
        i.setImageBitmap(myBitmap);
    } catch (IOException e) {
        e.printStackTrace();
    }

还在清单文件中添加权限,

<uses-permission android:name="android.permission.INTERNET"/>

修改

您也可以使用UrlEncoder

String urlString = URLEncoder.encode("http://ioe.edu.np/exam/notices/8560Result Diploma I_I.jpg");
url = new URL(urlString);