【问题标题】:How to solve NullPointer Exception?如何解决 NullPointer 异常?
【发布时间】:2015-04-23 10:25:06
【问题描述】:

我有一个应用程序,在标签 1 中有 3 个标签(片段)我有一个像这样的异步方法

 public class getUserGroupAsync extends AsyncTask<JSONObject,Void,JSONObject>{
        String resp;
        @Override
        protected JSONObject doInBackground(JSONObject... params) {

            JSONObject paramObj = new JSONObject();

            try {
                getToken();
                method = "hostgroup.get";
                paramObj.put("output","groupids");

                response = sendJsonRequest.getResponse(method,paramObj,token);
                resp = response.getString("result");
            }

            catch (JSONException e) {
                System.out.println("Error "+e.getMessage());
            }





        }
    }

当我从选项卡 1 切换到另一个选项卡并返回到选项卡 1 时,我想重新加载异步任务。

我试过这样:

   public class ClientActivity extends  ActionBarActivity{
       protected void onCreate(Bundle savedInstanceState) {
      public void onPageSelected(int position) {




                   if (position == 0){


                        systemStatus.new getUserGroupAsync().execute();


                   }





                }
    }
}

但我得到一个 NullPointerException ? 有什么帮助吗?

【问题讨论】:

  • 请发布您的异常的堆栈跟踪。
  • 另外,这段代码能编译吗? systemStatus.new getUserGroupAsync().execute();似乎语法不正确。
  • 我的回答没有用?

标签: android android-fragments android-asynctask


【解决方案1】:

尝试将您的代码放入片段 1 的 onResume 方法中

@Override
public void onResume() {
    super.onResume();
    new getUserGroupAsync().execute();
}

【讨论】:

    【解决方案2】:

    我从您的代码中假设getUserGroupAsync 类位于另一个名为systemStatus 的类中?很难说清楚,因为类通常首字母大写(GetUserGroupAsyncSystemStatus),而对象首字母小写(getUserGroupAsyncsystemStatus)。

    如果 getUserGroupAsync 位于名为 systemStatus 的类中,可以通过选项卡访问,那么最好的方法就是以这种方式刷新数据:

    class systemStatus extends Fragment {
        private getUserGroupAsync asyncTask = null;
    
        @Override
        public void onCreate(Bundle savedInstanceState) {
           super.onCreate(savedInstanceState);
           if (asyncTask == null) {
               asyncTask = new getUserGroupAsync();
               asyncTask.execute();
           }
        }
    
        @Override
        public void onResume () {
               asyncTask = new getUserGroupAsync();
               asyncTask.execute();
           }
    
        //...
        public class getUserGroupAsync extends AsyncTask<JSONObject,Void,JSONObject>{
        //etc...
    

    【讨论】:

      猜你喜欢
      • 2011-02-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2023-03-24
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多