doInBackground方法必须返回JSONObject类型的结果

时间:2015-09-18 01:45:10

标签: android

我正在尝试在子类中使用Asynctask GCM的组合实现JSONObject方法。我在doinBackground方法中应用GCM条件时遇到了问题。

以下是doInBackground method

的标题
 protected JSONObject doInBackground(String... args) {

    GCMRegistrar.checkDevice(context);
     GCMRegistrar.checkManifest(context);
     final String regId = GCMRegistrar.getRegistrationId(context);
     if (regId.equals("")) {        
        GCMRegistrar.register(context,SENDER_ID);
    }else {
        if (GCMRegistrar.isRegisteredOnServer(context)) {               
            Toast.makeText(getApplicationContext(), "Already registered with GCM", Toast.LENGTH_LONG).show();
        } else {
                UserFunctions userFunction = new UserFunctions();
                JSONObject json =userFunction.registerUser(context,fname, lname, email, password,regId);
                return json;
        }
    }
 }

我的IDE不允许执行它。这是它给出的错误信息。

  

此方法必须返回JSONObject类型的结果

现在,当返回值超出条件时,上面的代码正常工作,但是假设只有条件为真时才会执行返回值。

更新

还有另一个问题。 json始终在doInBackground方法中返回null,因为当GCM registrationID为空时,GCM注册器会对其进行注册。一旦注册,GCM意图服务就会接管服务器注册,这意味着doInBackground中的json会向onPostExecute method发送空值。

我还检查了onPostExecute方法的成功和验证。检查验证后,会向UI发送一条消息。

如果jsononPostExecute方法发送空值,则无法进行任何验证并向UI发布消息

请问有没有办法让上面的方法工作,我会的 感谢有人可以提供帮助。感谢。

3 个答案:

答案 0 :(得分:1)

因为你定义了JSONObject。试试这个 -

protected JSONObject doInBackground(String... args) {

    GCMRegistrar.checkDevice(context);
    GCMRegistrar.checkManifest(context);
    final String regId = GCMRegistrar.getRegistrationId(context);
    JSONObject jsonObject = null; //Declaration
    if (regId.equals("")) {
        GCMRegistrar.register(context,SENDER_ID);
    }else {
        if (GCMRegistrar.isRegisteredOnServer(context)) {
            Toast.makeText(getApplicationContext(), "Already registered with GCM", Toast.LENGTH_LONG).show();
        } else {
            UserFunctions userFunction = new UserFunctions();
            jsonObject =userFunction.registerUser(context,fname, lname, email, password,regId);

        }
    }
    return jsonObject;
}

现在在你的onPostExecute()中,在开始访问数据之前,只检查你的JSONObject是否为null -

@Override
protected void onPostExecute(JSONObject jsonObject) {
    if(jsonObject != null) {
        //Do something i.e. access data
    } else {
        //Handle null JSON
    }
}

答案 1 :(得分:0)

只需在外面声明一个变量,然后将其返回。

slice

答案 2 :(得分:0)

如果没有任何内容可以传回,您可以简单地null

{{1}}

然后在{{1}}中进行空引用检查。

如果你告诉方法返回某种类型的东西,那么你需要这样做。您只需要始终考虑对象是否可以{{1}}

相关问题