Android : can't update member variable

on Thursday, April 16, 2015


Somehow line mResponseText = response.body().string(); isn't writing member variable. Instead it appears to be creating and logging it locally.


Any ideas why? The more I look at it the more clueless I'm getting :(



public class Gateway extends Activity {
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' , 'nickname' : 'fake', 'created':'now', 'parent_class':''}]";



public Gateway (String url, String json, 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(Gateway.this, "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, "RESPONSE IS SUCCESSFUL");
Log.v(TAG, mResponseText);
} else {
alertUserAboutError();
}
}
});
} else {
Toast.makeText(this, "No network", Toast.LENGTH_LONG).show();
}

}

public String getResponse () { 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() {
AlertDialogFragment dialog = new AlertDialogFragment();
dialog.show(getFragmentManager(), "error_dialog");
}
}

0 comments:

Post a Comment