1

I am writing a code which should return NFC tag value on the next activity ( page ) when NFC get detected during scan. What happens here is that when I launch the app for the first time it the first page shows for a fraction of a second and moves to second page directly ( activity ).

Here is the piece of code for the first activity ( which is just for asking user to tap to scan )

protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main2);
        askPermissions();

        mtxtViewNfcContent = (TextView) findViewById(R.id.text);
        nfcAdapter         = NfcAdapter.getDefaultAdapter(this);

        if (nfcAdapter == null) {
            Toast.makeText(this, "No NFC", Toast.LENGTH_SHORT).show();
            finish();
            return;
        }

        else {

Intent in = new Intent(Main2Activity.this, MainActivity.class);
            startActivity(in);
}

What I want is the the to show the first page at launch and when user tap to nfc scan, show the output on the next page ( MainActivity).

PS : I am new to android, please excuse with my codes.

vinuraj_pg
  • 57
  • 1
  • 8
  • You might be getting nfcAdapter as null that's why your app is moving to next screen – Karan Mehta Jan 27 '20 at 07:28
  • You should try to move to next screen in callback of nfc discovery – Karan Mehta Jan 27 '20 at 07:29
  • @KaranMehta I think if the nfcAdapter is null it should show as a text. Will you be able to help me with the code or syntax for callback method ? – vinuraj_pg Jan 27 '20 at 07:44
  • 1
    As you have not read any data from the card in your example, it looks like you want help on how to read data from the cards? There are 2 methods of reading data from NFC cards `enableForegroundDispatch` and `enableReaderMode`. Understanding what type of NFC card you are wanting to read and what type of data is on the card is key to reading. As you don't specify this it is difficult to help. Generally I would recommend using `enableReaderMode` as this is more reliable and provides better user interaction. – Andrew Jan 27 '20 at 09:09
  • @Andrew Thanks for your inputs, I am able to read the data and display it on the same page. Now I am trying to add an activity before this main activity ( for eg, a picture that says user to tap to scan ). Once user taps it, I want to call the new activity which is already implemented. – vinuraj_pg Jan 27 '20 at 09:15
  • For reliable handling of cards you need to read the card data as soon are you notified a card has come in to range, this means you need to read the data from the card in this activity and then pass the data in the Intent that starts second activity as shown in Prashant's answer. It is possible to do what you want but it will be extremely unreliable – Andrew Jan 27 '20 at 09:41

2 Answers2

1

what are you doing until now is to exit the app when the device doesnot support nfc or to start another activity when the device supports nfc.

you are actually not listening at all to any tag.

here you have two possibilities: first : read an nfc tag in the first activity and then creat a new intent with and put the result of tag reading as extra bundel.

two : listen to tag existance in the first activity and then send the tag to second one and read it in the second activity.

I would prefer the first secinario.

on firstActivity:

public class MainActivity extends AppCompatActivity {
private PendingIntent pendingIntent;
private IntentFilter[] writeTagFilters;
private NfcAdapter nfcAdapter;
@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setTheme(R.style.AppTheme);
    setContentView(R.layout.activity_main);
    nfcAdapter = NfcAdapter.getDefaultAdapter(this);
    if (nfcAdapter == null) {
        Toast.makeText(this, "No NFC", Toast.LENGTH_SHORT).show();
        finish();
        return;
    }
    setForeground();

}
 private void setForeground() {
    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};
}
@Override
protected void onResume() {

    super.onResume();
    if (nfcAdapter != null) {
        nfcAdapter.enableForegroundDispatch(this, pendingIntent, null, null);
    }
    processNfcTag(getIntent());
}
@Override
protected void onNewIntent(Intent intent) {
    super.onNewIntent(intent);
    setIntent(intent);
}

@Override
protected void onPause() {

    super.onPause();
    if (nfcAdapter != null) {
        nfcAdapter.disableForegroundDispatch(this);
    }

}

private void processNfcTag(Intent intent) {
//TODO: here you should to check if this intent is an NFC Intent, in case it is an nfc intent you could read it according of tag tech you have 
// for example MifareUltralight.
MifareUltralight mfu = MifareUltralight.get(intent.getParcelableExtra(NfcAdapter.EXTRA_TAG));
try {
        mfu.connect();
        byte [] bytes = mfu.readPages(pageNumber);
        mfu.close();
    } catch (IOException e) {
        e.printStackTrace();

    }
// then you could get this bytes and send it to the other activity 
}

please check this link to know how to send data between activities.

p.s: you should to check the code I have wrote it quickly.

Karam
  • 303
  • 2
  • 16
0

You can use intent.putExtra (key,value) while calling the intent and use bundle on the result activity to fetch the variable data

use this while calling the intent

`Intent intent = new Intent(FirstActivity.this, SecondActivity.class);
intent.putExtra("some_key", value);
intent.putExtra("some_other_key", "a value");
startActivity(intent);`

use this on result activity

`Bundle bundle = getIntent().getExtras();
int valueText = bundle.getInt("some_key");
String valueString = bundle.getString("some_other_key");
TextView textone =(TextView)findVeiwById(R.id.textone);
textone.setText(valueText);
TextView stringTextView = (TextView)FindViewById(R.id.stringTextView)
stringTextView.setText(valueString)`
Community
  • 1
  • 1
  • or else you use nfc callback functions https://developer.android.com/guide/topics/connectivity/nfc/nfc#abs-uri – Prashant verma Jan 27 '20 at 07:57
  • override fun onNewIntent(intent: Intent) { super.onNewIntent(intent) ... if (NfcAdapter.ACTION_NDEF_DISCOVERED == intent.action) { intent.getParcelableArrayExtra(NfcAdapter.EXTRA_NDEF_MESSAGES)?.also { rawMessages -> val messages: List = rawMessages.map { it as NdefMessage } // Process the messages array. ... } } } – Prashant verma Dec 16 '21 at 06:42