JsonHttpResponseHandler - method does not override method from its superclass - java

I have been struggling with this code for some time now. Why am I getting the follow error?
method does not override method from its superclass
Here is the code:
public void CanSendPassword() {
asyncHttpClientPassword = new AsyncHttpClient();
requestParamsPassword = new RequestParams();
requestParamsPassword.put("email", mEmail);
asyncHttpClientPassword.post(BASE_URL, requestParamsPassword, new JsonHttpResponseHandler()
{
#Override
public void onSuccess(int statusCode, Header[] headers, JSONObject response) {
super.onSuccess(statusCode, headers, response);
jsonResponse = response.toString();
}
#Override
public void onFailure(int statusCode, Header[] headers, Throwable throwable, JSONObject errorResponse) {
super.onFailure(statusCode, headers, throwable, errorResponse);
jsonResponse = "failed";
}
}
);
}
#override both are showing the same error and onSuccess and onFailure are greyed out too?

Here is my code
TwitterRestClient
import android.content.Context;
import com.loopj.android.http.*;
import cz.msebera.android.httpclient.entity.StringEntity;
public class TwitterRestClient {
private static final String BASE_URL = "https://www.example.com/api/";
private static AsyncHttpClient client = new AsyncHttpClient();
public static void get(String url, RequestParams params, AsyncHttpResponseHandler responseHandler) {
client.get(getAbsoluteUrl(url), params, responseHandler);
}
public static void post(String url, RequestParams params, AsyncHttpResponseHandler responseHandler) {
client.post(getAbsoluteUrl(url), params, responseHandler);
}
public static void post(Context ctx, String url, StringEntity entity, java.lang.String contentType, AsyncHttpResponseHandler responseHandler ){
client.post(ctx,getAbsoluteUrl(url),entity,contentType,responseHandler);
}
private static String getAbsoluteUrl(String relativeUrl) {
return BASE_URL + relativeUrl;
}
}
This the method in my LoginAcitivity
public void testPost(StringEntity entity) throws JSONException {
TwitterRestClient.post(getApplicationContext(),"api-auth/", entity,"application/json", new JsonHttpResponseHandler() {
#Override
public void onSuccess(int statusCode, cz.msebera.android.httpclient.Header[] headers, org.json.JSONArray response) {
// If the response is JSONObject instead of expected JSONArray
GlobalFunctions.ShowToast(getApplicationContext(),"test");
}
#Override
public void onFailure(int statusCode, cz.msebera.android.httpclient.Header[] headers, java.lang.Throwable throwable, org.json.JSONArray errorResponse){
GlobalFunctions.ShowToast(getApplicationContext(),"test1123");
}
#Override
public void onFailure(int statusCode, cz.msebera.android.httpclient.Header[] headers, java.lang.Throwable throwable, org.json.JSONObject errorResponse){
GlobalFunctions.ShowToast(getApplicationContext(),errorResponse.toString());
}
#Override
public void onFailure(int statusCode, cz.msebera.android.httpclient.Header[] headers, java.lang.String responseString, java.lang.Throwable throwable){
GlobalFunctions.ShowToast(getApplicationContext(),responseString);
}
});
}
This is what i call when user clicks the button
public void signIn(View v){
try {
String url = "/api-auth";
JSONObject jsonParams = new JSONObject();
jsonParams.put("username", "binsoi#gmail.com");
jsonParams.put("password", "cornedbeef");
StringEntity entity = new StringEntity(jsonParams.toString());
client.post(context, url, entity, "application/json",
responseHandler);
testPost(entity);
} catch (Exception err)
{
GlobalFunctions.ShowToast(this, err.toString());
}
}
Hope this will help you, tell me if it this doesn't work because i edited this before posting.

Here is a solution that I have working but it does not solve my exact issue. I post this as I can not understand why this code works but my code does not.
public class MainActivity extends AppCompatActivity implements View.OnClickListener {
EditText etSearchTerms;
Button btnSearch;
TextView tvSearchResults;
MyLoopjTask myLoopjTask;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
etSearchTerms = (EditText) findViewById(R.id.etSearchTerms);
btnSearch = (Button) findViewById(R.id.btnSearch);
tvSearchResults = (TextView) findViewById(R.id.tvSearchResults);
btnSearch.setOnClickListener(this);
myLoopjTask = new MyLoopjTask();
}
#Override
public void onClick(View v) {
String searchTerm = etSearchTerms.getText().toString();
etSearchTerms.setText("");
// make loopj http call
myLoopjTask.executeLoopjCall(searchTerm);
}
}
And here is the other class:
public class MyLoopjTask {
AsyncHttpClient asyncHttpClient;
RequestParams requestParams;
String BASE_URL = "https://team.mycompany.com/teambeta/LoginApp/Recovery/";
String jsonResponse;
public MyLoopjTask() {
asyncHttpClient = new AsyncHttpClient();
requestParams = new RequestParams();
}
public void executeLoopjCall(final String queryTerm) {
requestParams.put("email", queryTerm);
asyncHttpClient.post(BASE_URL, requestParams, new JsonHttpResponseHandler() {
#Override
public void onSuccess(int statusCode, Header[] headers, JSONObject response) {
super.onSuccess(statusCode, headers, response);
jsonResponse = response.toString();
}
#Override
public void onFailure(int statusCode, Header[] headers, Throwable throwable, JSONObject errorResponse) {
super.onFailure(statusCode, headers, throwable, errorResponse);
jsonResponse = "failed";
}
});
}
}
So why does this code work but not in my oringinal question?

Finally solved my issue. It was not the code as I was doing everything correctly. I just had the old jar file still in the app/libs folder.
And here is the error I was seeing. Everything was working but Override and the super.onSuccess were red underlined.
Remove the android-async-1.4.3.jar file and the red lines disappeared.

Related

problem with android : data from class don't send to activity

i wrote the code to an activity it work perfect but when i writhing them to a java class and send the result to the activity is not show anything to text view.
public class TheaudiodbWebData {
private String result = "";
public String getResult() {
return result;
}
public TheaudiodbWebData() {
getBiographyData();
}
private void getBiographyData() {
String url = "https://www.theaudiodb.com/api/v1/json/1/search.php?s=coldplay";
AsyncHttpClient client = new AsyncHttpClient();
client.get(url, new TextHttpResponseHandler() {
#Override
public void onFailure(int statusCode, Header[] headers, String responseString, Throwable throwable) {
}
#Override
public void onSuccess(int statusCode, Header[] headers, String responseString) {
parseBiographyData(responseString);
}
});
}
private void parseBiographyData(String response) {
try {
Gson gson = new Gson();
TheaudiodbArtistBio bio = gson.fromJson(response, TheaudiodbArtistBio.class);
result = bio.getArtists().get(0).getStrArtist();
} catch (Exception e) {
}
}
}
and this is the Activity code :
public class BiographyActivity extends AppCompatActivity {
TextView test;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_biography);
test=findViewById(R.id.test);
TheaudiodbWebData bio=new TheaudiodbWebData();
test.setText(bio.getResult());
}
}
If you are not passing data from one Activity to another Activity and you are getting the result than problem is clear. Part of code which you are executing in onCreate() method:
TheaudiodbWebData bio=new TheaudiodbWebData();
test.setText(bio.getResult());
is executed immediately but you are getting results over the Internet which means that data is not received immediately (connecting server -> getting result -> returning result = takes some time) that is why you have callback methods onFailure and onSuccess which are triggered after result is returned from the Internet depending was it successful or fail.
So solution is to create your own interface with method where you can pass the result than implement that interface and create your own callback methods.
Or more simpler solution move this part of code directly into your Activity and set the the result to the TextView in onSucces method for example:
private void getBiographyData() {
String url = "https://www.theaudiodb.com/api/v1/json/1/search.php?s=coldplay";
AsyncHttpClient client = new AsyncHttpClient();
client.get(url, new TextHttpResponseHandler() {
#Override
public void onFailure(int statusCode, Header[] headers, String responseString, Throwable throwable) {
}
#Override
public void onSuccess(int statusCode, Header[] headers, String responseString) {
test.setText(responseString);
}
});
}
After that simply call this method inside onCreate() like:
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_biography);
test=findViewById(R.id.test);
getBiographyData();
}

Volley returns null on first call from method

I am trying to retrieve data from server using volley, but when I call this method the first time, I get the response from server, but null is returned by the method. If I call it the second time I get the last response.
public String retrieveDataFromServer(String url, String param, final String token){
StringRequest stringRequest = new StringRequest(Request.Method.GET, url,
new Response.Listener<String>() {
#Override
public void onResponse(String response) {
try{
data = new JSONObject(response).toString();
}catch (Exception e){}
//Toast.makeText(getApplicationContext(), "wow" + data, Toast.LENGTH_SHORT).show();
}
},
new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
try{
data = new JSONObject(error.toString()).toString();
}catch (Exception e){}
//Toast.makeText(getApplicationContext(), "" +data, Toast.LENGTH_SHORT).show();
}
}) {
/**
* Passing some request headers
*/
#Override
public Map<String, String> getHeaders() throws AuthFailureError {
String bearer = "Bearer ".concat(token);
Map<String, String> headersSys = super.getHeaders();
HashMap<String, String> headers = new HashMap<String, String>();
headers.put("Content-Type", "application/json; charset=utf-8");
//headers.put("token", token);
headersSys.remove("Authorization");
headers.put("Authorization", bearer);
headers.putAll(headersSys);
return headers;
}
};
// Adding request to request queue
addToRequestQueue(stringRequest);
//Toast.makeText(getApplicationContext(), "wow" + data, Toast.LENGTH_SHORT).show();
return data;
}
How do I get the response on first call of method?
You can use call back to return Volley response:
public void retrieveDataFromServer(final VolleyCallback callback) {
StringRequest strReq = new StringRequest(Request.Method.GET, url, new Response.Listener<String>() {
#Override
public void onResponse(String response) {
callback.onSuccess(response);
}
}
}}
Create interface:
public interface VolleyCallback{
void onSuccess(String response);
}
And get result from activity:
String yourString = "";
#override
public void onResume() {
super.onResume();
retrieveDataFromServer(new VolleyCallback(){
#Override
public void onSuccess(String response){
//Get result from here
yourString = response;
}
});
}

Android Volley can't get value in separate class

public class VolleyStringRequest {
String url;
String body;
String value;
public VolleyStringRequest(String url, String body){
this.url = url;
this.body = body;
value= "";
}
public StringRequest createStringRequest(){
StringRequest stringRequest = new StringRequest(Request.Method.POST, url,
new Response.Listener<String>() {
#Override
public void onResponse(String response) {
// Do something with the response
Log.e("Response", response);
try{
JSONObject o = new JSONObject(response);
JSONArray values=o.getJSONArray("response");
value += values.toString();
} catch (JSONException ex){}
}
},
new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
// Handle error
}
}) {
#Override
public byte[] getBody() throws AuthFailureError {
return body.getBytes();
};
#Override
public String getBodyContentType() {
return "application/json";
}
};
return stringRequest;
}
public String getValue() {
return value;
}
}
I wrote this code in a seperate class to prevent code repetition but when I run this inside a fragment like this:
RequestQueue rq = Volley.newRequestQueue(getActivity().getApplicationContext());
String url= "http://grwn.ddns.net:1337/results";
final String body = "{\"id\":1}";
VolleyStringRequest volleyStringRequest = new VolleyStringRequest(url, body);
rq.add(volleyStringRequest.createStringRequest());
volleyStringRequest.getValue();
And call the getValue() method. This method is always empty like: "". Does anyone know how I can enhance my class so this code will work? This issue is not because of a bad link or bad request. I can log the response and that does work (ofcourse inside VolleyStringRequest)
You run:
VolleyStringRequest volleyStringRequest = new VolleyStringRequest(url, body);
rq.add(volleyStringRequest.createStringRequest());
volleyStringRequest.getValue();
But remember createStringRequest is async method and value is populated after some delay a.e. inside public void onResponse(String response)
So when you call volleyStringRequest.getValue(); you get empty string
To make it work you can write some interface as:
public interface RequestHandlerInterface(){
void onResponse(String resp);
}
And pass it to VolleyStringRequest constructor:
RequestHandlerInterface rh = this; //Your main class should implement this method
RequestQueue rq = Volley.newRequestQueue(getActivity().getApplicationContext());
String url= "http://grwn.ddns.net:1337/results";
final String body = "{\"id\":1}";
VolleyStringRequest volleyStringRequest = new VolleyStringRequest(url, body, rh);
rq.add(volleyStringRequest.createStringRequest());
Next, change your VolleyStringRequest:
public class VolleyStringRequest {
String url;
String body;
String value;
public VolleyStringRequest(String url, String body, RequestHandlerInterface rh){
this.url = url;
this.body = body;
this.rh = rh;
value= "";
}
//...
}
And once you got response from POST, call the callback as:
#Override
public void onResponse(String response) {
// Do something with the response
Log.e("Response", response);
try{
JSONObject o = new JSONObject(response);
JSONArray values=o.getJSONArray("response");
value += values.toString();
if(this.rh != null){
this.rh.onResponse(value);
}
} catch (JSONException ex){}
}
So in bottom line instead to call volleyStringRequest.getValue();
you have:
#Override
void onResponse(String resp){
// here you go
}
that will be called when you get POST response

Custom class extending AsyncHttpResponseHandler and return modified bytes

I have searched with google for the past 3 hours to no avail, I am not sure if this is even possible.
I am using AsyncHttpResponseHandler in 10-12 different activities, and with all of them I am doing the same initial transforming of the "byte[] bytes" in the initial code, which is around 50lines of code per activity.
How would I do said transformation of bytes, and then return the final value on the activity where the custom class gets called?
How would I reference the message variable?
public class MainActivity extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
AsyncHttpClient client = new AsyncHttpClient();
client.post(URL, params, new VenueAsyncHttpResponseHandler() {
#Override
public void onSuccess(int i, Header[] headers, byte[] bytes) {
//How do I reference the transformed message here?
switch (message) {
case "success":
//Do something
break;
}
}
});
}
}
when using the custom class
public class VenueAsyncHttpResponseHandler extends AsyncHttpResponseHandler {
#Override
public void onSuccess(int i, Header[] headers, byte[] bytes) {
String byteToString = null;
JSONObject response = null;
String message = "";
try {
byteToString = new String(bytes, "UTF-8");
response = new JSONObject(byteToString);
message = response.getString("response"); //return this to the activity
} catch (UnsupportedEncodingException | JSONException e) {
e.printStackTrace();
}
}
#Override
public void onFailure(int i, Header[] headers, byte[] bytes, Throwable throwable) {
}
}
Add a method to your activity class which does what you want with the message. Then call this method from onSuccess().
Also, do not create an anonymous inner class. Instead instantiate your custom class directly:
VenueAsyncHttpResponseHandler handler = new VenueAsyncHttpResponseHandler();
client.post(URL, params, handler);

Java Android AsyncHttpClient convert byte[]responseBody to InputStream

I want to create a methos which return a InputStream I did this :
public static InputStream sendGetDataRequest(Context context,
String version, String power, String lon, String lat, String radius) throws MalformedURLException, ConnectTimeoutException, IOException
{
AsyncHttpClient client = new AsyncHttpClient();
String url = Util.getServerUrl(context) + "/GetData";
// ContentValues values=new ContentValues();
RequestParams values = new RequestParams();
values.put("token", String.valueOf(E_Gps.TOKEN));
values.put("xml", login_xml);
StringEntity entity = null;
try {
entity = new StringEntity(values.toString());
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
entity.setContentType(new BasicHeader("Content-Type","application/xml"));
final InputStream[] is = new InputStream[1];
final InputStream inputStream;
client.post(context,url,values , new AsyncHttpResponseHandler(Looper.getMainLooper()) {
#Override
public void onSuccess(int statusCode, Header[] headers, byte[] responseBody) {
Log.e("success_noti", new String(responseBody) + "");
is[0] = new ByteArrayInputStream(responseBody);
Log.e("Status " , statusCode + " ");
Log.e("is" , convertStreamToString(is[0]));
}
#Override
public void onFailure(int statusCode, Header[] headers, byte[] responseBody, Throwable error) {
Log.e("success_noti", new String(responseBody) + "");
Log.e("Status " , statusCode + " ");
}
});
return is[0];
}
And I have probleme when I return is[0] is a null but when I log in onSuccess :
Log.e("is" , convertStreamToString(is[0]));
is not null why I have null object is[0] ?
Because client.post is an asynchronous call while return is[0] is a synchronous. This means that is[0] is null as long as the async call is not done yet. One way to solve is by making sendGetDataRequest return void and instead accepts a callback e.g.
public static void sendGetDataRequest(final YourCallback callback, ...)
Create a new Interface named YourCallback
public interface YourCallback{
void onSuccess(String string);
void failure();
}
And use that Callback inside the async method
client.post(context,url,values , new AsyncHttpResponseHandler(Looper.getMainLooper()) {
#Override
public void onSuccess(int statusCode, Header[] headers, byte[] responseBody) {
callback.onSuccess(convertStreamToString(is[0]));
}
#Override
public void onFailure(int statusCode, Header[] headers, byte[] responseBody, Throwable error) {
callback.onFailure();
}
}
Finally you call your static method like this
sendGetDataRequest(new YourCallback(){/* Override the methods */}, ...);
By the way you could also use AsyncTask from the android package which does everything above. It's personal preference.

Categories

Resources