Android AsyncTask json返回值

时间:2015-04-19 05:22:59

标签: android json android-asynctask

我已经从我的按钮点击调用了异步任务。在doInBackground中我调用了一个API并且它返回了一个Json对象。我想将Json对象传递给按钮click上的另一个活动。我怎么能获取返回的Json对象值,以便我可以将其发送到其他活动。

感谢。

2 个答案:

答案 0 :(得分:1)

创建界面

public interface Listener {
void success(BaseModel baseModel);
void fail(String message);
}

创建基础模型类

public class BaseModel  implements Serializable {
private static final long serialVersionUID = 1L;
}

在onClick mehtod中调用以下方法。

 protected void userLoginData(final String userName) {
// if you want to pass multiple data to server like string or json you can pass in this constructor
     UserLoginLoader  userLoginLoader = new UserLoginLoader(LoginActivity.this, userName, "1234567899", new Listener() {

        @Override
        public void success(BaseModel baseModel) {
             // here you got response in object you can use in your  activity
            UserLoginModel userLoginModel = (UserLoginModel) baseModel;
             // you can get data from user login model

             }catch(Exception exception){
                 exception.printStackTrace();
                 Utils.showAlertDialog(LoginActivity.this, "Server is not responding! Try Later.");
             }
        }

        @Override
        public void fail(String message) {

        }
    });
     userLoginLoader.execute();

}

: - 用户登录加载程序类

public class UserLoginLoader extends AsyncTask<String, Void, Boolean> {
private Dialog dialog;
private Listener listner;
private String deviceId;
Activity activity;
String message;
String userName;
boolean checkLoginStatus;
public UserLoginLoader(Activity activity,String userName, String deviceId, Listener listener) {
    this.listner = listener;
    this.userName =userName;
    this.activity = activity;
    this.deviceId = deviceId;
}


@Override
protected Boolean doInBackground(String... arg0) {
       //User login web service is only for making connection to your API  return data into message string
          message = new UserLoginWebService().getUserId(userName, deviceId);
    if (message != "null"  &&  !message.equals("false")) {
        return true;
    }
    return false;

}

@Override
protected void onPreExecute() {
    super.onPreExecute();
    dialog = new Dialog(activity, R.style.CustomDialogTheme);
    dialog.setContentView(R.layout.progress);
    dialog.setCancelable(false);
    dialog.show();
}

@Override
protected void onPostExecute(Boolean result) {
    super.onPostExecute(result);
    BaseModel baseModel = null;
    if (!message.equals("null") && (!message.equals("false")) )
        baseModel = parseData(message, result);

    if (dialog.isShowing()) {
        dialog.dismiss();
        dialog.cancel();
        dialog = null;
    }
    if (listner != null) {
        if (result && baseModel != null)
            listner.success(baseModel);
        else
            listner.fail("Server  not responding! Try agian.");
    } else
        listner.fail("Server  not responding! Try agian.");
}
 //call parser for parsing data return data from the parser
private BaseModel parseData(String responseData, Boolean success) {
    if (success == true && responseData != null
            && responseData.length() != 0) {
        UserLoginParser loginParser = new UserLoginParser(responseData);
        loginParser.parse();
            return loginParser.getResult();

    }
    return null;
}

}

这是您登录解析器类

 public class UserLoginParser {
JSONObject jsonObject;
UserLoginModel userLoginModel;

 /*stored data  into json object*/
public UserLoginParser(String data) {
    try {
        jsonObject = new JSONObject(data);
    } catch (JSONException e) {
        Log.d("TAG MSG", e.getMessage());
        e.printStackTrace();

    }
}

public void parse() {
    userLoginModel = new UserLoginModel();
    try {
        if (jsonObject != null) {
             userLoginModel.setUser_name(jsonObject.getString("user_name")== null ? "": jsonObject.getString("user_name"));
             userLoginModel.setUser_id(jsonObject.getString("user_id") == null ? "" : jsonObject.getString("user_id"));
             userLoginModel.setFlag_type(jsonObject.getString("flag_type") == null ? "" : jsonObject.getString("flag_type"));
        } else {
            return;
        }
    } catch (Exception exception) {
        exception.printStackTrace();
    }

}
/*return ship name list which is stored into model */
public UserLoginModel getResult() {
    return userLoginModel;
}

 }

答案 1 :(得分:0)

在Activity中编写一个回调方法,该方法接收您希望从AsyncTask传递给该Activity的参数。在创建它时将活动的引用发送给AysncTask。从doInBackground()方法调用此回调方法,并使用API​​返回的数据。

代码就像 -

public class TestAsyncTask extends AsyncTask<Integer, Integer, String[]> {  
    Activity myActivity;
    public TestAsyncTask(Activity activity) {
        this.myActivity = activity;
    }

    @Override
    protected String[] doInBackground(Integer... params) {
        String data = yourApi();
        myActivity.callback(data);
    }
}

public class MyActivity extends Activity {
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        new TestAsyncTask(this).execute(someId);
    }

    public void callback(String data) {
        //process data
    }
}

只需记录,您就可以通过调用doInBackground()方法直接从get()方法获取返回值。

String data = new TestAsyncTask(this).execute(someId).get();

但请注意,这可能会阻止您的UI线程,因为它会等待doInBackground()方法完成它的执行。