我有一个buttons
和TextView
的自定义适配器,TextView
在button
点击listview
之后发生变化,发送和接收反馈后从http
Post
到Json
回复,我尝试使用runnable
和assynctask
,但没有成功。在runnable中,我无法从方法返回值。
我想要的是向服务器发送http
请求并返回json
结果,根据返回的结果,TextView
会发生变化。
实现这一目标的最佳方法是什么。
如果有人能帮我指出一个能帮助我实现这一目标的资源,那将非常受欢迎。
提前致谢!
这是我的代码..
public String getStatus(final String id, final String user){
final String[] resp = {"0/0/0"};
new Thread(new Runnable() {
@Override
public void run() {
// Building Parameters
final List<NameValuePair> params = new ArrayList<NameValuePair>();
params.add(new BasicNameValuePair("username", user));
params.add(new BasicNameValuePair("id", id));
Log.d("Nay Params", "" + params);
// getting product details by making HTTP request
JSONObject json = jsonParser.makeHttpRequest(NAY_URL, "POST",
params);
// check your log for json response
// json success tag
try {
Log.d("Nay Response", ""+ json);
success = json.getBoolean(TAG_SUCCESS);
yeaSt = json.getBoolean(TAG_E_STATUS);
naySt = json.getBoolean(TAG_A_STATUS);
yeaC = json.getInt(TAG_YEA);
nayC = json.getInt(TAG_NAY);
if (success){
resp[0] = yeaS + "/" + naySt + "/" + yeaC + "/" + nayC;
return resp[0];
//Can not return return value within void method that is; Class void run()
}
} catch (JSONException e) {
e.printStackTrace();
//return resp[0];
}
}
}).start();
//Can not acces json result outside the try catch block
Log.d("sux", ""+success);
// Log.d("Rest1", resp[0]);
return resp[0];
}
答案 0 :(得分:1)
您可以使用Callable接口来运行线程并获取线程的结果。
这是Callable documentation。
雅各布解释了如何使用它here。
希望有所帮助,如果您需要一个具体的例子,我最近在我的项目中使用了这种方法,我很乐意为您提供样本。
修改强> 这是一个使用callable的简单示例,我更改了一些代码,因此更清楚:
public class Test {
ExecutorService executor;
public Test() {
/* I used an executor that creates a new thread every time creating a server requests object
* you might need to create a thread pool instead, depending on your application
* */
executor = Executors.newSingleThreadExecutor();
}
private JSONObject doTheWork() {
// init
Callable<JSONObject> callable;
Future<JSONObject> future;
JSONObject jsonResult = null;
try {
// create callable object with desired job
callable = new Callable<JSONObject>() {
@Override
public JSONObject call() throws Exception {
JSONObject jsonResult = new JSONObject();
// connect to the server
// insert desired data into json object
// and return the json object
return jsonResult;
}
};
future = executor.submit(callable);
jsonResult = future.get();
} catch(InterruptedException ex) {
// Log exception at first so you could know if something went wrong and needs to be fixed
} catch(ExecutionException ex) {
// Log exception at first so you could know if something went wrong and needs to be fixed
}
return jsonResult;
}
}
另一种方法是创建一个实现Callable的类。无论你选择哪种方法取决于你的应用,也许还有人的口味:)。 我很乐意帮助你。