Micael Tchapmi
Micael Tchapmi

Reputation: 37

Change fragment's Textview from main activity

I have been following tutorials on how to implement bottom nav bar with three fragments. I am now stuck when I need to update my profile fragment's textview. MainActivity code:

public class MainActivity extends AppCompatActivity {
    String activeUser = "", response="myresponse";
    ProgressDialog progDailog;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    activeUser = getIntent().getStringExtra("currentUser");

    setupNavigationView();

    new getProfileData().execute("myurl");

    getSupportActionBar().setTitle("Home");


}


private void setupNavigationView() {
    BottomNavigationView bottomNavigationView = (BottomNavigationView) findViewById(R.id.bottom_navigation);
    if (bottomNavigationView != null) {

        // Select first menu item by default and show Fragment accordingly.
        Menu menu = bottomNavigationView.getMenu();
        selectFragment(menu.getItem(1));

        // Set action to perform when any menu-item is selected.
        bottomNavigationView.setOnNavigationItemSelectedListener(
                new BottomNavigationView.OnNavigationItemSelectedListener() {
                    @Override
                    public boolean onNavigationItemSelected(@NonNull MenuItem item) {
                        selectFragment(item);
                        return false;
                    }
                });
    }
}

/**
 * Perform action when any item is selected.
 *
 * @param item Item that is selected.
 */
protected void selectFragment(MenuItem item) {

    item.setChecked(true);

    switch (item.getItemId()) {
        case R.id.menu_home:
            // Action to perform when Home Menu item is selected.
            pushFragment(new HomeFragment());

            break;
        case R.id.menu_news:
            // Action to perform when News Menu item is selected.
            pushFragment(new NewsFragment());
            break;
        case R.id.menu_profile:
            // Action to perform when Profile Menu item is selected.
            pushFragment(new ProfileFragment());
            break;
    }
}

/**
 * Method to push any fragment into given id.
 *
 * @param fragment An instance of Fragment to show into the given id.
 */
protected void pushFragment(Fragment fragment) {
    if (fragment == null)
        return;

    FragmentManager fragmentManager = getFragmentManager();
    if (fragmentManager != null) {
        FragmentTransaction ft = fragmentManager.beginTransaction();
        if (ft != null) {
            ft.replace(R.id.main_container, fragment);
            ft.commit();
        }
    }
}

@Override
public boolean onCreateOptionsMenu(Menu menu) {
    getMenuInflater().inflate(R.menu.three_dots_items, menu);
    return true;
}

ProfileFragment code:

public class ProfileFragment extends Fragment {

TextView profile;

@Nullable
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
    View view = inflater.inflate(R.layout.profile_fragment, container, false);
    profile = (TextView) view.findViewById(profileData);
    return  view;
}

public void updateTextView(String text){
    profile.setText(text);
}

My profilefragment.xml has a textview with id profileData. In my ProfileFragment java class, I introduced a method updateTextView to update the profile layout but I don't know where or how to call this method in my mainactivity.java. I've searched several questions on this topic and tried the different solutions proposed on stackoverflow but I keep getting a null pointer exception error whenever i try to call that method in my mainactivity. Please can someone help me?

Upvotes: 1

Views: 1703

Answers (3)

Brian Yencho
Brian Yencho

Reputation: 2958

When replacing a container's content with a Fragment, you can always get the currently displayed Fragment by calling getSupportFragmentManaget().findFragmentById(...) with that container's ID. You can then check if the current Fragment is a ProfileFragment and, if so, make your update:

    Fragment fragment = getSupportFragmentManager().findFragmentById(R.id.main_container);
    if (fragment instanceof ProfileFragment) {
        ((ProfileFragment) fragment).updateTextView(text);
    }

Upvotes: 0

Pratik
Pratik

Reputation: 450

Create a getInstance() function in Fragment

public static ProfileFragment mProfileFragment =null;
public static ProfileFragment getInstance(){
if(mProfileFragment == null){
mProfileFragment = new ProfileFragment();
}
return mProfileFragment;
}

And in your Activity class when you are trying to set text value check first instance of Fragment is null or not. If not null set text value.

if(ProfileFragment.getInstance() != null){
textview.SetText("Your Text Value here"); 
}

Upvotes: 0

user4571931
user4571931

Reputation:

Following changes you need to make in MainActivity:

Get your fragment (i.e ProfileFragment) by tag using method:

Profile Fragment fragment =  (ProfileFragment)getSupportFragmentManager().findFragmentByTag("tag");
 if(fragment != null)
 fragment.updateTextView();

Here tag is a String constant that you need to add while replacing fragment as below:

In your code make following changes

FragmentTransaction ft = fragmentManager.beginTransaction();
    if (ft != null) {
        ft.replace(R.id.main_container, fragment,"tag");

Upvotes: 2

Related Questions