This question already has answers here:
“Variable example might not have been initialized” in anonymous class
                                
                                    (2个答案)
                                
                        
                2年前关闭。
            
        

这是我的代码片段:

public View onCreateView(LayoutInflater inflater, ViewGroup container,
                         Bundle savedInstanceState) {

    View view= inflater.inflate(R.layout.fragment_profile, container, false);
    profile();
    textView = (TextView) view.findViewById(R.id.textViewUsername);
    listView = (ListView) view.findViewById(R.id.listView);
    timer_start();
    return view;
}

public void timer_start(){
    final Runnable mTicker = new Runnable() {
        @Override
        public void run() {
            sendRequest();
            handler.postDelayed(mTicker, 5000); // error shows only for this line
        }
    };

    handler.postDelayed(mTicker, 5000);
}


我想每5秒执行一次sendRequest()函数。但是它显示错误:当我调用timer_start()片段时,“变量mTicker可能尚未初始化”。

最佳答案

您在初始化的同一行中引用mTicker。这是不允许的。这就像在说:

String s = s;


这没有道理。尝试使用“ this”:

handler.postDelayed(this, 5000);

08-18 06:12
查看更多