How to consume a web service that returns a nameless jsonArray

2

I am working with android, I want to consume a web service that returns a jsonObject from laravel but the jsonobject has no name as I can receive it with the volley library and print it in a list. The route and the json is:

 http://localhost/SecurityPets4/public/api/consultar/blogs/veterinario/1

json:

[{"id":1,"titulo":"PruebaWebService","resumen":"ProbandoEnLaravel","descripcion":"PrimeraPrueba","veterinario_id":1,"remember_token":null,"created_at":"2018-04-17 15:47:21","updated_at":"2018-04-17 15:47:21"},{"id":2,"titulo":"PruebaNavegador","resumen":"DesdeFirefox","descripcion":"prueba2","veterinario_id":1,"remember_token":null,"created_at":"2018-04-17 16:15:28","updated_at":"2018-04-17 16:15:28"},
{"id":3,"titulo":"PruebaNavegador","resumen":"DesdeFirefox","descripcion":"prueba2","veterinario_id":1,"remember_token":null,"created_at":"2018-04-17 16:29:05","updated_at":"2018-04-17 16:29:05"},
{"id":4,"titulo":"sfsdf","resumen":"fsfsdfs","descripcion":"fsfsfds","veterinario_id":1,"remember_token":null,"created_at":"2018-04-17 17:25:31","updated_at":"2018-04-17 17:25:31"}]

on android I receive it this way:

 @Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
    // Inflate the layout for this fragment
    View view = inflater.inflate(R.layout.fragment_lista_blog, container, false);

    listaBlog= new ArrayList<>();
    recyclerView = view.findViewById(R.id.listBlogRecyvler);

    recyclerView.setLayoutManager(new LinearLayoutManager(this.getContext()));
    recyclerView.setHasFixedSize(true);

    request= Volley.newRequestQueue(getContext());

    progress= new ProgressDialog(getContext());
    progress.setTitle("Consultas");
    progress.setMessage("Cargando consultas espere por favor...");
    progress.show();
    obtenerLitaBlog("http://192.168.0.9/SecurityPets4/public/api/consultar/blogs/veterinario/1");

    return view;

}

private void obtenerLitaBlog(String URL) {

    Log.i("url", "" + URL);
    StringRequest request1 = new StringRequest(Request.Method.GET, URL, new Response.Listener<String>() {
        @Override
        public void onResponse(String response) {
            JSONArray jsonArray = null;
            try {
                progress.hide();
                    jsonArray = new JSONArray(response);

                    for (int i = 0; i < jsonArray.length(); i++) {

                        JSONObject cosnulstasDBWEB = jsonArray.getJSONObject(i);

                        Blogs oclientes = new Blogs();
                        oclientes.setID(cosnulstasDBWEB.getInt("id"));
                        oclientes.setNombre(cosnulstasDBWEB.getString("titulo"));
                        oclientes.setDescripcionCorta(cosnulstasDBWEB.getString("resumen"));


                        makeText(getContext(), "Existen Blogs", LENGTH_SHORT).show();

                        listaBlog.add(oclientes);

                        BlogsAdapter adapter = new BlogsAdapter(listaBlog);
                        recyclerView.setAdapter(adapter);
                }



            } catch (JSONException e) {
                e.printStackTrace();
            }
        }
    }, new Response.ErrorListener() {
        @Override
        public void onErrorResponse(VolleyError error) {
            error.printStackTrace();
            progress.hide();
            makeText(getContext(), "Error al cargar consultas ", LENGTH_SHORT).show();
        }
    });

    request.add(request1);
}

private void obtenerLosObjetos(String URL) {
    Log.i("url", "" + URL);
    JsonObjectRequest jsonObjectRequest = new JsonObjectRequest(Request.Method.GET, URL, null, new Response.Listener<JSONObject>() {
        @Override
        public void onResponse(JSONObject response) {
            try {
                progress.hide();
                JSONObject jsonArray = new JSONObject();

                for (Iterator<String> iterator = jsonArray.keys(); iterator.hasNext(); ) {
                    String key = iterator.next();

                    JSONObject cosnulstasDBWEB = jsonArray.getJSONObject(key);
                    Blogs oclientes = new Blogs();
                    oclientes.setID(cosnulstasDBWEB.getInt("id"));
                    oclientes.setNombre(cosnulstasDBWEB.getString("titulo"));
                    oclientes.setDescripcionCorta(cosnulstasDBWEB.getString("resumen"));


                    makeText(getContext(), "Existen Blogs", LENGTH_SHORT).show();

                    listaBlog.add(oclientes);

                    BlogsAdapter adapter = new BlogsAdapter(listaBlog);
                    recyclerView.setAdapter(adapter);

                }

            } catch (JSONException i) {
                i.printStackTrace();
            }
        }
    }, new Response.ErrorListener() {
        @Override
        public void onErrorResponse(VolleyError error) {

        }
    });

}
    
asked by Juan Antonio 02.05.2018 в 03:19
source

2 answers

0

Everything related to Volley must be of the type of the Web service response, that is, if the web service returns a JsonArray , your request sent by Volley should indicate at all times that you wait a JsonArray . And in the request you should indicate that it is of type JsonArrayRequest . In the Listener , you must also indicate a type JsonArray ....

Currently you indicate that it is a request and a response of type String , which does not correspond to the actual response of the web service.

Try this:

private void obtenerLitaBlog(String URL) {

    Log.i("url", "" + URL);
    JsonArrayRequest request1 = 
    new JsonArrayRequest(
                          Request.Method.GET, URL, new Response.Listener<JsonArray>() {
        @Override
        public void onResponse(JsonArray response) {
            try {
                progress.hide();

                    for (int i = 0; i < response.length(); i++) {

                        JSONObject cosnulstasDBWEB = response.getJSONObject(i);

                        Blogs oclientes = new Blogs();
                        oclientes.setID(cosnulstasDBWEB.getInt("id"));
                        oclientes.setNombre(cosnulstasDBWEB.getString("titulo"));
                        oclientes.setDescripcionCorta(cosnulstasDBWEB.getString("resumen"));


                        makeText(getContext(), "Existen Blogs", LENGTH_SHORT).show();

                        listaBlog.add(oclientes);

                        BlogsAdapter adapter = new BlogsAdapter(listaBlog);
                        recyclerView.setAdapter(adapter);
                }



            } catch (JSONException e) {
                e.printStackTrace();
            }
        }
    }, new Response.ErrorListener() {
        @Override
        public void onErrorResponse(VolleyError error) {
            error.printStackTrace();
            progress.hide();
            makeText(getContext(), "Error al cargar consultas ", LENGTH_SHORT).show();
        }
    });

    request.add(request1);
}

Note: If your obtenerLosObjetos method also expects a JsonArray it should be modified in the same way.

    
answered by 02.05.2018 в 03:57
-1

Do it with volley information download as follows:

private class Obtener extends AsyncTask<Void, Void, Void> {
        public void onPreExecute() {
                Toast.makeText(this,"obteniendo informacion...",Toast.LENGTH_SHORT).show();
        }
        public void onPostExecute(Void unused) {
        }

        @Override
        protected Void doInBackground(Void... params) {
            StringRequest request = new StringRequest(Request.Method.POST, URL, new Response.Listener<String>() {
                @Override
                public void onResponse(String response) {
                    if (!response.equals("null")){
                        try {
                        JSONArray jsonArray = new JSONArray(response);
                        for (int i = 0; i < jsonArray.length(); i++) {
                                   String x=  jsonArray.getJSONObject(i).getInt("id");
                                   String y=  jsonArray.getJSONObject(i).getString("titulo");
                                   String z=  jsonArray.getJSONObject(i).getString("resumen");
                                   String h = jsonArray.getJSONObject(i).getString("descripcion");
                                   //Aqui cambialo a donde lo vallas a enviar ...

                        } catch (JSONException e) {
                            e.printStackTrace();
                        }
                    }else{
                        Verificador.setText("Se ha presentado un problema");
                    }
                }
            }, new Response.ErrorListener() {
                @Override
                public void onErrorResponse(VolleyError error) {
                    Toast.makeText(this,"Verifique que este conectado a internet",Toast.LENGTH_SHORT).show();
                }
            });
            requestQueue.add(request);
            return null;
        }
    }

and to execute it simply do it like this:

Activitynombre.Obtener obtener = new Obtener();
obtener.execute();
    
answered by 02.05.2018 в 05:08