【问题标题】:"Variable might not have been initialized" in java while using timer [duplicate]使用计时器时Java中的“变量可能尚未初始化”[重复]
【发布时间】:2017-07-08 21:01:03
【问题描述】:

这是我的代码片段:

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() 函数。但它显示错误:“变量 mTicker 可能尚未初始化”,而我正在调用 timer_start() 片段。

【问题讨论】:

  • 对于纯粹的自我放纵,用自己提出和回答的问题来敲打这个问题,我们深表歉意。我只是认为它完全涵盖了您在这里提出的问题!

标签: java android


【解决方案1】:

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

String s = s;

这没有意义。尝试使用“this”:

handler.postDelayed(this, 5000);

【讨论】:

  • 目前没有错误。在这里,我正在使用导航抽屉。 ProfileFragment 是我的默认片段。现在,默认片段正确显示。但是在添加此行后,应用程序在从抽屉菜单中转到 profilefragment 时不幸停止了。如果我评论这一行,一切都会好起来的。
  • 有趣的是,你可以写String s = s = "";。这是我本周发现的规范的一个怪癖。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2012-03-25
  • 2015-07-04
相关资源
最近更新 更多