【发布时间】:2014-10-04 12:45:49
【问题描述】:
在下面的代码中,我无法从 getValue 类中获得结果,这就是返回 null 但这必须是返回值。结果是正确的,此函数无法返回。例如这是我的课:
public class JsonService {
private JSONObject json = new JSONObject();
public JsonService(final String username, final String password) throws Exception{
json.put("username", username);
json.put("password", password);
}
public class Foo implements Runnable {
private String result;
@Override
public void run() {
HttpClient client = new DefaultHttpClient();
HttpConnectionParams.setConnectionTimeout(client.getParams(), 10000);
HttpResponse response;
try {
HttpPost post = new HttpPost("http://www.example.com/json_android.php");
StringEntity se = new StringEntity( json.toString());
se.setContentType(new BasicHeader(HTTP.CONTENT_TYPE, "application/json"));
post.setEntity(se);
response = client.execute(post);
if(response!=null){
InputStream stream = response.getEntity().getContent();
result = convertToString(stream);
/*
I can Log result with below line
*/
Log.e("response is: ", result);
/*
result is {"username = ":"Hello"}
*/
}
} catch(Exception e) {
e.printStackTrace();
Log.e("Error", String.valueOf(e));
}
}
public String getValue() {
/*
return in this fucntion not working
*/
return result;
}
}
public String request() throws ExecutionException, InterruptedException {
Foo foo = new Foo();
new Thread(foo).start();
return foo.getValue();
}
如何从Foo 正确获取结果并从reauest() 返回?请帮我。谢谢
【问题讨论】:
标签: java android android-handler