I am working on an Android app.
There is a recyclerview that shows user messages, and there is another recyclerview in the adapter from first recyclerview that shows responses from users to the messages.
It is working but not as I want.
The responses shown at each message are not always the responses related to the message.
For example, at message #3, there are shown the responses to message #3, at message #2 there are shown the responses to message #3 and #2, at message #1 there are shown the responses to message #3, #2 and #1.
After refreshing the view, this can be different, the responses shown may be different.
This is the piece of code inside the adapter that manages the responses recyclerview;
//respuestas
holder.recyclerViewPosts.setHasFixedSize(true);
holder.recyclerViewlayoutManager = new LinearLayoutManager(context);
holder.recyclerViewPosts.setLayoutManager(holder.recyclerViewlayoutManager);
subjectsList = new ArrayList<>();
AsyncHttpClient client = new AsyncHttpClient();
RequestParams params = new RequestParams();
params.put("origen", subjects.get(position).id_mensaje_chat);
params.put("rnd", getSaltString());
client.get(HTTP_JSON_URL, params, new TextHttpResponseHandler() {
#Override
public void onSuccess(int statusCode, Header[] headers, String res) {
// called when response HTTP status is "200 OK"
Log.d("RES SUVJETC","respuesta chat "+res);
try {
JSONArray jsonArray = new JSONArray(res);
for(int i = 0; i<jsonArray.length(); i++) {
MensajesRespuestaChat GetDataAdapter2 = new MensajesRespuestaChat();
JSONObject json = null;
try {
json = jsonArray.getJSONObject(i);
GetDataAdapter2.setid_respuesta(json.getString("id_respuesta"));
GetDataAdapter2.setemisor(json.getString("emisor"));
GetDataAdapter2.settexto(json.getString("texto"));
GetDataAdapter2.setfecha(json.getString("fecha"));
GetDataAdapter2.setorigen(json.getString("origen"));
GetDataAdapter2.setnombre(json.getString("nombre"));
GetDataAdapter2.setapellidos(json.getString("apellidos"));
} catch (JSONException e) {
e.printStackTrace();
}
subjectsList.add(GetDataAdapter2);
}
recyclerViewadapter = new RecyclerViewChatRespuestaCardViewAdapter(subjectsList, context);
holder.recyclerViewPosts.setAdapter(recyclerViewadapter);
Integer num_mensajes = subjectsList.size();
if (num_mensajes == 0){
}
if (num_mensajes > 0){
}
} catch (JSONException e) {
e.printStackTrace();
}
}
#Override
public void onFailure(int statusCode, Header[] headers, String res, Throwable t) {
// called when response HTTP status is "4XX" (eg. 401, 403, 404)
}
}
);
Maybe you can find the reason for that issue there.
If you need further pieces of code, I can put them here, no problem.
Related
I am trying to do a get from the API, but it returns a 400, I have tried putting my local IP and putting 10.0.2.2, but he has continued to do the same, in the Event Log shows me this too: Emulator: CANNOT TRANSLATE guest DNS ip.From the PostMan I get the JSON back correctly so I do not think the problem is in the API
This is where I do everything
public void PendingTrajects(){
AsyncHttpClient client = new AsyncHttpClient();
String URL = "http://ip:port/api/trajectes";
client.get(this, URL, new AsyncHttpResponseHandler() {
#Override
public void onStart() {
Toast.makeText(PendingTrajectRecyclerView.this, "Carregant...", Toast.LENGTH_SHORT).show();
}
#Override
public void onSuccess(int statusCode, Header[] headers, byte[] responseBody) {
JSONArray Usuaris = new JSONArray();
JSONArray trajectes = new JSONArray();
String Nom = null;
String strResponseBody = new String(responseBody);
try {
//Usuari = new JSONArray(strResponseBody);
trajectes = new JSONArray(strResponseBody);
}catch (JSONException e){
Toast.makeText(PendingTrajectRecyclerView.this, "Error a la connexió", Toast.LENGTH_SHORT).show();
}
try {
for(int i = 0; i < trajectes.length(); i++){
JSONObject trajecte = trajectes.getJSONObject(i);
JSONArray realitzas = trajecte.getJSONArray("realitzas");
for(int j = 0; j < realitzas.length(); j++){
JSONObject realitza = realitzas.getJSONObject(j);
JSONObject usuari = realitza.getJSONObject("usuari");
Log.d("xd", ""+usuari.getString("name"));
}
}
}catch (JSONException e){
Toast.makeText(PendingTrajectRecyclerView.this, "Error a la connexió", Toast.LENGTH_SHORT).show();
}
}
#Override
public void onFailure(int statusCode, cz.msebera.android.httpclient.Header[] headers, byte[] responseBody, Throwable error) {
Toast.makeText(PendingTrajectRecyclerView.this, "Error a la connexió ONFailure", Toast.LENGTH_SHORT).show();
Log.d("Error",""+statusCode);
}
});
400 BAD REQUEST
The server cannot or will not process the request due to something
that is perceived to be a client error (e.g., malformed request
syntax, invalid request message framing, or deceptive request
routing).
You should DEBUG your Application. Check your parameters.
Add a Break-point here
String URL = "http://ip:port/api/trajectes";
Actually server could not understand the request due to invalid syntax.
I use Loop j for fetching data from server in my app. But it always fetch the old response . I test my api on postman and gets the latest response from server.
If any one know how to clear the loop j old response from cache?
Here is my code
AsyncHttpClient client = new AsyncHttpClient();
client.get("http://bnailsusa.com/app_api/getView.php?serviceprovider", new JsonHttpResponseHandler() {
#Override
public void onSuccess(int statusCode, cz.msebera.android.httpclient.Header[] headers, JSONArray response) {
Log.d("Tag:", String.valueOf(response));
try {
for (int i=0;i<=response.length();i++){
//region Fetching
JSONObject index=response.getJSONObject(i);
String name=index.getString("Name");
String spid=index.getString("spid");
String Photo=index.getString("PHOTO");
//endregion
//region Storing
names.add(name);
SPID.add(spid);
images.add(Photo);
Log.d("Tag:ar", String.valueOf(names));
//endregion
}
} catch (JSONException e) {
e.printStackTrace();
}
ProvidersAdapter booksAdapter = new ProvidersAdapter(SelectServiceProvider.this, names,images);
gridView.setAdapter(booksAdapter);
}
public void onFailure(int statusCode, cz.msebera.android.httpclient.entity.mime.Header[] headers, Throwable throwable, JSONObject errorResponse){
}
});
I'm developing a new Android app which allow the user to rate the content. The rate is sent thanks to an asynchronous request (POST) over HTTPS. Unfortunately, the request don't reach my webservice. When I took a look at the log access log, the URL is truncated. You can find below the relevant code.
private static AsyncHttpClient getClient()
{
if(client == null)
{
client = new AsyncHttpClient(true, 80, 443);
client.getHttpClient().getParams().setParameter(ClientPNames.ALLOW_CIRCULAR_REDIRECTS, true);
client.getHttpClient().getParams().setParameter(CoreProtocolPNames.PROTOCOL_VERSION, HttpVersion.HTTP_1_1);
}
return client;
}
public static void createComment(int idArticle, String content, final Context context, final Callback callback)
{
final User currentUser = RealmManager.getUser();
RequestParams paramsPost = new RequestParams();
paramsPost.put("id_article", idArticle);
paramsPost.put("id_utilisateur", currentUser.getId());
paramsPost.put("content", content);
HashMap<String, String> paramsGet = getDefaultParams(context, currentUser, "webservices.createCommentaire");
getClient().post(createGetURL(currentUser.getURL(), paramsGet), paramsPost, new AsyncHttpResponseHandler()
{
#Override
public void onSuccess(int statusCode, Header[] headers, byte[] response)
{
callback.onSuccess(/*..*/);
}
#Override
public void onFailure(int statusCode, Header[] headers, byte[] errorResponse, Throwable e)
{
callback.onFailure(/*..*/);
}
});
}
When I put a breakpoint and examine the request, it looks like :
https://api.webservices.com/index.php?option=webservices&app_version=2.0&task=createCommentaire&token=XXXXXXXXXXXX&version=v2&format=raw
But, in the access log, the URL is truncated after "?" :
POST - https://api.webservices.com/index.php?
Consequently, I got in the response the HTML of the index.php which I can't parse in JSON.
Thank you in advance for your help.
I have two suggestion for you.
Use from UrlEncoder.encode("") method for every part of your parameters
Do not use query string parameters for post data to server.
I am trying to get response from my node.js server with MySQL database.
When I connect to server with my browser I get result like this:
[{"person_id":0,"age":18},{"person_id":1,"age":17},{"person_id":2,"age":30}]
What I want to do is to get the same result with my Android app after pressing the button.
I wanted to use LoopJ AndroidAsyncHttp:
AsyncHttpClient client = new AsyncHttpClient();
client.get("http://localhost:3000", new JsonHttpResponseHandler() {
#Override
public void onSuccess(int statusCode, Header[] headers, JSONArray response) {
super.onSuccess(statusCode, headers, response);
}
});
I know that I connected to server properly because I got log in server's console.
What is the easiest way to retrieve that data?
Create a model Person contain "person_id" and "age"
AsyncHttpClient client = new AsyncHttpClient();
client.get("http://localhost:3000",new AsyncHttpResponseHandler() {
#Override
public void onSuccess(int statusCode, Header[] headers, byte[] responseBody) {
try {
String response = responseBody == null ? null : new String(
responseBody, getCharset());
Log.d("Response: ", response);
Gson gson = new Gson();
Person[] arr = gson.fromJson(response, Person[].class);
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
}
I'm using the Android Asynchronous Http Client. My code looks like this and is working fine.
DataUtil.post("RegisterUser", params, new AsyncHttpResponseHandler() {
#Override
public void onSuccess(String answer) {
// initialize variables
JSONObject json = new JSONObject();
String message = null;
try {
// turn string into JSONObject
json = new JSONObject(answer);
message = json.getString("message");
} catch (JSONException e) {
Log.e("ERROR", e.getMessage());
}
// registration was successful
if (message.equals("success")) {
// forward to login page
} else {
// error
}
}
});
I implemented a static HTTP Client. My server returns this JSON data {"message":"success"}. I do not want to treat it as a String and cast it back to JSON. But when I change it to public void onSuccess(JSONObject answer) eclipse tells me
The method onSuccess(JSONObject) of type new
AsyncHttpResponseHandler(){} must override or implement a supertype
method
The correct method signature would be this public void onSuccess(int statusCode, Header[] headers, JSONObject response) or any of the other available methods in the JsonHttpResponseHandler class