【发布时间】:2017-01-12 17:01:46
【问题描述】:
我正在尝试为我的应用生成二维码。用户将输入一些文本,数据将被传递到下一个将显示 QR 码的活动。
这是我的代码。
public class QRgenerator extends AppCompatActivity {
ImageView imageView;
String Qrcode;
public static final int WIDTH = 500;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_qrgenerator);
getID();
Intent intent = getIntent();
Qrcode = intent.getStringExtra("Data");
//creating thread to avoid ANR exception
Thread t = new Thread(new Runnable() {
@Override
public void run() {
//the message to be encoded in the qr code.
try {
synchronized (this) {
wait(5000);
//runonUIthread on the main thread
runOnUiThread(new Runnable() {
@Override
public void run() {
try {
Bitmap bitmap = null;
bitmap = encodeasBitmap(Qrcode);
imageView.setImageBitmap(bitmap);
} catch (WriterException e) {
e.printStackTrace();
;
} //end of catch block
} //end of rum method
});
}
} catch (InterruptedException e) {
e.printStackTrace();
}
}
});
t.start();
}
//method that returns the bitmap image of the QRcode.
public void getID() {
imageView = (ImageView) findViewById(R.id.imageView2);
}
public Bitmap encodeasBitmap(String str) throws WriterException {
BitMatrix result;
try {
result = new MultiFormatWriter().encode(str, BarcodeFormat.QR_CODE, WIDTH, WIDTH, null);
} catch (IllegalArgumentException e) {
//unsupported format
return null;
}
int h = result.getHeight();
int w = result.getWidth();
int[] pixels = new int[w * h];
for (int i = 0; i < h; i++) {
int offset = i * w;
for (int j = 0; j < w; j++) {
pixels[offset + j] = result.get(j, i)? R.color.black:R.color.white;
}
}
Bitmap bitmap = Bitmap.createBitmap(w, h, Bitmap.Config.ARGB_8888);
bitmap.setPixels(pixels, 0, 500, 0, 0, w, h);
return bitmap;
}
}
问题是当我按下按钮并转到下一个屏幕时,只出现白屏,并且图像视图中也没有二维码。可能是什么错误?
【问题讨论】:
-
除了
return null之外还要记录异常吗?