user2855792
user2855792

Reputation: 37

Getting NullPointerException in NFC-handling code

I got some code for handling NFC tags from StackOverflow but I'm getting a NullPointerException while running it:

public class MainActivity extends Activity {    
    NfcAdapter adapter;
    PendingIntent pendingIntent;
    IntentFilter writeTagFilters[];
    boolean writeMode;
    Tag mytag;
    Context ctx;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
        ctx = this;
        Button btnWrite = (Button) findViewById(R.id.button);
        final TextView plateno = (TextView)findViewById(R.id.plate_no);
        final TextView model = (TextView)findViewById(R.id.model);
        final TextView chasis = (TextView)findViewById(R.id.chasis_no);
        final TextView engine = (TextView)findViewById(R.id.engine_no);
        final TextView duedate = (TextView)findViewById(R.id.due_date);
        final TextView rotexno = (TextView)findViewById(R.id.rotex_no);

        btnWrite.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                try {
                    if (mytag == null) {
                        Toast.makeText(ctx, ctx.getString(R.string.error_detected), Toast.LENGTH_LONG ).show();
                    } else {
                        write(plateno.getText().toString(),mytag);
                        write(model.getText().toString(),mytag);
                        write(chasis.getText().toString(),mytag);
                        write(engine.getText().toString(),mytag);
                        write(duedate.getText().toString(),mytag);
                        write(rotexno.getText().toString(),mytag);
                        Toast.makeText(ctx, ctx.getString(R.string.ok_writing), Toast.LENGTH_LONG ).show();
                    }
                } catch (IOException e) {
                    Toast.makeText(ctx, ctx.getString(R.string.error_writing), Toast.LENGTH_LONG ).show();
                    e.printStackTrace();
                } catch (FormatException e) {
                    Toast.makeText(ctx, ctx.getString(R.string.error_writing) , Toast.LENGTH_LONG ).show();
                    e.printStackTrace();
                }
            }
        });
        adapter = NfcAdapter.getDefaultAdapter(this);
        pendingIntent = PendingIntent.getActivity(this, 0, new Intent(this, getClass()).addFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP), 0);
        IntentFilter tagDetected = new IntentFilter(NfcAdapter.ACTION_TAG_DISCOVERED);
        tagDetected.addCategory(Intent.CATEGORY_DEFAULT);
        writeTagFilters = new IntentFilter[] { tagDetected };
    }

    private void write(String text, Tag tag) throws IOException, FormatException {
        NdefRecord[] records = { createRecord(text) };
        NdefMessage  message = new NdefMessage(records);
        // Get an instance of Ndef for the tag.
        Ndef ndef = Ndef.get(tag);
        // Enable I/O
        ndef.connect();
        // Write the message
        ndef.writeNdefMessage(message);
        // Close the connection
        ndef.close();
    }

    private NdefRecord createRecord(String text) throws UnsupportedEncodingException {
        String lang       = "en";
        byte[] textBytes  = text.getBytes();
        byte[] langBytes  = lang.getBytes("US-ASCII");
        int    langLength = langBytes.length;
        int    textLength = textBytes.length;
        byte[] payload    = new byte[1 + langLength + textLength];
        // set status byte (see NDEF spec for actual bits)
        payload[0] = (byte) langLength;
        // copy langbytes and textbytes into payload
        System.arraycopy(langBytes, 0, payload, 1,              langLength);
        System.arraycopy(textBytes, 0, payload, 1 + langLength, textLength);
        NdefRecord recordNFC = new NdefRecord(NdefRecord.TNF_WELL_KNOWN,  NdefRecord.RTD_TEXT,  new byte[0], payload);
        return recordNFC;
    }

    @Override
    protected void onNewIntent(Intent intent){
        if (NfcAdapter.ACTION_TAG_DISCOVERED.equals(intent.getAction())) {
            mytag = intent.getParcelableExtra(NfcAdapter.EXTRA_TAG);    
            Toast.makeText(this, this.getString(R.string.ok_detection) + mytag.toString(), Toast.LENGTH_LONG ).show();
        }
    }

    @Override
    public void onPause(){
        super.onPause();
        WriteModeOff();
    }

    @Override
    public void onResume(){
        super.onResume();
        WriteModeOn();
    }

    private void WriteModeOn(){
        writeMode = true;
        adapter.enableForegroundDispatch(this, pendingIntent, writeTagFilters, null);
    }

    private void WriteModeOff(){
        writeMode = false;
        adapter.disableForegroundDispatch(this);
    }
}

This is the error message from LogCat:

04-11 14:21:15.020: E/AndroidRuntime(1512): FATAL EXCEPTION: main 04-11 14:21:15.020: E/AndroidRuntime(1512): Process: com.example.nfcwrite, PID: 1512 04-11 14:21:15.020: E/AndroidRuntime(1512): java.lang.RuntimeException: Unable to resume activity {com.example.nfcwrite/com.example.nfcwrite.MainActivity}: java.lang.NullPointerException 04-11 14:21:15.020: E/AndroidRuntime(1512): at android.app.ActivityThread.performResumeActivity(ActivityThread.java:2788) 04-11 14:21:15.020: E/AndroidRuntime(1512): at android.app.ActivityThread.handleResumeActivity(ActivityThread.java:2817) 04-11 14:21:15.020: E/AndroidRuntime(1512): at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2250) 04-11 14:21:15.020: E/AndroidRuntime(1512): at android.app.ActivityThread.access$800(ActivityThread.java:135) 04-11 14:21:15.020: E/AndroidRuntime(1512): at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1196) 04-11 14:21:15.020: E/AndroidRuntime(1512): at android.os.Handler.dispatchMessage(Handler.java:102) 04-11 14:21:15.020: E/AndroidRuntime(1512): at android.os.Looper.loop(Looper.java:136) 04-11 14:21:15.020: E/AndroidRuntime(1512): at android.app.ActivityThread.main(ActivityThread.java:5017) 04-11 14:21:15.020: E/AndroidRuntime(1512): at java.lang.reflect.Method.invokeNative(Native Method) 04-11 14:21:15.020: E/AndroidRuntime(1512): at java.lang.reflect.Method.invoke(Method.java:515) 04-11 14:21:15.020: E/AndroidRuntime(1512): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:779) 04-11 14:21:15.020: E/AndroidRuntime(1512): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:595) 04-11 14:21:15.020: E/AndroidRuntime(1512): at dalvik.system.NativeStart.main(Native Method) 04-11 14:21:15.020: E/AndroidRuntime(1512): Caused by: java.lang.NullPointerException 04-11 14:21:15.020: E/AndroidRuntime(1512): at com.example.nfcwrite.MainActivity.WriteModeOn(MainActivity.java:149) 04-11 14:21:15.020: E/AndroidRuntime(1512): at com.example.nfcwrite.MainActivity.onResume(MainActivity.java:144) 04-11 14:21:15.020: E/AndroidRuntime(1512): at android.app.Instrumentation.callActivityOnResume(Instrumentation.java:1192) 04-11 14:21:15.020: E/AndroidRuntime(1512): at android.app.Activity.performResume(Activity.java:5310) 04-11 14:21:15.020: E/AndroidRuntime(1512): at android.app.ActivityThread.performResumeActivity(ActivityThread.java:2778) 04-11 14:21:15.020: E/AndroidRuntime(1512): ... 12 more

Upvotes: 1

Views: 2140

Answers (2)

BlackPearl
BlackPearl

Reputation: 31

Please refer Android developer page for EnableForegroundDispatch

Calling WriteModeOn(); in onResume must be causing the issue. You can call this may be in onPostResume().

Make sure before calling onPause() you must have disabledForegroundDispatch.

Upvotes: 1

AndroidEx
AndroidEx

Reputation: 15824

According to the stacktrace in this line

adapter.enableForegroundDispatch(this, pendingIntent, writeTagFilters, null);

you adapter is null.

NfcAdapter.getDefaultAdapter(this); may return null if no such adapter is available. Are you sure this function is supported on your testing device?

Upvotes: 0

Related Questions