0

我正在尝试通过向 QR 生成器 API 发送 HTTP 请求并将图像放入 imageview 来在我的应用程序中生成 QR 码。然而,我只是得到一个空白屏幕。我尝试了几种不同的解决方案,但都没有找到。这是我正在使用的代码。我还在清单中添加了互联网权限

活动主.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"
    tools:context=".MainActivity" >

    <ImageView android:id="@+id/qrImageView"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_centerHorizontal="true"
        android:layout_centerVertical="true" />

</RelativeLayout>

MainActivity.java

public class MainActivity extends Activity {

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

        ImageView imageview = (ImageView) findViewById(R.id.qrImageView);

        String qrURL = "http://api.qrserver.com/v1/create-qr-code/?data=thisisatest&amp;size=300x300";
        String src = "QRGenerator";

        Drawable qrCode=null;
        try {
            qrCode = drawable_from_url(qrURL, src);
        } catch (MalformedURLException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        } 

        imageview.setImageDrawable(qrCode); 
    }

        Drawable drawable_from_url(String qurl, String src_name) throws MalformedURLException, IOException {
            URL url = new URL(qurl);
            HttpURLConnection connection = (HttpURLConnection) url.openConnection();
            InputStream is = connection.getInputStream();
            Drawable d = Drawable.createFromStream(is, src_name);
            return d;
        }

}
4

2 回答 2

1

您必须首先下载图像:

public static Bitmap loadBitmap(String url) {
    Bitmap bitmap = null;
    InputStream in = null;
    BufferedOutputStream out = null;

    try {
        in = new BufferedInputStream(new URL(url).openStream(), IO_BUFFER_SIZE);

        final ByteArrayOutputStream dataStream = new ByteArrayOutputStream();
        out = new BufferedOutputStream(dataStream, IO_BUFFER_SIZE);
        copy(in, out);
        out.flush();

        final byte[] data = dataStream.toByteArray();
        BitmapFactory.Options options = new BitmapFactory.Options();
        //options.inSampleSize = 1;

        bitmap = BitmapFactory.decodeByteArray(data, 0, data.length,options);
    } catch (IOException e) {
        Log.e(TAG, "Could not load Bitmap from: " + url);
    } finally {
        closeStream(in);
        closeStream(out);
    }

    return bitmap;
}

然后使用 Imageview.setImageBitmap 将位图设置到 ImageView

于 2012-11-25T00:11:28.243 回答
0

我已经解决了。我在没有互联网连接的模拟器上运行它,所以它显然无法联系 API。我在手机上运行它,它工作。我会把这个问题留给其他人参考。感谢您的输入

于 2012-11-29T11:47:53.373 回答