Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
214 views
in Technique[技术] by (71.8m points)

java - How to access a method in fragment class from parent Activity?

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

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

1 Reply

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...