我是 JAVA 新手,但在 C/C++ 等其他语言方面有经验。我正在研究 android,现在创建一个访问 JSON Web 服务的应用程序。
我的课程代码如下:
public class AsycTaskCall {
private final JSONObject jsonObject;
private final Context context;
public static String results;
public AsycTaskCall(Context ctx, JSONObject jobject)
{
this.jsonObject = jobject;
this.context = ctx;
}
public String call()
{
new WebServiceTask().execute("");
Log.d("RESULTS_CALL", "Results : " + results); //results is null here
return this.results;
}
private class WebServiceTask extends AsyncTask<String, Void, String> {
protected String doInBackground(String... args) {
JsonWebService jsonWebService = new JsonWebService(context);
return jsonWebService.callWebService(jsonObject);
}
protected void onPostExecute(String result) {
try
{
JSONObject jo = new JSONObject(result);
String status = jo.getString("success");
results = result;
if (status == "true")
{
Log.d("RESULTS", " Result : " + result + " : Results " + results); // results is fine here also
}
else
{
Log.d("RESULT_STATUS", "False");
}
} catch (JSONException e) {
e.printStackTrace();
}
}
}
}
我创建了这个类,因为我的应用程序将在很多地方调用 Web 服务,所以我想创建一个类,并将 JSONObject 传递给它,然后这个类调用 Web 服务异步。
一切正常,我得到了所需的结果,但现在我想将结果返回给调用活动。为此,我创建了一个
public static String results;
属性并将从 web 服务返回的字符串保存在此变量中。该变量在子类 WebServiceTask 中有数据,但在同一个变量中,主类中的数据为空,或者当我在主类调用函数中返回时,它为空。
请告诉我如何解决这个问题。
谢谢