I have created a Fragment but don't know what to put inside

1

I have realised an NFC (to scan tags) application, but now I have to create fragment who works with my MainActivity because I'd like to implement ViewPager in future.

Problem is that i'm really beginner and my code became too big to know what I have to put in Activity and what I have to put in Fragment

One week that I'm trying to understand...

Here is my code

public class MainActivity extends FragmentActivity {
    ObjectAnimator anim;
    ObjectAnimator anim2;
    private int display, result, detect = 0;
    private NfcAdapter nfcAdapter;
    private ImageButton nfcButton;
    private PendingIntent pendingIntent;
    private ImageButton qrButton;
    private TextView text;
    private ImageButton webButton;
    String link = null;
    public final int CUSTOMIZED_REQUEST_CODE = 0x0000ffff;

    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        slidr = Slidr.attach(this);
        setDetect(1);
        setContentView((int) R.layout.activity_main);
        this.text = (TextView) findViewById(R.id.text);
        this.nfcAdapter = NfcAdapter.getDefaultAdapter(this);
        this.nfcButton = (ImageButton) findViewById(R.id.nfc_button);
        this.anim = ObjectAnimator.ofFloat(this.nfcButton, "scaleX", new float[]{0.9f});
        this.anim2 = ObjectAnimator.ofFloat(this.nfcButton, "scaleY", new float[]{0.9f});
        IntentIntegrator integrator = new IntentIntegrator(this);
        this.nfcButton.setOnClickListener(new View.OnClickListener() {
            public void onClick(View v) {
                setDisplay(1);
                manageBlinkEffect();
            }
        });
        this.pendingIntent = PendingIntent.getActivity(this, 0, new Intent(this, getClass()).addFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP), 0);
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {                                   // RESULTAT DU SCAN QR CODE
        if (requestCode != CUSTOMIZED_REQUEST_CODE && requestCode != IntentIntegrator.REQUEST_CODE) {
            super.onActivityResult(requestCode, resultCode, data);
            return;
        }
        switch (requestCode) {
            case CUSTOMIZED_REQUEST_CODE: {
                Toast.makeText(this, "REQUEST_CODE = " + requestCode, Toast.LENGTH_LONG).show();
                break;
            }
            default:
                break;
        }

        IntentResult result = IntentIntegrator.parseActivityResult(resultCode, data);

        if (result.getContents() != null) {
            Log.d("MainActivity", "Scanned");
            AlertDialog.Builder builder = new AlertDialog.Builder(this);
            builder.setTitle("Résultat du scan :");
            if (URLUtil.isValidUrl(result.getContents())) {                                                                      // si url...
                builder.setNeutralButton("Visiter", new DialogInterface.OnClickListener() {
                    public void onClick(DialogInterface dialog, int which) {
                    }
                });
                builder.setPositiveButton("Fermer", new DialogInterface.OnClickListener() {
                    public void onClick(DialogInterface dialog, int which) { }
                });
                builder.setNegativeButton("Copier", new DialogInterface.OnClickListener() {
                    public void onClick(DialogInterface dialog, int which) {
                        ClipboardManager clipboard = (ClipboardManager) getSystemService(Context.CLIPBOARD_SERVICE);
                        ClipData clip = ClipData.newPlainText("Texte copié", result.getContents());
                        clipboard.setPrimaryClip(clip);
                    }
                });
            } else {                                                                                                             // si plain text...
                builder.setNeutralButton("Copier", new DialogInterface.OnClickListener() {
                    public void onClick(DialogInterface dialog, int which) {
                        ClipboardManager clipboard = (ClipboardManager) getSystemService(Context.CLIPBOARD_SERVICE);
                        ClipData clip = ClipData.newPlainText("Texte copié", result.getContents());
                        clipboard.setPrimaryClip(clip);
                    }
                });
                builder.setPositiveButton("Fermer", new DialogInterface.OnClickListener() {
                    public void onClick(DialogInterface dialog, int which) { }
                });
            }
            builder.setMessage(result.getContents().toString());
            builder.create().show();
        }
    }


    public void manageBlinkEffect() {                                                                           // ANIMATION DU LOGO SENZU SUITE A UN CLIC
        anim.setDuration(1000);
        anim.setRepeatMode(ValueAnimator.REVERSE);
        anim.setRepeatCount(9);
        anim.start();
        anim.addListener(new AnimatorListenerAdapter() {
            @Override
            public void onAnimationEnd(Animator animation) {
                super.onAnimationCancel(animation);
                if (getRes() != 1){
                    Animation shake = AnimationUtils.loadAnimation(getApplicationContext(), R.anim.shake);
                    Toast.makeText(getApplicationContext(), "Aucun badge n'a été détécté !", Toast.LENGTH_SHORT).show();
                    nfcButton.startAnimation(shake);
                }
            }
        });
        anim2.setDuration(1000);
        anim2.setRepeatMode(ValueAnimator.REVERSE);
        anim2.setRepeatCount(9);
        anim2.start();
    }

    public void onResume() {
        super.onResume();

        Intent intent = getIntent(); // Recuperer l'intent actuel
        NdefMessage[] msgs;
        if (getDetect() == 1 && (NfcAdapter.ACTION_NDEF_DISCOVERED.equals(intent.getAction()) || NfcAdapter.ACTION_TECH_DISCOVERED.equals(intent.getAction()))) { // si l'application a ete lancee via une detection NFC du device  (ACTION_NDEF_DISCOVERED, voir AndroidManifest)
            Parcelable[] rawMessages =
                    intent.getParcelableArrayExtra("android.nfc.extra.NDEF_MESSAGES");
            if (rawMessages != null) { // si NDEF dans le scan
                setDisplay(1);
                resolveIntent(intent); // parser le scan NFC
            }  else {
                byte[] empty = new byte[0];
                byte[] id = intent.getByteArrayExtra(NfcAdapter.EXTRA_ID);
                Tag tag = (Tag) intent.getParcelableExtra(NfcAdapter.EXTRA_TAG);
                byte[] payload = NdefMessageParser.dumpTagData(tag).getBytes();
                NdefRecord record = new NdefRecord(NdefRecord.TNF_UNKNOWN, empty, id, payload);
                NdefMessage msg = new NdefMessage(new NdefRecord[] {record});
                msgs = new NdefMessage[] {msg};
                setDetect(0);
                getResult(msgs);
            }
        }
        NfcAdapter nfcAdapter2 = this.nfcAdapter;
        if (nfcAdapter2 != null) {
            if (!nfcAdapter2.isEnabled()) {
                showWirelessSettings();
            }
            this.nfcAdapter.enableForegroundDispatch(this, this.pendingIntent, (IntentFilter[]) null, (String[][]) null);
        }
    }

    private void showWirelessSettings() {
        Toast.makeText(this, "Veuillez activer le service NFC", Toast.LENGTH_SHORT).show();
        startActivity(new Intent("android.settings.WIRELESS_SETTINGS"));
    }

    public void onPause() {
        setDetect(0);
        super.onPause();
    }


    public void onNewIntent(Intent intent) {
        super.onNewIntent(intent);
        setIntent(intent);
        if (getDetect() != 1) {
            resolveIntent(intent);
        }
    }

    private void resolveIntent(Intent intent) {                                                                 // DETECTION NFC ET PARSING NDEF
        NdefMessage[] msgs;
        String action = intent.getAction();
        Log.d("Infos", getIntent().toString());
        Log.d("Infos", "display = " + display);
        if (getDisplay() != 1) {
            Animation shake = AnimationUtils.loadAnimation(this, R.anim.shake);
            nfcButton.startAnimation(shake);
            Toast.makeText(this, "Veuillez lancer un scan", Toast.LENGTH_LONG).show();
            return;
        }
        else if ("android.nfc.action.TAG_DISCOVERED".equals(action) || "android.nfc.action.TECH_DISCOVERED".equals(action) || "android.nfc.action.NDEF_DISCOVERED".equals(action)) {
            setRes(1);
            Parcelable[] rawMsgs = intent.getParcelableArrayExtra("android.nfc.extra.NDEF_MESSAGES");
            if (rawMsgs != null) {
                msgs = new NdefMessage[rawMsgs.length];
                for (int i = 0; i < rawMsgs.length; i++) {
                    msgs[i] = (NdefMessage) rawMsgs[i];
                }
            } else {
                byte[] empty = new byte[0];
                byte[] id = intent.getByteArrayExtra(NfcAdapter.EXTRA_ID);
                Tag tag = (Tag) intent.getParcelableExtra(NfcAdapter.EXTRA_TAG);
                byte[] payload = NdefMessageParser.dumpTagData(tag).getBytes();
                NdefRecord record = new NdefRecord(NdefRecord.TNF_UNKNOWN, empty, id, payload);
                NdefMessage msg = new NdefMessage(new NdefRecord[] {record});
                msgs = new NdefMessage[] {msg};
            }
            if (getDisplay() == 1) {
                getResult(msgs);
            }
        }
    }

    private void getResult(NdefMessage[] msgs) {                                                            // MODAL AVEC RESULTAT DU SCAN NFC
        if (msgs != null && msgs.length != 0) {
            final StringBuilder tmp_builder = new StringBuilder();
            List<ParsedNdefRecord> records = NdefMessageParser.parse(msgs[0]);
            int size = records.size();
            for (int i = 0; i < size; i++) {
                tmp_builder.append(records.get(i).str());
                tmp_builder.append("\n");
            }
            System.out.println(tmp_builder.toString());
            this.anim.cancel();
            this.anim2.cancel();
            setDisplay(0);
            AlertDialog.Builder builder = new AlertDialog.Builder(this);
            builder.setTitle("Resultat du scan :");
            builder.setNeutralButton("Visiter", new DialogInterface.OnClickListener() {
                public void onClick(DialogInterface dialog, int which) {
                 /*  Intent i = new Intent(MainActivity.this, RightActivity.class);
                    link = tmp_builder.toString();
                    i.putExtra("url", link);
                    startActivity(i);*/
                }
            });
            builder.setNegativeButton("Copier", new DialogInterface.OnClickListener() {
                public void onClick(DialogInterface dialog, int which) {
                    ClipboardManager clipboard = (ClipboardManager) getSystemService(Context.CLIPBOARD_SERVICE);
                    ClipData clip = ClipData.newPlainText("Texte copié", link);
                    clipboard.setPrimaryClip(clip);
                }
            });
            builder.setPositiveButton("Fermer", new DialogInterface.OnClickListener() {
                public void onClick(DialogInterface dialog, int which) {}
            });
            builder.setMessage(tmp_builder.toString());
            builder.create().show();
        }
    }

I don't know if I have to transfert my onResume, onPause etc. in my Fragment

Really lost...

android
android-fragments
android-activity
asked on Stack Overflow Feb 20, 2020 by aagrios • edited Feb 20, 2020 by Bruno

2 Answers

1

I think you need to make the changes in stages

I would understand how viewpager and fragments work first see https://abhiandroid.com/materialdesign/viewpager for a tutorial

The next stage is to create your first fragment with the nfcButton on it BUT not try to link it up yet with the NFC stuff.

This is because the starting point of handling NFC has to be in the Activity as you are overriding Activity methods to do this.

This is basically putting the code below in to the onViewCreated method of your fragment and moving the xml related to the button to the fragment's xml

this.text = (TextView) findViewById(R.id.text);
        this.nfcButton = (ImageButton) findViewById(R.id.nfc_button);
        this.anim = ObjectAnimator.ofFloat(this.nfcButton, "scaleX", new float[]{0.9f});
        this.anim2 = ObjectAnimator.ofFloat(this.nfcButton, "scaleY", new float[]{0.9f});
        this.nfcButton.setOnClickListener(new View.OnClickListener() {
            public void onClick(View v) {
                // setDisplay should not be used at this stage
                // setDisplay(1);
                manageBlinkEffect();
            }
        });

Also move the method manageBlinkEffect() to the fragment.

You should comment out in getResult as well at the moment

this.anim.cancel();
this.anim2.cancel();

Then setup your viewpager in main xml file

The reason for commenting out these lines at the moment is that these need Activity to Fragment communication, you should understand https://developer.android.com/training/basics/fragments/communicating

Next stage is connecting you button back to the setDetect Flag (replacing the commented out setDetect() line)

i.e Your Fragment with the nfcButton it in has to tell the MainActivity to start processing any NFC data it gets sent

Then the MainActivity in getResult needs to tell the Fragment with the nfc to stop animating it's Button IF the Fragment with the button in is being displayed and and that Fragment is up and running. Again this is fragment communication from Activity to Fragment this time.

answered on Stack Overflow Feb 20, 2020 by Andrew
0

First of all you should add ViewPager in XML;

Then;

In your activity define your viewpager like that;

viewPager = findViewById(R.id.viewpager_main)

Then use this for setup viewpager

setupViewPager(viewPager)

Create setupViewPager function like that;

private fun setupViewPager(viewPager: ViewPager) {
        val adapter = ViewPagerAdapter(supportFragmentManager)
        adapter.addFragment(
            MainFragment(),
            "Fragment1"
        )
adapter.addFragment(
            SecondFragment(),
            "Fragment2"
        )
        viewPager.adapter = adapter}

Simple example of fragments;

class MainFragment() : Fragment() {

override fun onCreate(savedInstanceState: Bundle?) {
    super.onCreate(savedInstanceState)
    retainInstance = true
}

override fun onCreateView(
    inflater: LayoutInflater,
    container: ViewGroup?,
    savedInstanceState: Bundle?
): View? =
    inflater.inflate(R.layout.info_screen_fragment, container, false)

/* info_screen_fragment is your xml for this fragment */
    override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
        super.onViewCreated(view, savedInstanceState)

    }
}

My codes written with Kotlin. But i used to this codes. Simple and flex.

answered on Stack Overflow Feb 20, 2020 by Murat Çakır

User contributions licensed under CC BY-SA 3.0