简体   繁体   中英

Executing method every second in Fragment - NULL Value on second run

We are getting values from onCreate method for someID. When the the onCreateView method runs the first time, everything is fine. However, on the second run (after the 1000 interval), the someID value is NULL. How can we make sure that this someID value will be sticky? Keep in mind that this thread exists in a Fragment

@Override
        public void onCreate(Bundle savedInstanceState){
            super.onCreate(savedInstanceState);
            someID = getArguments().getString(SOME_ID_KEY);

        }

        @Override
        public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState){
            View v = inflater.inflate(R.layout.fragment_game, container, false);
            Toast.makeText(getActivity(), someID, Toast.LENGTH_SHORT).show();

            handler.postDelayed(new Runnable() {
                @Override
                public void run() {

                    System.out.print(someID); // works on 1st time but not any other future runs of the 1k interval
                    handler.postDelayed(this, 1000);
                }
            }, 1000);

You can do it like this

private void printId(){
    handler.postDelayed(new Runnable() {
            @Override
            public void run() {

                System.out.print(someID); // works on 1st time but not any other future runs of the 1k interval
                printId();
            }
        }, 1000);
}

and in your onCreateView replace all the handler code with:

pirntId();

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM