Note that there are some explanatory texts on larger screens.

plurals
  1. POupdate TextView in fragment A when clicking button in fragment B
    text
    copied!<p>I have two fragments sitting side by side in the same activity. When I touch a button in the right fragment (fragment B), I need a TextView in the left fragment to update (fragment A). I have looked all over for the best way to do this, but nothing seems to work for my needs. Could someone possibly give me an example of how I would code this? Fragment A is set through the XML layout, and fragment B gets loaded programmatically into a container. I have tried accomplishing this by using a method in fragment A to update the text, and calling on that method from a method in the parent activity. I then call on the method in the parent activity from fragment B.</p> <p>This is the code in fragment B that declares the interface and calls a method in the interface</p> <pre><code>AttackCards attackCards; public interface AttackCards { public void deckSize(); } public void onAttach(DeckBuilder deckBuilder) { super.onAttach(deckBuilder); attackCards = (AttackCards) deckBuilder; } attackCards.deckSize(); //this is in my onclick methods </code></pre> <p>This is the code in the activity that implements the interface and calls the method in fragment A</p> <pre><code>public class DeckBuilder extends Activity implements AttackCards{ public void deckSize() { DeckBuilderFragment deckBuilderFragment = (DeckBuilderFragment)getFragmentManager(). findFragmentById(R.id.deckbuilder_fragment); deckBuilderFragment.deckSize(); } </code></pre> <p>This is the method in fragment A that appends the textview with the contents of a shared preferences value</p> <pre><code>public void deckSize() { deckSize = (TextView) getView().findViewById(R.id.decksize); final SharedPreferences defaultDeck = getActivity() .getSharedPreferences("defaultDeck", Context.MODE_PRIVATE); deckSize.setText(String.valueOf(defaultDeck.getInt("decksize", 0))); } </code></pre> <p>Sadly this attempt simply brings me a nullpointer when touching a button. I am getting a null pointer at</p> <pre><code>attackCards.deckSize(); //this is in my onclick methods </code></pre> <p>Could someone please help me out with an example of how to do this correctly?</p>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload