我让ZXing使用了intent,但我真的很困惑如何使用输出并将其保存为字符串。
这是意图:
public void scan(View view) {
try {
Intent intent = new Intent("com.google.zxing.client.android.SCAN");
intent.putExtra("SCAN_MODE", "QR_CODE_MODE"); // "PRODUCT_MODE for bar codes
startActivityForResult(intent, 0);
}
catch (Exception e) {
Uri marketUri = Uri.parse("market://details?id=com.google.zxing.client.android");
Intent marketIntent = new Intent(Intent.ACTION_VIEW, marketUri);
startActivity(marketIntent);
}
}
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == 0) {
if (resultCode == RESULT_OK) {
String contents = data.getStringExtra("SCAN_RESULT");
}
if(resultCode == RESULT_CANCELED){
//handle cancel
}
}
}
尝试将其用作字符串:
<TextView
android:id="@+id/result"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="@string/"title_activity_on_activity_result"
android:layout_marginTop="45dp"
android:layout_alignParentTop="true"
android:layout_alignRight="@+id/button"
android:layout_alignEnd="@+id/button" />
最后是字符串:
<string name="app_name">TEST123</string>
<string name="hello_world">Hello world!</string>
<string name="action_settings">Settings</string>
<string name="button_scan">Scan</string>
<string name="title_activity_activity_result">ActivityResult</string>
<string name="title_activity_on_activity_result">onActivityResult</string>
例外:
EXCEPTION: main
java.lang.RuntimeException: Unable to resume activity
{com.JunkerDev.testfaggot/com.JunkerDev.testfaggot.MainActivity}:
java.lang.RuntimeException: Failure delivering result ResultInfo{who=null, request=0,
result=-1, data=Intent { act=com.google.zxing.client.android.SCAN flg=0x80000 (has
extras) }} to activity
{com.JunkerDev.testfaggot/com.JunkerDev.testfaggot.MainActivity}:
java.lang.NullPointerException
如何解决此问题?
答案 0 :(得分:1)
QR码中的文字位于局部变量contents
中。必须将其设置为TextView
的内容为result
的文字;在代码中,而不是在XML中。
为此,您应在活动中声明一名成员:
TextView mResult;
在onCreate()
之后,setContentView()
之后,将其绑定到TextView
:
mResult = (TextView) findViewById(R.id.result);
最后在onActivityResult()
:
if (resultCode == RESULT_OK) {
String contents = data.getStringExtra("SCAN_RESULT");
mResult.setText(contents);
}