I want to get string JSON response to the main activity after making the connection I know it is running in different thread so please help me how I can get it and then return it from this method;
public class MakeNetworkConnection {
private String mBaseUrl;
private String mApiKey;
private String mContentType;
private String mJsonResponce;
public MakeNetworkConnection(String baseUrl, String apiKey, String contentType) {
mBaseUrl = baseUrl;
mApiKey = apiKey;
mContentType = contentType;
}
public String startNetworkConnection() throws IOException {
OkHttpClient client=new OkHttpClient();
Request request=new Request.Builder().url("http://content.guardianapis.com/sections?api-key=1123456").build();
client.newCall(request).enqueue(new Callback() {
#Override
public void onFailure(Call call, IOException e) {
}
#Override
public void onResponse(Call call, Response response) throws IOException {
if(response.isSuccessful()){
mJsonResponce=response.body().string();
}
}
});
return mJsonResponce;
}
}
The problem here is about understanding how asynchronous tasks work. When you are calling client.newCall(request).enqueue(new Callback(), it will run in the background thread (off the main thread) and control will pass to the next line which is return mJsonResponce; And thus, it will always return null.
What you should do is to pass a callback method which will be called when the response is successful. You can create an interface to return the result:
public interface NetworkCallback {
void onSuccess(String repsonse);
void onFailure();
}
Pass an object of this interface while making the network request and call appropriate method when network request finishes.
One more thing you will have take care is that OkHttp doesn't return the response on the main thread so you will have to return the response on UI/main thread if you are going to update any UI. Something like this will work.
#Override
public void onResponse(Call call, Response response) throws IOException {
if(response.isSuccessful()){
new Handler(Looper.getMainLooper()).post(new Runnable() {
#Override
public void run() {
//return response from here to update any UI
networkCallback.onSuccess(response.body().string());
}
});
}
}
Instead of using calls asynchronously, you could use it synchronously with execute().
public String startNetworkConnection() throws IOException {
OkHttpClient client = new OkHttpClient();
Request request = new Request.Builder()
.url("http://content.guardianapis.com/sections?api-key=1123456")
.build();
return client.newCall(request)
.execute()
.body()
.string();
}
after advice from Rohit Arya i did the following:
public class OkHttpUtil {
public interface OKHttpNetwork{
void onSuccess(String body);
void onFailure();
}
public void startConnection(String url, final OKHttpNetwork okHttpCallBack) throws IOException {
OkHttpClient client=new OkHttpClient();
Request request=new Request.Builder()
.url(url)
.build();
client.newCall(request).enqueue(new Callback() {
#Override
public void onFailure(Call call, IOException e) {
}
#Override
public void onResponse(Call call, Response response) throws IOException {
if (response.isSuccessful()){
okHttpCallBack.onSuccess(response.body().string());
}
}
});
}
}
in the MainActvity i did the following :
OkHttpUtil okHttpUtil=new OkHttpUtil();
try {
okHttpUtil.startConnection("http://content.guardianapis.com/sections?api-key=8161f1e9-248b-4bde-be68-637dd91e92dd"
, new OkHttpUtil.OKHttpNetwork() {
#Override
public void onSuccess(String body) {
final String jsonResponse=body;
runOnUiThread(new Runnable() {
#Override
public void run() {
//show the response body
Toast.makeText(MainActivity.this,jsonResponse, Toast.LENGTH_SHORT).show();
}
});
}
#Override
public void onFailure() {
//do something
}
});
} catch (IOException e) {
e.printStackTrace();
}
Change this line
mJsonResponce=response.body().toString();
To
mJsonResponce=response.body().string();
Hope help you.
Related
I'm very new to android development. Trying to connect some site and get data from it. I have this function called only from onCreate in the main activity. Every time I turn virtual Android phone left or right I see new "run()" strings in EditText and requests in Wireshark. How to stop that properly?
Tried call.cancel() and mClient.dispatcher().cancelAll() inside OnResponse
protected void Load(String url) {
Request request = new Request.Builder()
.url(url)
.build();
mClient.newCall(request).enqueue(new Callback() {
#Override
public void onFailure(Call call, IOException e) {
e.printStackTrace();
}
#Override
public void onResponse(Call call, final Response response) throws IOException {
if (response.isSuccessful()) {
mHandler.post(new Runnable() {
#Override
public void run() {
mEdit.setText(mEdit.getText() + "run()\n");
}
});
}
}
});
}
retrofit supports enqueue canceling, and it works great.
And i think if you will try to run this code - your client enqueues would be stoped
protected void Load(String url) {
Request request = new Request.Builder()
.url(url)
.build();
Call<Response> mCall = mClient.newCall(request).enqueue(new Callback() {
#Override
public void onFailure(Call call, IOException e) {
if (call.isCanceled()) {
Log.e(TAG, "request was cancelled");
}
else {
Log.e(TAG, "other larger issue, i.e. no network connection?");
}
}
#Override
public void onResponse(Call call, final Response response) throws IOException {
if (response.isSuccessful()) {
mHandler.post(new Runnable() {
#Override
public void run() {
mEdit.setText(mEdit.getText() + "run()\n");
}
});
}
}
});
mCall.cancel();
}
I don't know you project structure and what kind of patterns you using(MVP, MVVM or else), but in simple, this code can be improved by returning Call
protected void Load(String url): Call<Response>
And then you can hadle you request status, and if it longer than 5 seconds for example, you call call.cancel() and request is stopping.
onCreate is called every time configuration changes (for example you rotate your phone/emulator). For more info: https://developer.android.com/guide/components/activities/activity-lifecycle
You can save your response to prevent new request on every onCreate. Something like this:
MainActivity {
private Response savedResponse;
onCreate() {
if (savedResponse == null) {
Load(url)
}
}
}
and in your onResponse save the response:
#Override
public void onResponse(Call call, final Response response) throws IOException {
if (response.isSuccessful()) {
savedResponse = response; // <----
mHandler.post(new Runnable() {
#Override
public void run() {
mEdit.setText(mEdit.getText() + "run()\n");
}
});
}
}
However, correct way would be to separete network calls/requests from activity lifecycle and load data somewhere else (Service, WorkManager, ...)
I have fragment and Common class which inside it used retrofit callback..I have Connect_and_get class.It sends request to server and gets information.I must use this information in my fragment.. But I can't return result onResponse.How can I do it..(Response is coming well from server)
Please see my code
public class Connect_and_Get {
private int size;
private OkHttpClient.Builder httpClient;
private ApiService client;
private Call<Response> call;
private MyPreference myPreference;
String a[] = {"secret"};
String b[] = {"secret"};
public int Connect_and_Get() {
Requests request;
request = new Requests("tasks.list", new params(20, 0, a, b, "", "", "", "", ""));
httpClient = new OkHttpClient.Builder();
httpClient.addInterceptor(new Interceptor() {
#Override
public okhttp3.Response intercept(Chain chain) throws IOException {
Request request = chain.request().newBuilder().addHeader("Authorization", "Bearer " + "secret").build();
return chain.proceed(request);
}
});
Retrofit retrofit = new Retrofit.Builder()
.baseUrl(Constants.baseUrl)
.addConverterFactory(GsonConverterFactory.create())
.client(httpClient.build())
.build();
client = retrofit.create(ApiService.class);
call = client.getDocument(request);
call.enqueue(new Callback<Response>() {
#Override
public void onResponse(Call<Response> call, retrofit2.Response<Response> response) {
size = response.body().getResult().getList().size();
}
#Override
public void onFailure(Call<Response> call, Throwable t) {
}
});
//retruning information
return size;
}
}
and result from common class coming 0;Because it doesn't wait my response so it is returning 0;
In fragment
Connect_and_Get a = new Connect_and_Get();
int getting = a.Connect_and_Get();
Log.d("mylog", "result:"+String.valueOf(getting));
Declare an interface like this
public interface ResponseListener {
public int onResponse(int size);
}
and use below code in your activity
public class MainActivity extends AppCompatActivity implements ResponseListener {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
new Connect_and_Get().Connect_and_Get(this);
}
#Override
public int onResponse(int size) {
// to do
return 0;
}
}
modify your connect class like this
public class Connect_and_Get {
public int Connect_and_Get(ResponseListener responseListener) {
// as it was
call.enqueue(new Callback<Response>() {
#Override
public void onResponse(Call<Response> call, retrofit2.Response<Response> response) {
size = response.body().getResult().getList().size();
responseListener.onResponse(size);
}
#Override
public void onFailure(Call<Response> call, Throwable t) {
}
});
}
}
You need to check whether your response is successful or not.
Check the code below.
call.enqueue(new Callback<Response>() {
#Override
public void onResponse(Call<Response> call, retrofit2.Response<Response> response) {
if(response.isSuccessful()){
//enter code here
} else {
//Error Message
}
}
#Override
public void onFailure(Call<Response> call, Throwable t) {
Log.e("Log", "Error -> "+t.getLocalizedMessage());
}
});
You can use an event bus like (rxbus,otto, etc..) to post events across your app when the response from the api ready to use .
Retrofit callback sample code:
call.enqueue(new Callback<Response>() {
#Override
public void onResponse(Call<Response> call, retrofit2.Response<Response> response) {
Bus.getInstance.post(Event)
}
#Override
public void onFailure(Call<Response> call, Throwable t) {
}
});
Fragment sample:
#Override
protected void onCreate(Bundle savedInstanceState) {
Bus.getInstance.register(this)
}
#Subscribe
public void onCallDone(Event response) {
//enter code here
}
I have web request helper class in my app using OKHttp3 via standard async method call. everything just work fine, but in my Splash Activity just for first run (after new installation) web request calling not work! but if I close the app and run again everything work fine.
here is my call back interface:
public interface WebResult<T> {
void onValue(T value);}
here is calling method
public void getStatus(final WebResult result) {
urlBuilder.addQueryParameter("action", "test");
urlBuilder.addQueryParameter("reqbody", cd.toJSON());
String url = urlBuilder.build().toString();
Request request = new Request.Builder()
.header("Authorization", AuthKey)
.url(url)
.build();
client.newCall(request).enqueue(new Callback() {
#Override
public void onFailure(Call call, IOException e) {
setHasError(true);
setMsg(e.getMessage());
}
#Override
public void onResponse(Call call, final Response response) throws IOException {
if (!response.isSuccessful()) {
throw new IOException("Unexpected code " + response);
} else {
iAct.runOnUiThread(new Runnable() {
public void run() {
try {
String s = response.body().string();
ServerStat r = new ServerStat();
r.fromJSON(s);
result.onValue(r);
return;
} catch (IOException e) {
}
}
});
}
}
});
}
and its my splash activity
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
context = this;
WebHelper wh = new WebHelper(context);
wh.getStatus(new WebResult() {
#Override
public void onValue(Object value) {
ServerStat r = (ServerStat) value;
if (r.getErrorCode() == 0) {
Toast.makeText(context, r.getErrorMsg(), Toast.LENGTH_LONG).show();
} else {
Toast.makeText(context, r.getErrorMsg(), Toast.LENGTH_LONG).show();
}
}
});
}
I replaced OKHttp3 with google Volley and it's work in my case!
Previously I would simply pass the response.body().string() to OnPostExecute() method of an asyncTask to update TextViews of the UI. okHttp doesn't seem to have this option. Where is the equivalent or how to achieve this?
//Call to server to echo MySQL query
private void usersInZone() {
if (!isNetworkAvailable()) return;
rotate(true);
OkHttpClient client = new OkHttpClient();
RequestBody formBody = new FormBody.Builder()
.add("userId", String.valueOf(userId))
.add("channel", String.valueOf(subport + port))
.build();
Request request = new Request.Builder()
.url(SITE_URL + "inZone.php")
.post(formBody)
.build();
Call users = client.newCall(request);
users.enqueue(caller);
}
//okHttp Callback to parse echo response
caller = new Callback() {
#Override
public void onFailure(Call call, IOException e) {
if (RS != null) RS.makePoor(true);
}
#Override
public void onResponse(Call call, Response response) throws IOException {
LOG.l(String.valueOf(call));
if (response.isSuccessful()) {
try {
JSONObject data = new JSONObject(response.body().string());
updateFields(getString(R.string.inzone) + data.getInt("total") + "]", String.valueOf(data.getInt("zone")));
} catch (JSONException e) {
LOG.l("JSONException" + e);
}
} else if (RS != null) RS.makePoor(true);
}
};
//UI textViews i'm needing to update with the echoed results
private void updateFields(String total, String channelTotal){
subtitle.setText(total);
tvusercount.setText(channelTotal);
}
Where is the equivalent or how to achieve this?
OkHttp's onResponse() is not called on main thread. If you want to update UI in onResponse you must delegate this task to UI thread. Using Handler and posting Runnable is one way of doing so.
The callback is not called on the main thread. If you need to update the UI, a simple way to do that is to create a class that implemented Callback and post the items to the UI like so:
public abstract class UIMainCallback implements Callback {
private static final Handler mUIHandler = new Handler(Looper.getMainLooper());
abstract void failure(Request request, IOException e);
abstract void response(Response response);
#Override
public void onFailure(final Request request, final IOException e) {
mUIHandler.post(new Runnable() {
#Override
public void run() {
failure(request, e);
}
});
}
#Override
public void onResponse(final Response response) throws IOException {
mUIHandler.post(new Runnable() {
#Override
public void run() {
response(response);
}
});
}
}
Then your Caller can just implement the UIMainCallback instead of the interface.
I need make POST request with parameters "guid=1" in Body. i use Retrofit2
I try :
#POST("/api/1/model")
Call<ApiModelJson> getPostClub(#Body User body);
User Class:
public class User {
#SerializedName("guid")
String guid;
public User(String guid ) {
this.guid = guid;
}
MailActivity:
User user =new User ("1");
Call<ApiModelJson> call = service.getPostClub(user);
call.enqueue(new Callback<ApiModelJson>() {
#Override
public void onResponse(Response<ApiModelJson> response) {
}
#Override
public void onFailure(Throwable t) {
dialog.dismiss();
}
How make this request?
you have to call call.enqueue, providing an instance of Callback< ApiModelJson>, where you will get the response. enqueue executes your backend call asynchronously. You can read more about call.enqueue here
With code below, you can make the request synchronously:
ApiModelJson responseBody = call.execute();
If you want it to be asynchronous:
call.enqueue(new Callback<ApiModelJson>() {
#Override
public void onResponse(Response<ApiModelJson> response, Retrofit retrofit) {
}
#Override
public void onFailure(Throwable t) {
}
});