i'm working on an app that need to do a GET request to update a TextView on screen, now im doing it with a button but i need to update the textview constantly. what's the best way or practice to do it? here the code of the request, the button just call it and put the response string on the TextView.
protected void getEquiposHTTP() {
//Método GET HTTP al servicio Cloudant IBM para las credenciales dadas
final OkHttpClient client = new OkHttpClient();
Uri.Builder builder = new Uri.Builder();
builder.scheme("https")
.authority("data")
.appendPath("data")
.appendPath("data")
.appendPath("data")
.appendPath("data")
.appendPath("data")
.appendQueryParameter("data", "data");
String myUrl = builder.build().toString();
byte[] encoding = Base64.encodeBase64(("data" + ":" + "data").getBytes());
String encodedString = new String(encoding);
final Request request = new Request.Builder()
.url(myUrl)
.addHeader("Content-Type", "application/json")
.addHeader("Authorization", "Basic " + encodedString)
.addHeader("cache-control", "no-cache")
.build();
client.newCall(request).enqueue(new Callback() {
#Override
public void onFailure(Call call, IOException e) {
String mMessage = e.getMessage().toString();
call.cancel();
Log.e(TAG, "Problem at HTTP connection and call.cancel() executed");
}
#Override
public void onResponse(Call call, Response response) throws IOException {
if (response.isSuccessful()) {
try {
addToListEquipos(response.body().string());
} catch (Exception e) {
Log.e(TAG, "Problem at response of HTTP conection, response.isSuccessful() = true then try{} fail");
}
}
}
});
}
One way to achieve this is by running a thread which keeps hitting the server in small intervals to fetch the new data and update the ui. This is not the appropriate way to do things because app will keep hitting the server again and again even in case of no update.
The second way (which is more preferred one but needs extra efforts) is by using something like Push-notification, Firebase Realtime Database
or XMPP server. This way your server will tell the client app about the new data.
From the official site of Firebase Realtime Database
The Firebase Realtime Database is a cloud-hosted database. Data is stored as JSON and synchronized in realtime to every connected client. When you build cross-platform apps with our iOS, Android, and JavaScript SDKs, all of your clients share one Realtime Database instance and automatically receive updates with the newest data.
Related
i am new to Android Studio and making app using WordPress Website as backend , i want users ti post comment on posts which is working well but i want to tell users if their comment has been submitted successfully or got any error.. this is my code
OkHttpClient httpClient = new OkHttpClient();
Request request = new Request.Builder()
.url("https://www.sikhnama.com/?json=respond/submit_comment&post_id=" + Postid
+ "&name=" + name + "&email=" + email + "&content=" + comment)
.build();
try {
Response response = httpClient.newCall(request).execute();
runOnUiThread(new Runnable() {
public void run() {
Toast.makeText(getApplicationContext(),"Hello Javatpoint",Toast.LENGTH_SHORT).show();
}
});
} catch (IOException e) {
e.printStackTrace();
Log.d("Comment", "Comment Failed");
}
i have log "comment failed" but it never comes even if failed comment.. please help
See the documentation for OkHttpClient. Execution of the call will not throw an exception in case of an http error response code (and it would be a very bad library design if it did so), only on network failure, interruption etc.
You can check the reponse.isSuccessful() and log your "comment failed" message or whatever.
I'm want to consume share point rest API service to call from Android previously i use to call share point web service through the graph API but while generating token from graph API its not support in below URL, does any one have any solution about this problem.
https://mysharepoint.sharepoint.com/sites/MySite/_api/web/lists/getbytitle('Announcements')/Items
JsonObjectRequest request = new JsonObjectRequest(Request.Method.GET, MSGRAPH_URL,
parameters,new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject response) {
/* Successfully called graph, process data and send to UI */
Log.d(TAG, "Response: " + response.toString());
updateGraphUI(response);
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Log.d(TAG, "Error: " + error.toString());
}
}) {
#Override
public Map<String, String> getHeaders() throws AuthFailureError {
Map<String, String> headers = new HashMap<>();
headers.put("Authorization", "Bearer " + authResult.getAccessToken());
return headers;
}
};
Log.d(TAG, "Adding HTTP GET to Queue, Request: " + request.toString());
request.setRetryPolicy(new DefaultRetryPolicy(
3000,
DefaultRetryPolicy.DEFAULT_MAX_RETRIES,
DefaultRetryPolicy.DEFAULT_BACKOFF_MULT));
queue.add(request);
I already tried with MSAL library but its does not work with this token.
Update: i used to call graph api for janrating token but i got 401 error with this above mention URL.
You are calling a SharePoint API, so you will need a SharePoint token instead of a Graph token. These are two separate APIs with different authentications.
To get a SharePoint token you will need to register an App in SharePoint itself or use the users username + password if available in your app.
Also see:
https://spshell.blogspot.com/2015/03/sharepoint-online-o365-oauth.html
https://shareyourpoint.net/2017/01/25/operations-using-rest-in-sharepoint-online-authorization/
For Graph, use an URL like this to get your list items:
https://graph.microsoft.com/v1.0/sites/{site-id}/lists/{list-id}/items?expand=fields(select=Column1,Column2)
You will probably need to do several calls to get your site ID and list ID first.
https://learn.microsoft.com/en-us/graph/api/listitem-list?view=graph-rest-1.0
I am trying to create an android app in which a user enters login details and the data is validated on server ,for server i am using xampp.I want to get the value shown on the php result page in android app and show it to the user using Toast.
#Override
protected Boolean doInBackground(Void... params) {
// TODO: attempt authentication against a network service.
Toast.makeText(getApplicationContext(),"Problem is in http", Toast.LENGTH_LONG).show();
String result;
OkHttpClient client = new OkHttpClient();
Request request = new Request.Builder()
.url("http:192.168.0.102/db.php?username=tkajbaje#gmail.com&password=123456")
.build();
Response response = null;
try {
response = client.newCall(request).execute();
} catch (IOException e) {
e.printStackTrace();
}
result=response.toString();
Toast.makeText(getApplicationContext(),result, Toast.LENGTH_LONG).show();
// TODO: register the new account here.
return true;
}
When I run the app it exits unexpectedly,what could be the problem?Apologies if some important information is missing regarding question.
This is certainly problematic
try {
response = client.newCall(request).execute();
} catch (IOException e) {
e.printStackTrace();
}
You are catching and logging the error but continuing, so response can be null.
There are other issues with the code
You are creating a new OkHttp instance for each call
it's unclear if you are actually running this on a background thread
IIRC Toast.show should be on UI thread, but okhttp calls should be background
I'm trying to create a websocket and dynamically recalculate its header in every message sent. Is it possible?
I was trying to use an interceptor but is only called once.
public void run() {
// only open a websocket if there aren't websockets already open
if (this.webSocket == null || !this.openingWS) {
this.openingWS = true;
wsBuilder = new OkHttpClient.Builder();
OkHttpClient client = wsBuilder.addInterceptor(this)
.readTimeout(0, TimeUnit.MILLISECONDS)
.build();
Request request = new Request.Builder()
.url("wss://...")
.build();
client.newWebSocket(request, this);
// Trigger shutdown of the dispatcher's executor so this process can exit cleanly.
client.dispatcher().executorService().shutdown();
}
}
#Override public void onOpen(WebSocket webSocket, Response response) {
this.openingWS = false; // already open
this.webSocket = webSocket; // storing websocket for future usages
if (listener != null) listener.onWSOpen();
}
public void sendCommand(String cmd) {
System.out.println("SEND " + cmd);
if (webSocket != null) webSocket.send(cmd);
}
This same class is implementing the interceptor
public Response intercept(Chain chain) throws IOException {
Request originalRequest = chain.request();
if (!isSpecial()) return chain.proceed(originalRequest);
okhttp3.Request.Builder builder = originalRequest.newBuilder()
.addHeader("text", "...")
.addHeader("dfds", "...");
Request compressedRequest = builder.build();
return chain.proceed(compressedRequest);
}
The authentication code sent in the header will change every X seconds/minutes.
If it's not possible to change dynamically the header, what is the best way to approach this kind of connection?
Thank you for your help.
I think the headers are send only first time when you request the connection, later is depends on frames between the client and the server.
So if you want to inform the server that you had changed the header then send message with your new header. Or you can close the connection and start a new one with the new header.
I am using:
Andorid Studio.
Okhttp 2.4.0 with AsyncTask. But I can't cancel a request.
Connected to server on wi-fi. And if server is off then okHttp keeps trying to connect, and I can't cancel it.
time outs is working but i want to cancel before timeouts
private OkHttpClient client = new OkHttpClient();
client.setConnectTimeout(30000, TimeUnit.MILLISECONDS);
after execute I press special cancel button in my api
public void onCancelClick(View v){
BaseApplication.getInstance().server.cancel();
synchProducts.cancel(true);
}
first line must stoped okHttp, second line stoped class extended AsyncTask
private static final String myTag = "AsyncCall";
public void cancel(){
client.cancel(myTag);
}
backGround in AsyncTask class
#Override
protected String doInBackground(Void... params) {
publishProgress(1);
String responseStr = sendProductHeaders();
//this performed after timeouts, and spit to my cancel okHttp
publishProgress(2);
if (responseStr != null && !isCancelled()){
ProductsList productsForSend = parseProducts(responseStr);
//correctly stoped thread
I didn't forget to use .tag in the builder request
public Response post(String url, String json) {
RequestBody body = RequestBody.create(JSON, json);
Request request = new Request.Builder()
.tag(myTag)
.url(url)
.post(body)
.build();
return call(request);
}
"call" is my method which makes the okHttp call
private Response call(Request request){
try {
return client.newCall(request).execute();
} catch (IOException e) {
Log.e("Aync call", "IO exception " + e.getMessage());
}
return null;
}
"Tags" is true, code in okHttp Library realy fires call.cancel();
for (Call call : executedCalls) {
if (Util.equal(tag, call.tag())) {
call.cancel();
}
}
method which is running Async
public void onRefreshProducts(View v){
progressLayout.setVisibility(View.VISIBLE);
progressBar.setProgress(0);
synchProducts = new SynchProducts(activityCallBack);
synchProducts.execute();
}
"activityCallBack" is the interface I use when I call to my activity from AsyncTask class
i don't want to use okHttp enqueue, but I can't insert a friendly progress bar in my app.
Thanks!
Try updating the library to okhttp 2.5.0 and use the cancel() method. The ChangeLog for 2.5.0 mentions the following:
Call canceling is more reliable. We had a bug where a socket being connected wasn't being closed when the application used Call.cancel().
Hopefully it will fix the issue.