trakasi trakasi - 1 year ago 123
Android Question

Android Studio "Refresh" fragment(s) layout from MainActivity

It's been a while, when I am trying to figure out my problem.

I want to "refresh" my fragments layout widgets, for example, textviews, imageviews, cardviews, and all other.

I'm trying to do this like:

((ImageView) findViewById(;

But, it always shows, nullObjectPointer error(Becouse these for
example CardViews are in other layout.)

I have figured out, that I can refresh them, when I click somewhere in that fragment, with "onClick" function

public void RefreshUpgrade(View view){
((TextView) findViewById("Player level: " +Main.PlayerLevel[0]);
((TextView) findViewById("Box level: " + Main.BoxesLevel[0]);
((TextView) findViewById("Garage level: " + Main.GarageLevel[0]);
((TextView) findViewById("Garage slots: " + Main.GarageSlots[0]);
((TextView) findViewById("Money: " + Main.Money[0] + "/600");
((TextView) findViewById("Boxes Opened: " + Main.BoxesOpened[0] + "/30");

if(Main.Money[0] >= 600){
((TextView) findViewById(;

But I need 2 things, that can't figure out.

1.I need these objects to "refresh" automatically, if arguments are true(if statements in MainActivity)

2.I need these objects to "refresh" automatically, after some time have went(Like GameLoop).

In Simple Java I got this all working, but there I got only JPanels, nothing like fragments.

Answer Source

Don't search for the Views in your Activity that belong to the Fragment. In your Fragment class store them in varibles like e.g.

class Fragment
private TextView playerUpgradeTextView;

 public void refreshViews(){
 // your refreshUpgrade() method

 public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        View v = inflater.inflate(R.layout.yourFragmentLayout, container, false);
        playerUpgradeTextView = (TextView) v.findViewById(
        return v;

Since your Activity holds your Fragment you can call the refreshViews method and pass it method parameters if needed.

Your second question is more a classic periodic event which also calls the refreshViews method.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download