Fill data to a custom ListView from server (Web Service)

1

Good afternoon.

I'm running a web service on Android, in this case I'm pulling data from a table in MySql that I have on a server to populate a custom ListView.

The query I have is that the data I'm trying to get is not being populated in the ListView. I'm using PHP, MySQL.

Being more specific, I'm pulling the data from a table in mysql, I save it in a get set class, and then I create an array of that class and then populate it in the custom listview, I'll leave the code of all this below.

This is my Json result that I get from the php.

[{"idproducto":"1","idtipo":"1","descproducto":"Loza de tama\u00f1o 7x9","imagen":"http:\/\/appfotoceramica.pe.hu\/01.jpg"},{"idproducto":"2","idtipo":"2","descproducto":"L\u00e1pida cl\u00e1sica","imagen":"http:\/\/appfotoceramica.pe.hu\/hola.jpg"}]

Now this is the code on Android.

 public class Productos extends Activity {

  Spinner spTipoProducto;
  ListView listaProducto;
  ProgressDialog pd;

  String resultadoTotal;


@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    requestWindowFeature(Window.FEATURE_NO_TITLE);
    getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN, 0);
    setContentView(R.layout.activity_productos);

    spTipoProducto = (Spinner) findViewById(R.id.spSeleccionar);
    listaProducto = (ListView) findViewById(R.id.listaProductos);


   EjecutarTodo();

}

private String Conectar(){

    int respuesta = 0;
    StringBuilder stringBuilder = null;
    String linea = "";
    URL url = null;

    try{
        url = new URL("http://appfotoceramica.pe.hu/cargarimagen.php");

        HttpURLConnection conexion = (HttpURLConnection) url.openConnection();
        respuesta = conexion.getResponseCode();

        stringBuilder = new StringBuilder();

        if(respuesta == HttpURLConnection.HTTP_OK){

            InputStream inputStream = new BufferedInputStream(conexion.getInputStream());
            BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(inputStream));

            while((linea = bufferedReader.readLine()) != null){
                   stringBuilder.append(linea + "\n");
            }
        }

    }catch (Exception e){
        e.printStackTrace();
    }
    return resultadoTotal = stringBuilder.toString();
}

public void ObtenerJson(String result){
    try{

        JSONArray jsonArray = new JSONArray(result);
        ProductoBean pb;

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

            pb.setCodigoproducto(jsonArray.getJSONObject(i).getInt("idproducto"));
            pb.setIdtipo(jsonArray.getJSONObject(i).getInt("idtipo"));
            pb.setDescproducto(jsonArray.getJSONObject(i).getString("descproducto"));
            pb.setImagen(jsonArray.getJSONObject(i).getString("imagen"));


        }

    }catch (Exception e){
        e.printStackTrace();
    }
}

protected class HiloCargarImagen extends AsyncTask<String, Void, Object>{

    @Override
    protected Object doInBackground(String... strings) {
        Conectar();
        return null;
    }

    protected void onPostExecute(Object result){
        pd.dismiss();
        ObtenerJson(resultadoTotal);
        ArrayList<ProductoBean> productoBean = new ArrayList<ProductoBean>();
        Adaptador adaptador = new Adaptador(Productos.this, productoBean);
        listaProducto.setAdapter(adaptador);

    }
}

private void EjecutarTodo(){
    pd = ProgressDialog.show(this, "Cargando productos", "Espere por favor...", true, false);
    new HiloCargarImagen().execute();
  }
}

This is the adapter to create the ListView personalization.

    public class Adaptador extends BaseAdapter {

Context context;
ArrayList<ProductoBean> pb;


public Adaptador(Context ctx, ArrayList<ProductoBean> productos){
    context = ctx;
    pb = productos;
}

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

@Override
public Object getItem(int i) {
    return pb.get(i);
}

@Override
public long getItemId(int i) {
    return i;
}

@Override
public View getView(int i, View view, ViewGroup viewGroup) {

    if(view == null){

        LayoutInflater layoutInflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
        view = layoutInflater.inflate(R.layout.customlistview,viewGroup,false);

        TextView tipoProducto, descProducto;
        SmartImageView imagen;

        tipoProducto = (TextView) view.findViewById(R.id.textoTipoProducto);
        descProducto = (TextView) view.findViewById(R.id.textoDescripcionProducto);
        imagen = (SmartImageView) view.findViewById(R.id.imagenProducto);

        int id;

        id = pb.get(i).getIdtipo();

        if(id == 1){
            tipoProducto.setText("Lozas");
        }else if(id == 2){
            tipoProducto.setText("Lápidas");
        }else if(id == 3){
            tipoProducto.setText("Tarjeteros");
        }else{
            tipoProducto.setText("Fotos 20x30");
        }

        descProducto.setText(pb.get(i).getDescproducto());
        imagen.setImageUrl(pb.get(i).getImagen());

     }

    return view;
   }
}

I upload the php part anyway.

 <?php

$conexion =   mysqli_connect("mysql.hostinger.es","u534134956_jorge","jorgejorge","u534134956_appfo");

$query = mysqli_query($conexion, "select * from producto");

while($fila = mysqli_fetch_array($query, MYSQLI_ASSOC){

$idproducto = $fila["idproducto"];
$idtipo = $fila["idtipo"];
$descproducto = $fila["descproducto"];
$imagen = $fila["imagen"];

  $productos[] = array("idproducto" => $idproducto, "idtipo" => $idtipo, "descproducto" => $descproducto, "imagen" => $imagen);

  }

 $json = json_encode($productos);
 echo $json;


?>
    
asked by Jorge Requez 05.01.2017 в 20:52
source

1 answer

1

It seems that the problem is that you are creating instances of ProductoBean and you are not doing anything with them, and you are passing an empty list to your adapter, you can do the following:

public ArrayList<ProductoBean> ObtenerJson(String result){
try{
    ArrayList<ProductoBean> productoBean = new ArrayList<ProductoBean>();
    JSONArray jsonArray = new JSONArray(result);
    ProductoBean pb;

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

        pb.setCodigoproducto(jsonArray.getJSONObject(i).getInt("idproducto"));
        pb.setIdtipo(jsonArray.getJSONObject(i).getInt("idtipo"));
        pb.setDescproducto(jsonArray.getJSONObject(i).getString("descproducto"));
        pb.setImagen(jsonArray.getJSONObject(i).getString("imagen"));

        //Agregas a tu lista el nuevo objeto
        productoBean.add(pb);

    }
    //Devuelves el listado
    return productoBean;

  }catch (Exception e){
    e.printStackTrace();
  }

   return null;

}

On your onPostExecute, you get the list

  protected void onPostExecute(Object result){
    pd.dismiss();

    ArrayList<ProductoBean> productoBean = ObtenerJson(resultadoTotal);
    if (productoBean != null){
       Adaptador adaptador = new Adaptador(Productos.this, productoBean);
       listaProducto.setAdapter(adaptador);
    }

}

Suggestion : You must use the ViewHolder pattern on your Adapter

    
answered by 05.01.2017 / 22:16
source