I use the JSONObject forecast = new JSONObject(response.body().string()) to get the weather information, but android monitor always show "org.json.JSONException: End of input at character 0 of ".
import android.app.AlertDialog;
import android.app.Dialog;
import android.content.Context;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.os.Bundle;
import android.os.Debug;
import android.support.design.widget.FloatingActionButton;
import android.support.design.widget.Snackbar;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.util.Log;
import android.view.View;
import android.view.Menu;
import android.view.MenuItem;
import android.widget.Toast;
import org.json.JSONException;
import org.json.JSONObject;
import java.io.IOException;
import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;
public class MainActivity extends AppCompatActivity {
private static final String TAG = MainActivity.class.getSimpleName();
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
if(isconnected()){
String url = "https://api.forecast.io/forecast/2d0f15adaeff2c8e1343201418843890/37.8267,-122.423";
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()) {
Log.d(TAG, response.body().string());
String a=response.body().string();
try {
JSONObject forecast = new JSONObject(a);
} catch (JSONException e) {
e.printStackTrace();
}
} else {
alertUserAboutError();
}
}
});
}
else{
Toast.makeText(MainActivity.this,"LOST CONNECTION",Toast.LENGTH_SHORT).show();
}
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
getSupportActionBar().hide();
FloatingActionButton fab = (FloatingActionButton) findViewById(R.id.fab);
fab.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Snackbar.make(view, "Replace with your own action", Snackbar.LENGTH_LONG)
.setAction("Action", null).show();
}
});
}
private boolean isconnected() {
ConnectivityManager cm =
(ConnectivityManager)MainActivity.this.getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo activeNetwork = cm.getActiveNetworkInfo();
boolean isConnected = activeNetwork != null &&
activeNetwork.isConnectedOrConnecting();
return isConnected;
}
private void alertUserAboutError() {
AlertDialogFragment alertDialogFragment = new AlertDialogFragment();
alertDialogFragment.show(getSupportFragmentManager(), "error");
}
}
I use the Log.d(TAG, response.body().string()) to test it is a string, but when in JSONObject forecast = new JSONObject(response.body().string()), it will not work.
For some weird reason if you use .string() >1 time, response turns out to be empty. Try to use it only once when parsing Retrofit response.
Someone, who knows why it happens like this, please improve my answer.
Answer : Response object should of Generic type - ResponseBody.
See below Correct code for reference.
Now response.body() method will return object ResponseBody
i.e.
ResponseBody rb = response.body();
rb.string();
Here ResponseBody have method string() which returns String object but internally string() method calls Util.closeQuietly(source); which makes response empty once method string() gets called.
Just remove Log.d(TAG, response.body().string()); and follow below code.
Reference - okhttp3.ResponseBody.java
error : org.json.JSONException: End of input at character 0
Correct code :
#Override
public void onResponse(Call call, Response<ResponseBody> response) throws IOException {
if (response.isSuccessful()) {
String remoteResponse=response.body().string();
Log.d(TAG, remoteResponse);
try {
JSONObject forecast = new JSONObject(remoteResponse);
} catch (JSONException e) {
e.printStackTrace();
}
}
}
Sometimes the probleme is th URL, if your website forces HTTPS, you have to make sure that you are using an HTTPS URL in your APP, and vice-versa if your website doesn't support HTTPS, you have to use an HTTP URL.
I have solved this problem after moving the "String a=response.body().string()" before "if (response.isSuccessful())".
Related
I have written a code to access the below api and get the corresponding values of namaz timings, but the onResponse method is not getting invoked. I have given internet permissions in the android manifest file. I am new to Android, please help.
While Installing app is not asking for internet permissions though I mentioned it in manifest file.
import android.app.ProgressDialog;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
import android.widget.Toast;
import com.android.volley.Request;
import com.android.volley.RequestQueue;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.VolleyLog;
import com.android.volley.toolbox.JsonObjectRequest;
import com.android.volley.toolbox.Volley;
import org.json.JSONException;
import org.json.JSONObject;
public class NamazTiming extends AppCompatActivity {
private TextView fazarId, zoharid, asarid, magribid, ishaid, location;
private RequestQueue mQueue;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.namaz_timing);
Toolbar toolbar = findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
getSupportActionBar().setTitle("Namaz Timings");
fazarId = findViewById(R.id.fazarid);
zoharid = findViewById(R.id.zoharid);
asarid = findViewById(R.id.asarid);
magribid = findViewById(R.id.magribid);
ishaid = findViewById(R.id.ishaid);
location = findViewById(R.id.location);
Button locationbutton = findViewById(R.id.locationbutton);
mQueue = Volley.newRequestQueue(this);
locationbutton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
jsonParse();
}
});
}
private void jsonParse() {
//String loc = location.getText().toString().trim();
String url ="https://muslimsalat.com/uravakonda.json?key=ba8d0b5ba55c6db3cebbe3fefd6090f8";
JsonObjectRequest request = new JsonObjectRequest(Request.Method.GET, url, null, new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject response) {
Toast.makeText(NamazTiming.this, "Entered onresponse", Toast.LENGTH_SHORT).show();
try {
Toast.makeText(NamazTiming.this, "Entered into TRY", Toast.LENGTH_SHORT).show();
String Fazar = response.getJSONArray("items").getJSONObject(0).get("fajr").toString();
String Zohr = response.getJSONArray("items").getJSONObject(0).get("dhuhr").toString();
String Asar = response.getJSONArray("items").getJSONObject(0).get("asr").toString();
String Magrib = response.getJSONArray("items").getJSONObject(0).get("maghrib").toString();
String Isha = response.getJSONArray("items").getJSONObject(0).get("isha").toString();
fazarId.setText(Fazar);
zoharid.setText(Zohr);
asarid.setText(Asar);
magribid.setText(Magrib);
ishaid.setText(Isha);
} catch (JSONException e) {
e.printStackTrace();
Toast.makeText(NamazTiming.this, "Please enter the lccation name", Toast.LENGTH_SHORT).show();
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
error.printStackTrace();
Toast.makeText(NamazTiming.this, "Please enter the lccation name", Toast.LENGTH_SHORT).show();
}
});
}
You need to add your request object to the Volley queue (in your case, mQueue) in order for the request to be executed.
Example:
mQueue.add(request);
Internet permission is normal permission so the android system will not ask internet permission.
You just call this line:
mQueue.add(request);
end of the request.
Add below line after errorListener method at end of your request
mQueue.add("your request type");
The app does the following initially
Get data from user including image and store in Sqlite database.
image path is stored in Sqlite db.
The aim of the app is to upload the data automatically and I am able to do that successfully using BroadcaseReciever for text using Volley but stuck as I don't know how the process to upload the image from Android.
I am able to retrieve the image path from the database but not sure what to do next.
I have done fair research but not getting solution when comes to upload image to server from imagepath stored in Sqlite.
Below is image path example stored in sqlite. ( I am a beginner in Android)
/storage/emulated/0/Pictures/1547728376728.jpg
Below code that I am working from.
PS : I believe the purpose of getimagepath method would be to 1. find the image 2. convert it into bytes 3. pass to Volley. I am stuck on 1. and the code might be wrong.
package com.example.narendra.e5.activities.Connectivity;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.net.Uri;
import android.provider.MediaStore;
import android.util.Base64;
import android.widget.Toast;
import com.android.volley.AuthFailureError;
import com.android.volley.Request;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.StringRequest;
import com.example.narendra.e5.activities.database.DatabaseHelper;
import com.example.narendra.e5.activities.others.AppSingleton;
import com.example.narendra.e5.activities.others.MySingleton;
import org.json.JSONException;
import org.json.JSONObject;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.util.HashMap;
import java.util.Map;
public class NetworkMonitor extends BroadcastReceiver {
Context context;
public Bitmap bitmap;
#Override
public void onReceive(final Context context, Intent intent) {
if (checkNetworkConnection(context)){
Toast.makeText(context, "Hello hello", Toast.LENGTH_LONG).show();
final DatabaseHelper db=new DatabaseHelper(context);
SQLiteDatabase database=db.getWritableDatabase();
Cursor cursor=db.getdataIncoming(database);
while (cursor.moveToNext()){
final String incoming=cursor.getString(cursor.getColumnIndex(DatabaseHelper.INCOMINGTIME));
Toast.makeText(context, incoming, Toast.LENGTH_LONG).show();
final String INVENID=cursor.getString(cursor.getColumnIndex(DatabaseHelper.INVENIDAPP));
final String imageurl=cursor.getString(cursor.getColumnIndex(DatabaseHelper.SLIP_IMAGE));
// get image path from database and convert it into bitmap
// Uri uri = Uri.parse(imageurl);
// bitmap=MediaStore.Images.Media.getBitmap();
StringRequest stringRequest=new StringRequest(Request.Method.POST, DatabaseHelper.SERVER_URL,
new Response.Listener<String>() {
#Override
public void onResponse(String response) {
try {
JSONObject jsonObject=new JSONObject(response);
String getResponse=jsonObject.getString("response");
if (getResponse.equals("OK")){
Toast.makeText(context, "Response ok", Toast.LENGTH_LONG).show();
//db.deleteOfflineSaveOutgoingDetails(INVENID);
}
} catch (JSONException e) {
e.printStackTrace();
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Toast.makeText(context, "Response error", Toast.LENGTH_LONG).show();
}
}
){
#Override
protected Map<String, String> getParams() throws AuthFailureError {
Map<String,String> params=new HashMap<>();
params.put("name",incoming);
// params.put("image",getimagepath(imageurl));
return params;
}
}
;
MySingleton.getInstance(context).addToRequestQue(stringRequest);
}
}
}
public boolean checkNetworkConnection(Context context){
ConnectivityManager connectivityManager= (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo networkInfo=connectivityManager.getActiveNetworkInfo();
return (networkInfo!=null && networkInfo.isConnected());
}
public String getimagepath(Intent imageurl){
// File imagepath=new File(String.valueOf(imageurl));
ByteArrayOutputStream byteArrayOutputStream=new ByteArrayOutputStream();
Uri imagePath = imageurl.getData();
bitmap=BitmapFactory.decodeFile(String.valueOf(imagePath));
bitmap.compress(Bitmap.CompressFormat.JPEG,60,byteArrayOutputStream);
byte[] imgByte=byteArrayOutputStream.toByteArray();
return Base64.encodeToString(imgByte,Base64.DEFAULT);
}
}
For POST you can use JsonObjectRequest like this way. No need to override getParams method.
HashMap<String,String> maps=new HashMap<>();
maps.put("name",incoming);
maps.put("image",getimagepath(imageurl));
JsonObjectRequest jsonObjectRequest=new JsonObjectRequest(Request.Method.POST, YOUR_URL, new JSONObject(maps), new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject response) {
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
}
});
jsonObjectRequest.setTag("TAG");
jsonObjectRequest.setRetryPolicy(new DefaultRetryPolicy(2,0f));
VolleySingleton.getInstance(context).addToRequestQueue(jsonObjectRequest);
I resolved the issue by correcting the method public String getimagepath(Intent imageurl)
to this:
public String getimagepath(String imageurl){
// File imagepath=new File(String.valueOf(imageurl));
ByteArrayOutputStream byteArrayOutputStream=new ByteArrayOutputStream();
//Uri imagePath = imageurl.getData();
if (imageurl !=null){
// Uri imagePath = Uri.fromFile(new File(imageurl));
bitmap=BitmapFactory.decodeFile(imageurl);
bitmap.compress(Bitmap.CompressFormat.JPEG,60,byteArrayOutputStream);
byte[] imgByte=byteArrayOutputStream.toByteArray();
return Base64.encodeToString(imgByte,Base64.DEFAULT);
}
else {
return null;
}
}
How can we pass params from editText to url using request.GET method.
Actually I am trying to pass an email address as parameter to a api which should b attached to api-url .
I came to know from here that getParams() is not called on the GET method, so it seems you'll have to add it to the URL before you send the request.
suggest me any solution to achieve the task ..
when i pass REG_URL="http://ec2-54-147-238-136.compute-1.amazonaws.com/hmc/api/registeruser?email=ameer#novatoresols.com";
it return success=true response as expected because is registered user
but if i set REG_URL="http://ec2-54-147-238-136.compute-1.amazonaws.com/hmc/api/registeruser and pass the params (get value from edittext and use params.put in getparams() method ).response is always success=false i.e params is not attached to url
here is my code.
package com.example.mts3.hammadnewsapp;
import android.app.AlertDialog;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.preference.PreferenceManager;
import android.provider.SyncStateContract;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;
import com.android.volley.AuthFailureError;
import com.android.volley.Request;
import com.android.volley.RequestQueue;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.JsonObjectRequest;
import com.android.volley.toolbox.StringRequest;
import com.android.volley.toolbox.Volley;
import org.json.JSONException;
import org.json.JSONObject;
import java.util.HashMap;
import java.util.Map;
import java.util.Objects;
public class RegisterActivity extends AppCompatActivity {
Button btn_verf;
EditText et_Email;
String u_emails,stat;
AlertDialog.Builder alertDialog;
private static final String TAG = "LoginActivity";
SharedPreferences sharedPreferences;
SharedPreferences.Editor editor;
Context context;
// public static String firstname, lastname, useremail, userphone, userpass;
// String REG_URL="http://ec2-54-147-238-136.compute-1.amazonaws.com/hmc/api/registeruser?email=ameer#novatoresols.com";
String REG_URL="http://ec2-54-147-238-136.compute-1.amazonaws.com/hmc/api/registeruser";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_register);
btn_verf=findViewById(R.id.btn_reg_send_vf_code);
et_Email=findViewById(R.id.et_reg_email);
alertDialog =new AlertDialog.Builder(RegisterActivity.this);
// u_emails=et_Email.getText().toString().trim();
btn_verf.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
callApi();
}
});
}
private void callApi() {
// Log.e(TAG, "onClick: ");
/*if (!utility.isInternetConnected()) {
Toast.makeText(LoginActivity.this, "Please check your internet connection.", Toast.LENGTH_SHORT).show();
return;
}*/
// dialog = utility.showProgressDialog(LoginActivity.this, "Please wait");
final String email = et_Email.getText().toString().trim();
// Log.e(TAG, "onClick: email = " + email );
// JSONObject params = new JSONObject();
/*
HashMap<String,String> params=new HashMap<>();
params.put("email",email);*/
/*try {
// params.getString("email");
params.put("email",email);
Log.e(TAG, "getParams: param = " + "try of put prams");
} catch (JSONException e){
Log.e(TAG, "getParams: param = " + "catch of put prams");
e.printStackTrace();
}*/
RequestQueue queue = Volley.newRequestQueue(RegisterActivity.this);
StringRequest stringRequest = new StringRequest(Request.Method.GET, REG_URL, new Response.Listener<String>() {
#Override
public void onResponse(String response) {
Toast.makeText(RegisterActivity.this, "REsponse: " + response, Toast.LENGTH_SHORT).show();
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
}
}){
#Override
protected Map<String, String> getParams() throws AuthFailureError {
HashMap<String,String> params=new HashMap<>();
// params.put("email",email);
params.put("email",email);
return params;
}
}; queue.add(stringRequest);
}
}
As suggested by #Puneet worked for me which is as :
getParams is only called for POST requests. GET requests don't have a body and hence, getParams is never called. For a simple request like yours just add the parameters to your URL and use that constructed URL to make that request to your server (REG_URL + "?email=" + email).
To pass the parameters, you need to create a class for the key-value pairs.
1) Create a class KeyValuePair with two fields key and value with appropriate constructor and getter-setter methods.
2) Now, for each parameter, you need to create an object of this class, i.e., for a key username with value user#gmail.com, the object would be new KeyValuePair("username", "user#gmail.com").
3) Now, you need to create a List to store these parameters and pass this list to the below method with your base url,
public static String generateUrl(String baseUrl, List<KeyValuePair> params) {
if (params.size() > 0) {
for (KeyValuePair parameter: params) {
if (parameter.getKey().trim().length() > 0)
baseUrl += "&" + parameter.getKey() + "=" + parameter.getValue();
}
}
return baseUrl;
}
4) Pass this baseUrl to your Request.
I'm currently try to implement a two factor authentication system on a project i'm working on using twilio as a sms gateway service to request a random login token and then send it to the user as a text message. I followed the tutorial found here "https://www.twilio.com/blog/2016/05/how-to-send-an-sms-from-android.html" to test the service out. Following the tutorial I hosted the backend on Heroku. The app works just fine and says that the sms has been sent. However I never receive it. Any help would great.
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;
import android.content.Context;
import java.io.IOException;
import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.FormBody;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.RequestBody;
import okhttp3.Response;
public class MainActivity extends AppCompatActivity {
private EditText mTo;
private EditText mBody;
private Button mSend;
private OkHttpClient mClient = new OkHttpClient();
private Context mContext;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mTo = (EditText) findViewById(R.id.txtNumber);
mBody = (EditText) findViewById(R.id.txtMessage);
mSend = (Button) findViewById(R.id.btnSend);
mSend.setOnClickListener(new View.OnClickListener(){
#Override
public void onClick(View v) {
try {
post(" https://cryptic-shore-79857.herokuapp.com", new
Callback(){
#Override
public void onFailure(Call call, IOException e) {
e.printStackTrace();
}
#Override
public void onResponse(Call call, Response response)
throws IOException {
runOnUiThread(new Runnable() {
#Override
public void run() {
mTo.setText("");
mBody.setText("");
Toast.makeText(getApplicationContext(),"SMS Sent!",Toast.LENGTH_SHORT).show();
}
});
}
});
} catch (IOException e) {
e.printStackTrace();
}
}
});
mContext = getApplicationContext();
}
Call post(String url, Callback callback) throws IOException {
RequestBody formBody = new FormBody.Builder()
.add("To", mTo.getText().toString())
.add("Body", mBody.getText().toString())
.build();
Request request = new Request.Builder()
.url(url)
.post(formBody)
.build();
Call response = mClient.newCall(request);
response.enqueue(callback);
return response;
}
}
I'm thinking the URL that connects to Heroku is incorrect but I have no idea what it should be.
Twilio developer evangelist here.
You're POSTing your request to the wrong URL. Currently your code does:
try {
post("https://cryptic-shore-79857.herokuapp.com", new
Callback(){
But the path for the action that sends the SMS should be:
try {
post("https://cryptic-shore-79857.herokuapp.com/sms", new
Callback(){
Note, the /sms path.
Let me know if that helps at all.
I am using OkHttp3 to do a GET API call, which works, however I would like to update a TextView (jsonTextView) in the UiThread with the result of the GET call.
I have tried 10 different ways but it does not work. Always tells me that can't resolve this or that therefore I ask that if you decide to help me, please take into account posting any dependencies on your answer such as import or declaration.
I left a line in my rest class: "CODE TO UPDATE jsonTextView IN UITHREAD". In your opinion what is the best way to achieve this?
Thank you so much in advance, I already lost hours on this.
This is my activity
package it.test.test;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
import android.widget.EditText;
import android.os.*;
import android.util.Log;
public class MainActivity extends AppCompatActivity {
Button fetchUpdateButton;
TextView jsonTextView;
EditText assetCode;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
fetchUpdateButton = (Button) findViewById(R.id.fetchUpdateButton);
fetchUpdateButton.setOnClickListener(fetchAssetUpdateClick);
jsonTextView = (TextView) findViewById(R.id.jsonTextView);
assetCode = (EditText) findViewById(R.id.assetCode);
}
View.OnClickListener fetchAssetUpdateClick = new View.OnClickListener() {
#Override
public void onClick(View v) {
REST r = new REST();
try {
r.getAssetUpdates(assetCode.getText().toString());
} catch (Exception e) {
e.printStackTrace();
jsonTextView.setText("API Fetch Failed");
}
}
};
}
This is my REST class
package it.test.test;
import android.util.Log;
import java.io.IOException;
import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.Headers;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;
import okhttp3.ResponseBody;
/**
* Created by fabio on 25/02/2017.
*/
public class REST {
private final OkHttpClient client = new OkHttpClient();
public void getAssetUpdates(String assetCode) throws Exception {
Request request = new Request.Builder()
.url("http://10.0.0.3:8080/api/api/assets/getAsset?networkAssetCode=" + assetCode)
.build();
client.newCall(request).enqueue(new Callback() {
#Override public void onFailure(Call call, IOException e) {
e.printStackTrace();
}
#Override public void onResponse(Call call, Response response) throws IOException {
try (final ResponseBody responseBody = response.body()) {
if (!response.isSuccessful()) throw new IOException("Unexpected code " + response);
Headers responseHeaders = response.headers();
for (int i = 0, size = responseHeaders.size(); i < size; i++) {
System.out.println(responseHeaders.name(i) + ": " + responseHeaders.value(i));
}
System.out.println(responseBody.string());
CODE TO UPDATE jsonTextView IN UITHREAD
}
}
});
}
}
You can't update the other class UI from the REST class unless you put the callback into the method definition.
public void getAssetUpdates(String assetCode, Callback callback) {
...
client.newCall(request).enqueue(callback);
}
it's simply moving around some variables
Then, in the onClick define your callback so you can access your TextView in that Activity class ,
#Override
public void onClick(View v) {
...
r.getAssetUpdates(assetCode.getText().toString(),
new Callback() {
#Override public void onFailure(Call call, IOException e) {
e.printStackTrace();
}
#Override public void onResponse(Call call, Response response) throws IOException {
try (final ResponseBody responseBody = response.body()) {
if (!response.isSuccessful()) throw new IOException("Unexpected code " + response);
...
// update UI in here
}
}
);
}
And I do think Okhttp requires a usage of runOnUiThread.
OkHTTP Update UI from enqueue callback
Note that if you have JSON and REST, then Retrofit is going to be better than pure Okhttp.
One solution is to give an Activity to REST and call runOnUiThread().
Create own listener & pass the listener object from your activity..
And return the call back from Rest to your Activity
Step 1: Create interface
public interface MyListener
{
void restResult(String result);
}
Step 2:Implement this listener to your activity
YourActivity implements MyListener
Step 3:Pass the listener to Rest class
Rest rest=new Rest(this);//this-- your listener object
Step 4:Modify Rest Constructor
Private MyListener myListener;
Rest(MyListener myListener){
this.myListener=myListener;
}
//After your Rest completed pass the result
CODE TO UPDATE jsonTextView IN UITHREAD
myListener.restResult(responseBody.string());
Step 5: In your Activity get your result
Update the textview using
#override
restResult(String result){
yourtextview.settext(result);
}