Listview with an icon and text

1

I have a Listview that brings me a text field from a Web server and shows it in the respective 'listview now the issue is that I want to add an icon plus the text to the lisview, but we must consider that the icon will be added as long as it finds text.

 private class AsyncRefrescar extends AsyncTask<String, String, String> {
    ProgressDialog pdLoading = new ProgressDialog(VerPreguntas.this);
    HttpURLConnection conn;
    URL url = null;

    @Override
    protected void onPreExecute() {
        super.onPreExecute();



    }


    @Override
    protected String doInBackground(String... params) {
        try {

            url = new URL("http://bdauditorio.esy.es/Verpregunta/mostrarpre.php");

        } catch (MalformedURLException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
            return e.toString();
        }
        try {


            conn = (HttpURLConnection) url.openConnection();
            conn.setReadTimeout(READ_TIMEOUT);
            conn.setConnectTimeout(CONNECTION_TIMEOUT);
            conn.setRequestMethod("GET");


            conn.setDoOutput(true);

        } catch (IOException e1) {
            // TODO Auto-generated catch block
            e1.printStackTrace();
            return e1.toString();
        }

        try {

            int response_code = conn.getResponseCode();


            if (response_code == HttpURLConnection.HTTP_OK) {


                InputStream input = conn.getInputStream();
                BufferedReader reader = new BufferedReader(new InputStreamReader(input));
                StringBuilder result = new StringBuilder();
                String line;

                while ((line = reader.readLine()) != null) {
                    result.append(line);
                }


                return (result.toString());

            } else {

                return ("unsuccessful");
            }

        } catch (IOException e) {
            e.printStackTrace();
            return e.toString();
        } finally {
            conn.disconnect();
        }


    }


    @Override
    protected void onPostExecute(String result) {


        if(result.equals("unsuccessful")) {
            final AlertDialog.Builder alertaDeError = new AlertDialog.Builder(VerPreguntas.this);
            alertaDeError.setTitle("Error");
            alertaDeError.setMessage("Ups, no se han podido cargar las preguntas. Intentelo de nuevo.");
            alertaDeError.setPositiveButton("Aceptar", new DialogInterface.OnClickListener() {
                @Override
                public void onClick(DialogInterface dialog, int which) {
                }
            });
            alertaDeError.create();
            alertaDeError.show();
        }else{
            //Existen Datos

            List<String> preguntas = new ArrayList<String>();

            //Parsea la respuesta obtenida por el Asynctask
            JSONArray jsonArray = null;
            try {
                jsonArray = new JSONArray(result);
            } catch (JSONException e) {
                e.printStackTrace();
            }
            for (int i=0; i<jsonArray.length(); i++) {
                JSONObject preguntaDatos = null;
                try {
                    preguntaDatos = jsonArray.getJSONObject(i);
                } catch (JSONException e) {
                    e.printStackTrace();
                }
                String pregunta = null;
                try {
                    pregunta = preguntaDatos.getString("pregunta");
                } catch (JSONException e) {
                    e.printStackTrace();
                }
                preguntas.add(pregunta);
            }
            //crear el Adapter.
            ArrayAdapter<String> adapter = new ArrayAdapter<String>(VerPreguntas.this,
                    android.R.layout.simple_list_item_1, preguntas);
            //Asignas el Adapter a tu ListView para mostrar los datos.
            mostrarr.setAdapter(adapter);



        }
    }

}
    
asked by Ashley G. 23.12.2016 в 21:19
source

2 answers

3

To achieve this you must make a CustomAdapter for your listview

First you create the layout with which you want each item on your list to have, it is the visual format you want to give to each of your items.

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:orientation="vertical"
    android:padding="10dp">

    <TextView
        android:id="@+id/txt"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignParentTop="true"
        android:text="Marshmallow"
        android:textAppearance="?android:attr/textAppearanceSmall"
        android:textColor="@android:color/black" />


    <ImageView
        android:id="@+id/imagen"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignParentEnd="true"
        android:layout_alignParentRight="true"
        android:layout_centerVertical="true"
        android:src="@android:drawable/ic_dialog_info" />


</RelativeLayout>

In this case, we create a TextView for the text and a ImageView for the icon.

Then we create a class that will refer to an Object, this object has two properties txt e imagen

public class Modelo {

    String txt;
    String imagen;

    public Modelo(){
    }

    public Modelo(String txt, String imagen) {
        this.txt=txt;
        this.imagen=imagen;
    }

    public String getTxt() {
        return txt;
    }

    public String getImagen() {
        return imagen;
    }

    public void setTxt(String txt){
        this.txt = txt;
    }

    public void setImagen(String imagen){
        this.imagen = imagen;
    }
}

Then we create the Custom Adapter, this kind of class allows you to manage the visual part and the elements of the previously created layout to deliver the corresponding data.

public class CustomAdapter extends ArrayAdapter<Modelo> {

    private ArrayList<Modelo> dataSet;
    Context mContext;

    // View lookup cache
    private static class ViewHolder {
        TextView txt;
        ImageView imagen;    
    }

    public CustomAdapter(ArrayList<Modelo> data, Context context) {
        super(context, R.layout.row_item, data);
        this.dataSet = data;
        this.mContext=context;

    }

    @Override
    public View getView(int position, View convertView, ViewGroup parent) {

        //Obtenemos el item de acuerdo a su posicion.
        Model dataModel = getItem(position);
        ViewHolder viewHolder;

        final View result;

        if (convertView == null) {

            viewHolder = new ViewHolder();
            LayoutInflater inflater = LayoutInflater.from(getContext());
            convertView = inflater.inflate(R.layout.row_item, parent, false);
            viewHolder.txt = (TextView) convertView.findViewById(R.id.txt);
            viewHolder.imagen = (ImageView) convertView.findViewById(R.id.imagen);

            result = convertView;

            convertView.setTag(viewHolder);
        } else {
            viewHolder = (ViewHolder) convertView.getTag();
            result = convertView;
        }

        viewHolder.txt.setText(dataModel.getName());
        //En el caso que la imagen venga desde el webservice y ya la hayas seteado en la clase asincrona.
        //viewHolder.imagen.setImageResource(dataModel.getImagen());
        return convertView;
    }
}

One of the most important methods is the getView , this method is called for each item that is created in your list, here you look for the items within your layout, format and deliver the data.

After obtaining your data asynchronously, just as you do, you must create with that result a list of objects belonging to your class Model that we created.

Replace List<String> preguntas = new ArrayList<String>(); with

ArrayList<Modelo> preguntas = new ArrayList<Modelo>();
//Parsea la respuesta obtenida por el Asynctask
JSONArray jsonArray = null;
try {
    jsonArray = new JSONArray(result);
} catch (JSONException e) {
    e.printStackTrace();
}
for (int i=0; i<jsonArray.length(); i++) {
    JSONObject preguntaDatos = null;
    try {
        preguntaDatos = jsonArray.getJSONObject(i);
    } catch (JSONException e) {
        e.printStackTrace();
    }
    String pregunta = null;
    try {
        Modelo pregunta = new Modelo();
        pregunta.txt = preguntaDatos.getString("pregunta");
        //pregunta.img = preguntaDatos.getString("imagen");
        //En el caso que no fuese la imagen la que vuelve por el webservice puedes dar las imagenes que estimes conveniente
    } catch (JSONException e) {
        e.printStackTrace();
    }
    preguntas.add(pregunta);
}
adapter = new CustomAdapter(preguntas,getApplicationContext());
//Asignas el Adapter a tu ListView para mostrar los datos.
mostrarr.setAdapter(adapter);
mostrarr.setOnItemClickListener(new AdapterView.OnItemClickListener() {
    @Override
    public void onItemClick(AdapterView<?> parent, View view, int position, long id) {

        Modelo pregunta = preguntas.get(position);

        System.out.println("Haz hecho click en "+pregunta.getTxt());
    }
});

In this example I gave an image by default to your item, which is @android:drawable/ic_dialog_info , but also leave commented as it should be in the case that it was an image from the webservice.

    
answered by 23.12.2016 / 22:40
source
1

There are several questions with something similar to what you want, in this case have a custom view that has an icon and text, for this you can create a layout layout with the elements you want, for example:

item.xml :

<?xml version="1.0" encoding="UTF-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:gravity="center"
    android:background="#000000"
    android:orientation="horizontal" >
    <ImageView
        android:id="@+id/imageView1"
        android:layout_width="100dp"
        android:layout_height="wrap_content"
        android:src="@drawable/foca" />

    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:id="@+id/text1"
        android:text="Rehabilitate Sick and Injured Seal Pups\World Oceans Week\n$1 means 1 pound of fish for a  hungry seal pup"
        android:textStyle="bold"
        android:textColor="#879BA6"
        android:background="#000000"
        android:textColorHighlight="#000000"
        android:paddingLeft="20dp"
        android:textIsSelectable="true" />
</LinearLayout>

Which would generate a view that contains an image (icon) and a text:

and this view will be inflated by means of your custom adapter within the getView () method,

I add some tutorials, one of our friends of "beautiful programming", where you can see that you simply need a personalized view with the desired elements.

Lists And Adapters On Android

and another one called How to create a custom adapter on Android

    
answered by 24.12.2016 в 00:33