Java AsyncTask:将异常值从doInBackground传递到onPostExecute

Java AsyncTask:将异常值从doInBackground传递到onPostExecute,java,android,android-asynctask,Java,Android,Android Asynctask,我正试图在doInBackground和onPostExecute之间传递错误消息。有没有办法使用数据结构来实现这一点?在我的情况下,我试图避免创建类和返回对象 @Override protected User doInBackground(List<Pair<String, String>>... params) { randomAPI api = randomAPI

我正试图在doInBackground和onPostExecute之间传递错误消息。有没有办法使用数据结构来实现这一点?在我的情况下,我试图避免创建类和返回对象

                    @Override
        protected User doInBackground(List<Pair<String, String>>... params) {
            randomAPI api = randomAPI
                    .getInstance(context);

            try {
                **thing that will generate error**
                }

            } catch (RandomException e) {
                Log.e(TAG, "Error", e);
            }
            return somethingThatIsUsableInOnPostExecute;
        }

        @Override
        protected void onPostExecute(User result) {

            }
@覆盖
受保护用户doInBackground(列表…参数){
randomAPI=randomAPI
.getInstance(上下文);
试一试{
**会产生错误的东西**
}
}捕获(随机异常){
Log.e(标签“错误”,e);
}
返回一些在执行时可以使用的东西;
}
@凌驾
受保护的void onPostExecute(用户结果){
}
私有字符串异常=”;
@凌驾
受保护用户doInBackground(列表…参数){
randomAPI=randomAPI
.getInstance(上下文);
试一试{
**会产生错误的东西**
}
}捕获(随机异常){
Log.e(标签“错误”,e);
异常=e.getMessage();
}
返回一些在执行时可以使用的东西;
}
@凌驾
受保护的void onPostExecute(用户结果){
如果(!exception.isEmpty()){
//异常路径
}
}
私有字符串异常=”;
@凌驾
受保护用户doInBackground(列表…参数){
randomAPI=randomAPI
.getInstance(上下文);
试一试{
**会产生错误的东西**
}
}捕获(随机异常){
Log.e(标签“错误”,e);
异常=e.getMessage();
}
返回一些在执行时可以使用的东西;
}
@凌驾
受保护的void onPostExecute(用户结果){
如果(!exception.isEmpty()){
//异常路径
}
}
您应该尝试更改
return
doInBackground
类型
User
object到
object
并在
onPostExecute
中强制转换它

您应该尝试更改
return
doInBackground
类型
User
object到
object
并在
onPostExecute
中强制转换它


您可以像任何其他类一样将成员变量放入Asynctask中,我刚才说的和Asynctask无关。它是一个类似于任何其他Java类的类。您不知道“成员变量”是什么意思吗?您可以像任何其他类一样将成员变量放入Asynctask中。我刚才说的与Asynctask无关。它是一个类似于任何其他Java类的类。您不知道“成员变量”是什么意思吗?如果它对您有帮助,您可以将其标记为正确答案!非常感谢。我认为您应该在doInBackground中每次初始化exception=“”。如果这对您有帮助,您可以将其标记为正确答案!非常感谢。我认为您应该在doInBackground中每次初始化exception=”“。
private String exception = "";
@Override
    protected User doInBackground(List<Pair<String, String>>... params) {
        randomAPI api = randomAPI
                .getInstance(context);

        try {
            **thing that will generate error**
            }

        } catch (RandomException e) {
            Log.e(TAG, "Error", e);
            exception = e.getMessage();
        }
        return somethingThatIsUsableInOnPostExecute;
    }

    @Override
    protected void onPostExecute(User result) {
            if(!exception.isEmpty()){
                //exception path
            }
        }