gpt4 book ai didi

java - 无法更新成员变量

转载 作者:行者123 更新时间:2023-12-02 04:45:36 26 4
gpt4 key购买 nike

不知何故,行mResponseText = response.body().string();没有写入成员变量。相反,它似乎是在本地创建并记录它。

有什么想法吗?我越看越觉得无能为力:(

public class Gateway {
private static final String TAG = Gateway.class.getSimpleName();
public static final MediaType JSON
= MediaType.parse("application/json; charset=utf-8");
private String mResponseText = "[{'comment' : 'fake' , 'psn_nickname' : 'fake', 'created':'now', 'parent_class':''}]";



public Gateway (String url, String json, final Context context) {

if(isNetworkAvailable(context)) {
//if network is available build request

OkHttpClient client = new OkHttpClient();
// RequestBody body = RequestBody.create(JSON, json);
Request request = new Request.Builder()
.url(url)
//.post(body)
.build();

Call call = client.newCall(request);
call.enqueue(new Callback() {
//execute call
@Override
public void onFailure(Request request, IOException e) {
// if request failed
Toast.makeText(context, "request failed", Toast.LENGTH_LONG).show();
}

@Override
public void onResponse(Response response) throws IOException {
// if succeeded
if(response.isSuccessful()){
mResponseText = response.body().string();
Log.v(TAG, "SETTING RESPONSE");
// THIS LOGS PROPER JSON LOADED FROM NETWORK
Log.v(TAG, mResponseText);

} else {

//alertUserAboutError(context);
Toast.makeText(context, "Something wrong with response", Toast.LENGTH_LONG).show();
}
}
});
} else {
Toast.makeText(context, "Network is not available", Toast.LENGTH_LONG).show();
}

}

public String getResponse () {
Log.v(TAG, "GETTING RESPONSE");
// THIS LOGS FAKE SAMPLE JSON --- WTF???
Log.v(TAG, mResponseText);
return mResponseText;
}


// check if network is available
private boolean isNetworkAvailable(Context c) {
ConnectivityManager manager = (ConnectivityManager) c.getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo networkInfo = manager.getActiveNetworkInfo();
boolean isAvailable = false;
if (networkInfo != null && networkInfo.isConnected()) {
isAvailable = true;
}

return isAvailable;
}
/*
private void alertUserAboutError(Context c) {
AlertDialogFragment dialog = new AlertDialogFragment();
dialog.show(c.getFragmentManager(), "error_dialog");
}
*/
}

这是使用此类的代码

Gateway gateway = new Gateway(mCommentURL, "", this);
String mJsonData = gateway.getResponse();

编辑代码更新 - 删除扩展 Activity

最佳答案

您调用 getResponse() 太早了。异步操作尚未完成,返回的值是您首先初始化的值,而不是 Callback 中写入的值。

将使用响应的代码放入回调中,或从回调中调用该代码。

关于java - 无法更新成员变量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29684007/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com