Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

I am implementing a database as I need to prepare the list or update it everytime I make some changes. I have a fragment on top of mainActivity and I can't perform the operations within the MainActivity so some of the operations are to be done in MainActivity and others in the fragment class. So in the fragment class which extends fragment has a method called preparelist(), which updates the database and populate the data. In my mainactivity I am performing a delete operations using the default overflow menu item, but here I need to call the preparelist() method in order to display the performed operations or the app has to be closed in order to diplay the operation that has been performed

I have tried the following code which is on the web

MyFragment fragment= (MyFragment)getSupportFragmentManager().findFragmentById(R.id.frag);
( (MyFragment)fragment).prepareList();

but this shows error

java.lang.NullPointerException: Attempt to invoke virtual method...on a null object reference

Basically what I want to know is how do I call the preparelist() method within my MainActivity without making any other abstract class or anything like that

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
207 views
Welcome To Ask or Share your Answers For Others

1 Answer

Solution 1

Call public method of your Fragment from your Activity:

MyFragment fragment= (MyFragment)getSupportFragmentManager().findFragmentById(R.id.frag);
if(fragment != null)
    ( (MyFragment)fragment).prepareList();
else
    Toast.makeText(this, "fragment is null", Toast.LENGTH_SHORT).show();

Solution 2

Move the functionality of delete to your fragment:

  1. move your delete operations in your fragment,
  2. in your fragment, write:

    @Override
    public void onActivityCreated(Bundle savedInstanceState) {
        super.onActivityCreated(savedInstanceState);
        setHasOptionsMenu(true);        //this fragment can now override
                                    //options menu
    }
    
  3. now do the same as you do in your activity, overriding the onCreateOptionsMenu(), onOptionsItemSelected etc. Please note that the method signatures differ to that of Activity's. See Fragment documentation.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...