Get Array List by AsyncTask from a URL

0

I am trying to extract a list array by asynctask of a url but I can not complete the action.

This is the error:

  

Error: (35, 22) error: incompatible types   required: ArrayList   found: ArrayList

     

Error: (34, 25) error: incompatible types   required: Activity   found: Context

Run:

  new List_URL().execute();



    ListView lvDiversos = (ListView) findViewById(R.id.lista_notificaciones);


    public class List_URL extends AsyncTask<ArrayList, ProgressBar, ArrayList<HttpHandler2>> {


        ArrayList<HttpHandler2> diversosAvaiable = new ArrayList<HttpHandler2>();

        protected void onPreExecute(){
            super.onPreExecute();
            // progressDialog
        }

        @Override
        protected ArrayList doInBackground(ArrayList... arg0){
            try {
            // Making HTTP Request
            try {

                final String id_pedido = getIntent().getStringExtra("id_pedido");

                // Crear un cliente por defecto
                HttpClient mClient = new DefaultHttpClient();
                StringBuilder sb=new StringBuilder("http://www.miweb.com/web_service/chat_api.php?id_pedido="+id_pedido);
                HttpPost mpost = new HttpPost(sb.toString());
                List nameValuepairs = new ArrayList();
                nameValuepairs.add(new BasicNameValuePair("id_pedido","51"));
                mpost.setEntity(new UrlEncodedFormEntity(nameValuepairs));
                HttpResponse responce = mClient.execute(mpost);
                HttpEntity entity = responce.getEntity();
                StringBuilder sb1 = new StringBuilder();



                String aux = "";
                BufferedHttpEntity buffer = new BufferedHttpEntity(entity);
                InputStream iStream = buffer.getContent();
                BufferedReader buf = new BufferedReader(new InputStreamReader(iStream));
                StringBuilder total = new StringBuilder();
                String line;
                while ((line = buf.readLine()) != null) {
                    aux += line;
                }
                // Parseamos la respuesta obtenida del servidor a un objeto JSON
                JSONObject jsonObject = new JSONObject(aux);
                JSONArray results = jsonObject.getJSONArray("results");


                Log.w(" RESULTADOS JSON ", String.valueOf(results));

                while ((line = buf.readLine()) != null) {
                    sb1.append(line+"\r\n");
                }

                for(int i = 0; i < results.length(); i++) {
                    JSONObject city = results.getJSONObject(i);

                    // Creamos el objeto City
                    HttpHandler2 c = new HttpHandler2(
                            city.getInt("id"),
                            city.getString("id_pedido"),
                            city.getString("user"),
                            city.getString("gcmpartner"),
                            city.getString("id_partner"),
                            city.getString("msg"),
                            city.getString("date"));
                    //c.setData(city.getString("imagen_comp"));
                    //c.setData2(city.getString("imagen_g"));

                    // Almacenamos el objeto en el array que hemos creado anteriormente
                    diversosAvaiable.add(c);



                }

            } catch (Exception e) {
                //Si se produce un error, lo mostramos
                Log.w(" error ", e.toString());
            }



            }catch (Exception e) {

            }

            return diversosAvaiable;



        }

        @Override
        protected void onPostExecute(ArrayList<HttpHandler2> diversosAvaiable) {
            SECUNDARIA cityAdapter = new SECUNDARIA(this, diversosAvaiable);
            lvDiversos.setAdapter(cityAdapter);



        }
    }

My HttpHandler2:

public class HttpHandler2 {
  protected int id;
  protected String id_pedido;
  protected String msg;
  protected String user;
  protected String gcmpartner;
  protected String id_partner;
  protected String date;


  public HttpHandler2(int id, String id_pedido, String user, String gcmpartner, String id_partner, String msg, String date) {
    this.id = id;
    this.id_pedido = id_pedido;
    this.msg = msg;
    this.user = user;
    this.gcmpartner = gcmpartner;
    this.id_partner = id_partner;
    this.date = date;
  }


  /////////////////////id////////////////////

  public int getId() {return id;}

  public void setId(int id) { this.id = id;}







  //////////////////////////////ID_PEDIDO/////////////////////////
  public String getid_pedido() {
    return id_pedido;
  }

  public void setid_pedido(String id_pedido) {
    this.id_pedido = id_pedido;
  }







  //////////////////////////////MSG/////////////////////////
  public String getmsg() {return msg;}

  public void setmsg(String msg) {
    this.msg = msg;
  }







  //////////////////////////////USER/////////////////////////
  public String getuser() {
    return user;
  }

  public void setuser(String user) {
    this.user = user;
  }








  //////////////////////////////GCM_PARTNER/////////////////////////
  public String getgcmpartner() {
    return gcmpartner;
  }

  public void setgcmpartner(String gcmpartner) {
    this.gcmpartner = gcmpartner;
  }







  //////////////////////////////ID_PEDIDO/////////////////////////
  public String getid_partner() {
    return id_partner;
  }

  public void setid_partner(String id_partner) {
    this.id_partner = id_pedido;
  }








  //////////////////////////////MSG/////////////////////////
  public String getdate() {
    return date;
  }

  public void setdate(String date) {
    this.date = date;
  }

}

AND MY SECONDARY:

public class SECUNDARIA extends BaseAdapter {






    protected Activity activity;
    protected ArrayList<HttpHandler2> items;
    protected Activity context;

    public SECUNDARIA(Context activity, ArrayList<String> items) {
        this.activity = activity;
        this.items = items;


    }




    @Override
    public int getCount() {
        return items.size();
    }

    @Override
    public Object getItem(int position) {
        return items.get(position);
    }

    @Override
    public long getItemId(int position) {
        return items.get(position).getId();


    }


    @TargetApi(Build.VERSION_CODES.JELLY_BEAN)
    @Override
    public View getView(int position, View convertView, ViewGroup parent) {
        View vi=convertView;
        View vi_admin=convertView;
        View vi_user=convertView;


    final HttpHandler2 city = items.get(position);




    LayoutInflater inflater = (LayoutInflater) activity.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
    vi = inflater.inflate(R.layout.ver_chat, parent, false);








    TextView user = (TextView) vi.findViewById(R.id.notificaciones_respuesta);
    //user.setText(city.getuser()+"ID: "+city.getId());
    user.setText(city.getmsg());
    user.setPadding(28, 28, 28, 28);





    TextView msg = (TextView) vi.findViewById(R.id.notificaciones_respuesta2);
    msg.setText(city.getuser() + " F/H: " + city.getdate());




        /*COLORES*/

        GradientDrawable gd = new GradientDrawable();
        gd.setColors(new int[]{
                Color.parseColor("#8CA9F5A9"),
                Color.parseColor("#8CA9F5A9")
        });
        gd.setCornerRadius(24);




        GradientDrawable gn = new GradientDrawable();
        gn.setColors(new int[]{
                Color.parseColor("#8C58ACFA"),
                Color.parseColor("#8C58ACFA")
                //Color.CYAN
        });// Changes this drawbale to use a single color instead of a gradient
        gn.setCornerRadius(24);


         /*COLORES*/






        if (city.getuser().equals("admin")){

         LinearLayout mensages=(LinearLayout)vi.findViewById(R.id.ESTILOS_RESULTADOS);
         mensages.setGravity(Gravity.LEFT);
         user.setBackgroundDrawable(gd);
         user.setTextColor(msg.getContext().getResources().getColor(R.color.black));
         msg.setTextColor(msg.getContext().getResources().getColor(R.color.gray));







        } else if (city.getuser().equals("user")){


            LinearLayout mensages=(LinearLayout)vi.findViewById(R.id.ESTILOS_RESULTADOS);
            mensages.setGravity(Gravity.RIGHT);


        user.setBackgroundDrawable(gn);
        user.setTextColor(user.getContext().getResources().getColor(R.color.black));
         msg.setTextColor(msg.getContext().getResources().getColor(R.color.gray));

        }


        /*
        if (city.getmsg().equals("admin")){

            user.setTextAppearance(context, R.style.admin);
            msg.setTextAppearance(context, R.style.admin);



        } else{

            user.setTextAppearance(context, R.style.user);
            msg.setTextAppearance(context, R.style.user);

        }

*/





        return vi;

    }
    
asked by GoIn Su 30.06.2016 в 21:17
source

2 answers

1

I'm finally at it this way:

In my main activity:

ArrayList<HttpHandler2> diversosAvaiable = new ArrayList<HttpHandler2>();



    class List_URL extends AsyncTask<String,Void,ArrayList<HttpHandler2>>{

        @Override
        protected ArrayList<HttpHandler2> doInBackground(String... params) {
            // TODO Auto-generated method stub


            try {

                final String id_pedido = getIntent().getStringExtra("id_pedido");

                // Crear un cliente por defecto
                HttpClient mClient = new DefaultHttpClient();

                // Indicar la url
                StringBuilder sb=new StringBuilder("http://www.miweb.com/web_service/chat_api.php?id_pedido="+id_pedido);

                // Establecer la conexión después de indicar la url
                HttpPost mpost = new HttpPost(sb.toString());

                // NameValuePair : Es una clase simple que encapsula el nombre del atributo y el valor que contiene.
                // Creamos una lista de 8 atributos
                List nameValuepairs = new ArrayList();

                // Añadimos los elementos a la lista
                nameValuepairs.add(new BasicNameValuePair("id_pedido","51"));



                // UrlEncodedFormEntity : Codificamos la lista para el envio por post
                mpost.setEntity(new UrlEncodedFormEntity(nameValuepairs));

                // Ejecutamos la solicitud y obtenemos una respuesta
                HttpResponse responce = mClient.execute(mpost);

                //  Obtenemos el contenido de la respuesta
                HttpEntity entity = responce.getEntity();

                // Convertimos el stream a un String

                StringBuilder sb1 = new StringBuilder();



                String aux = "";
                BufferedHttpEntity buffer = new BufferedHttpEntity(entity);
                InputStream iStream = buffer.getContent();
                BufferedReader buf = new BufferedReader(new InputStreamReader(iStream));
                StringBuilder total = new StringBuilder();
                String line;
                while ((line = buf.readLine()) != null) {
                    aux += line;
                }
                // Parseamos la respuesta obtenida del servidor a un objeto JSON
                JSONObject jsonObject = new JSONObject(aux);
                JSONArray results = jsonObject.getJSONArray("results");


                Log.w(" RESULTADOS JSON ", String.valueOf(results));

                while ((line = buf.readLine()) != null) {
                    sb1.append(line+"\r\n");
                }

                for(int i = 0; i < results.length(); i++) {
                    JSONObject city = results.getJSONObject(i);

                    // Creamos el objeto City
                    HttpHandler2 c = new HttpHandler2(
                            city.getInt("id"),
                            city.getString("id_pedido"),
                            city.getString("user"),
                            city.getString("gcmpartner"),
                            city.getString("id_partner"),
                            city.getString("msg"),
                            city.getString("date"));
                    //c.setData(city.getString("imagen_comp"));
                    //c.setData2(city.getString("imagen_g"));

                    // Almacenamos el objeto en el array que hemos creado anteriormente
                    diversosAvaiable.add(c);

                }


                return diversosAvaiable;


            }catch(Exception e){
                //return e.getMessage();
                return null;
            }

        }
        @Override
        protected void onPostExecute(ArrayList<HttpHandler2> result){
            //super.onPostExecute(result);


            final ListView lvDiversos = (ListView) findViewById(R.id.lista_notificaciones);
            SECUNDARIA cityAdapter=new SECUNDARIA(getApplicationContext(),result);
            lvDiversos.setAdapter(cityAdapter);






        }

    }

On my Base Adapter:

public class SECUNDARIA extends BaseAdapter {


    public static final String USER = "user";
    public static final String ADMIN = "admin";

    protected ArrayList<HttpHandler2> items;




    private LayoutInflater mInflater;
    private Context context;

    public SECUNDARIA(Context ctx,ArrayList<HttpHandler2> items) {
        // TODO Auto-generated constructor stub
        this.items = items;
        this.context=ctx;
    }








    @Override
    public int getCount() {
        return items.size();
    }

    @Override
    public Object getItem(int position) {
        return items.get(position);
    }

    @Override
    public long getItemId(int position) {
        return items.get(position).getId();


    }


    @TargetApi(Build.VERSION_CODES.JELLY_BEAN)
    @Override
    public View getView(int position, View convertView, ViewGroup parent) {
        View vi=convertView;
        View vi_admin=convertView;
        View vi_user=convertView;


    final HttpHandler2 city = items.get(position);


        mInflater = (LayoutInflater)context.getSystemService(Activity.LAYOUT_INFLATER_SERVICE);
        vi = mInflater.inflate(R.layout.ver_chat, parent, false);






    TextView user = (TextView) vi.findViewById(R.id.notificaciones_respuesta);
    //user.setText(city.getuser()+"ID: "+city.getId());
    user.setText(city.getmsg());
    user.setPadding(28, 28, 28, 28);





    TextView msg = (TextView) vi.findViewById(R.id.notificaciones_respuesta2);
    msg.setText(city.getuser() + " F/H: " + city.getdate());




        /*COLORES*/

        GradientDrawable gd = new GradientDrawable();
        gd.setColors(new int[]{
                Color.parseColor("#8CA9F5A9"),
                Color.parseColor("#8CA9F5A9")
        });
        gd.setCornerRadius(24);




        GradientDrawable gn = new GradientDrawable();
        gn.setColors(new int[]{
                Color.parseColor("#8C58ACFA"),
                Color.parseColor("#8C58ACFA")
                //Color.CYAN
        });// Changes this drawbale to use a single color instead of a gradient
        gn.setCornerRadius(24);


         /*COLORES*/






        if (city.getuser().equals("admin")){

         LinearLayout mensages=(LinearLayout)vi.findViewById(R.id.ESTILOS_RESULTADOS);
         mensages.setGravity(Gravity.LEFT);
         user.setBackgroundDrawable(gd);
         user.setTextColor(msg.getContext().getResources().getColor(R.color.black));
         msg.setTextColor(msg.getContext().getResources().getColor(R.color.gray));







        } else if (city.getuser().equals("user")){


            LinearLayout mensages=(LinearLayout)vi.findViewById(R.id.ESTILOS_RESULTADOS);
            mensages.setGravity(Gravity.RIGHT);


        user.setBackgroundDrawable(gn);
        user.setTextColor(user.getContext().getResources().getColor(R.color.black));
         msg.setTextColor(msg.getContext().getResources().getColor(R.color.gray));

        }


        /*
        if (city.getmsg().equals("admin")){

            user.setTextAppearance(context, R.style.admin);
            msg.setTextAppearance(context, R.style.admin);



        } else{

            user.setTextAppearance(context, R.style.user);
            msg.setTextAppearance(context, R.style.user);

        }

*/





        return vi;

    }



}

And the HttpHandler2 Nothing was modified!

THANK YOU!

    
answered by 01.07.2016 / 00:28
source
0

The error is in this part of the code

SECUNDARIA.java

protected Activity activity;
protected ArrayList<HttpHandler2> items;
protected Activity context;

public SECUNDARIA(Context activity, ArrayList<String> items) {
    this.activity = activity;
    this.items = items;
}

The values that you assign to the variables that you declare must be of the same type, that is:

protected Activity activity;
protected ArrayList<HttpHandler2> items;
protected Activity context;

public SECUNDARIA(Activity activity, ArrayList<HttpHandler2> items) {
    this.activity = activity;
    this.items = items;
}

or like this:

protected Context activity;
protected ArrayList<String> items;
protected Activity context;

public SECUNDARIA(Context activity, ArrayList<String> items) {
    this.activity = activity;
    this.items = items;
}
    
answered by 30.06.2016 в 23:27