Chimpanse
Chimpanse

Reputation: 350

How do I use a QR code result from ZXing as a string?

I got ZXing working using an intent, but I am really confused as how to use the output and save it as a string.

Here is the 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
        }
    }
}

And trying to use it as a string:

<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" />

And finally the strings:

<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:

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

How can I fix this problem?

Upvotes: 0

Views: 1628

Answers (1)

Gil Vegliach
Gil Vegliach

Reputation: 3562

The text in the QR code is in the local variable contents. This has to be set as the text of your TextView with id result; In code, not in XML.

To do so, you should declare a member in your Activity:

TextView mResult;

In onCreate(), after setContentView(), bind it to the TextView:

mResult = (TextView) findViewById(R.id.result);

And finally in onActivityResult():

if (resultCode == RESULT_OK) {
    String contents = data.getStringExtra("SCAN_RESULT");
    mResult.setText(contents);
}

Upvotes: 1

Related Questions