Java 从其他活动中的AsyncTask返回值
这是密码,对不起我的英语 错误是:Java 从其他活动中的AsyncTask返回值,java,android,android-asynctask,Java,Android,Android Asynctask,这是密码,对不起我的英语 错误是:NullPointerException。一个活动类“菜单”,一个类客户和一个返回值接口 public interface AsyncResponse { void processFinish(String output); } public class Cliente extends AsyncTask<String, String, String> { public AsyncResponse delegate = null;
NullPointerException
。一个活动类“菜单”,一个类客户和一个返回值接口
public interface AsyncResponse {
void processFinish(String output);
}
public class Cliente extends AsyncTask<String, String, String> {
public AsyncResponse delegate = null; //
public Cliente(AsyncResponse delegate) {
this.delegate = delegate;
}
public Cliente(String type) {
this.excute();
}
// in method doInBackground return correctly string
protected void onPostExecute(String result) {
// Log.d("OutPut",result); // it's ok String!
if (result == null)
Log.d("OUTPUT", "NULL"); // for example
else
delegate.processFinish(result); // --- ERROR !! --- but result not NUll
}
}
代码的问题在于,在第三行中,您正在创建客户机的新实例,而没有设置委托。要修复此问题,您只需运行
Cliente asyncTask =new Cliente(this);
asyncTask.execute();
实现这个构造函数
public Cliente(AsyncResponse delegate) {
this.delegate = delegate;
this.execute();
}
“类型”在这里没有用处
召唤
new Cliente(this);
将启动任务这需要正确理解一些格式。。。只是说;-)在活动中显示代码processFinish是否可以发布堆栈跟踪?还有,任务从哪里开始?很明显,这个实例没有存储在变量中,但如果没有更多的信息,我们不能说太多。。。我们甚至不知道OP在哪里调用execute()
(但我们知道他在哪里调用,因为他在任务回调中得到了错误)。我们实际上知道。看看将字符串作为参数@JoffreyThanks的构造函数!这是工作!修正:),但为什么主活动中的asyncTask.execute有效,而构造函数“this.execute”中的“this.execute”无效(变量为death)?因为您创建了一个新对象,并且没有为委托分配有效的引用。@blackbelt My bad,这太意外了,以至于我没有在该构造函数中看到execute()
!我在提供的代码中搜索它,但是打字错误阻止了搜索。。。
public Cliente(AsyncResponse delegate) {
this.delegate = delegate;
this.execute();
}
new Cliente(this);