我正在尝试通过向 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&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;
}
}