Home Menu

Menu



Programación y Desarrollo para Android Subforo exclusivo para temas de programación de software para PDAs y desarrollo de aplicaciones, interfaces, etc bajo Android


 
Herramientas
  #1  
Viejo 10/10/15, 19:49:50
Avatar de Merche300
Merche300 Merche300 no está en línea
Betatester oficial
Mensajes: 625
 
Fecha de registro: dic 2008
Localización: Valencia
Mensajes: 625
Modelo de smartphone: NEXUS 5 - ONEPLUS 3
Versión de ROM: Cata
Versión de Radio: Radio Macuto
Tu operador: Pepephone
Mencionado: 0 comentarios
Tagged: 0 hilos
images - json

Como puedo agregar las imagenes al listview?, me sale todo pero las imagenes no se ya el porque.
Esta es la imagen private static final String ESCUDO = "escudoLocal";Gracias.

Código:
import android.util.Log;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.StatusLine;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;
import org.json.JSONArray;
import org.json.JSONException;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;

public class JSONParser {

    static InputStream is = null;
    static JSONArray jarray = null;
    static String json = "";

    public JSONParser() {
    }

    public JSONArray getJSONFromUrl(String url) {

        StringBuilder builder = new StringBuilder();
        HttpClient client = new DefaultHttpClient();
        HttpGet httpGet = new HttpGet(url);
        try {
            HttpResponse response;
            response = client.execute(httpGet);
            StatusLine statusLine = response.getStatusLine();
            int statusCode = statusLine.getStatusCode();
            if (statusCode == 200) {
                HttpEntity entity;
                entity = response.getEntity();
                InputStream content = entity.getContent();
                BufferedReader reader = new BufferedReader(new InputStreamReader(content));
                String line;
                while ((line = reader.readLine()) != null) {
                    builder.append(line);
                }
            } else {
                Log.e("Error....", "Failed to download file");
            }
        } catch (ClientProtocolException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }

        try {
            jarray = new JSONArray( builder.toString());
        } catch (JSONException e) {
            Log.e("JSON Parser", "Error parsing data " + e.toString());
        }

        return jarray;

    }
}
Código:
import android.app.ProgressDialog;
import android.content.Context;
import android.os.AsyncTask;
import android.os.Bundle;
import android.support.v4.app.ListFragment;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ListAdapter;
import android.widget.ListView;
import android.widget.SimpleAdapter;

import com.herprogramacion.restaurantericoparico.R;
import com.herprogramacion.restaurantericoparico.parser.JSONParser;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.HashMap;

public class Frag_CadeteActual extends ListFragment {


    private Context context;
    private static String url = "http://cadetes.esy.es/conexion/jornadas/j_semanal.php";

    private static final String FECHA = "fecha";
    private static final String HORA = "hora";
    private static final String LOCAL = "nomLocal";
    private static final String RLOCAL = "resulLocal";
    private static final String RVISI = "resulVisitante";
    private static final String VISI = "nomVisitante";
    private static final String ESTADO = "estadoPartido";
    private static final String ESCUDO = "escudoLocal";

    ArrayList<HashMap<String, String>> jsonlist = new ArrayList<HashMap<String, String>>();

    ListView lv ;


       @override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {

        setRetainInstance(true);

        return inflater.inflate(R.layout.j_semanal_list, container, false);
    }


       @override
    public void onActivityCreated(Bundle savedInstanceState) {
        new ProgressTask(Frag_CadeteActual.this.getActivity()).execute();
        super.onActivityCreated(savedInstanceState);
    }

    private class ProgressTask extends AsyncTask<String, Void, Boolean> {
        private ProgressDialog dialog;

        public ProgressTask(Context ListFragment) {

            Log.i("1", "Called");
            context = ListFragment;
            dialog = new ProgressDialog(context);
        }

        private Context context;

        public ProgressTask(Frag_CadeteActual cadeteActual) {

        }

        protected void onPreExecute() {
            this.dialog.setMessage("Iniciando....");
            this.dialog.show();
        }

           @override
        protected void onPostExecute(final Boolean success) {
            if (dialog.isShowing()) {
                dialog.dismiss();
            }

            ListAdapter adapter = new SimpleAdapter(context, jsonlist, R.layout.jornadas_row,
                    new String[] { FECHA, HORA, LOCAL, RLOCAL, VISI, ESTADO, ESCUDO  }, new int[]
                    { R.id.tv_fecha, R.id.tv_hora, R.id.tv_local, R.id.tv_result, R.id.tv_visitante,
                            R.id.tv_espacio, R.id.tv_escudo_local });
            setListAdapter(adapter);
            lv = getListView();

        }



        protected Boolean doInBackground(final String... args) {

            JSONParser jParser = new JSONParser();
            JSONArray json = jParser.getJSONFromUrl(url);

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

                try {
                    JSONObject c = json.getJSONObject(i);

                    String vfecha = ("Fecha: " + c.getString(FECHA));
                    String vhora = ("Hora: " + c.getString(HORA));
                    String vlocal = c.getString(LOCAL);
                    String vrlocal = (c.getString(RLOCAL) + (" - " + c.getString(RVISI)));
                    String vrvisi = c.getString(RVISI);
                    String vvisi = c.getString(VISI);
                    String vestado = c.getString(ESTADO);
                    String vescudo = ("ESTO LO SE ES LO QUE FALTA A LA DIRECCION" + c.getString(ESCUDO));

                    HashMap<String, String> map = new HashMap<String, String>();

                    map.put(FECHA, vfecha);
                    map.put(HORA, vhora);
                    map.put(LOCAL, vlocal);
                    map.put(RLOCAL, vrlocal);
                    map.put(RVISI, vrvisi);
                    map.put(VISI, vvisi);
                    map.put(ESTADO, vestado);
                    map.put(ESCUDO, vescudo);

                    jsonlist.add(map);
                } catch (JSONException e)
                {
                    e.printStackTrace();
                }
            }
            return null;

        }

    }

}

Última edición por Merche300 Día 10/10/15 a las 20:02:22
Responder Con Cita


  #2  
Viejo 10/10/15, 20:08:37
Avatar de kriogeN
kriogeN kriogeN no está en línea
Colaborador/a
Mensajes: 4,637
Compra y venta: (1)
 
Fecha de registro: oct 2010
Localización: Murcia
Mensajes: 4,637
Modelo de smartphone: Samsung Galaxy S7 Edge SM-G935F
Versión de ROM: CM13 - CM 11
Tu operador: Vodafone
Mencionado: 60 comentarios
Tagged: 3 hilos
En primer lugar, esto: R.id.tv_escudo_local ¿Es un TextView o es un ImageView? Porque por el nombre tiene pinta de ser un TextView, y en ese caso lo que te estaría haciendo es mostrar la URL.

En el caso de que sea un ImageView, hasta donde yo se (no lo digo 100% seguro, porque yo siempre trabajaba con BaseAdapter, ahora lo hago con RecyclerView.Adapter) si en un SimpleAdapter usas un ImageView siempre va a tratar de abrir un Drawable, pero nunca una URL.

Si quieres que muestre una URL tendrás que personalizar el método getView para que descargue la imagen, por ejemplo con un gestor de descarga de imágenes que también hace cacheo (yo uso Volley, pero tienes por ejemplo también Picasso o Universal Image Loader, antes usaba este último hasta que empezó a darme problemas tontos y me lo quité) y luego asignar la imagen descargada al ImageView.

Además, si te fijas la URL es relativa y no absoluta, con lo cual aunque el SimpleAdapter funcionase con URL (como he dicho antes, puede que lo haga, pero yo creo que no) tendrías que generar la URL correcta.

EDIT: No se cual se supone que es la URL base de las imágenes, pero casi todo lo que he probado me da 404.

Última edición por kriogeN Día 10/10/15 a las 20:11:13
Responder Con Cita
Gracias de parte de:
  #3  
Viejo 11/10/15, 07:16:47
Avatar de mocelet
mocelet mocelet no está en línea
Desarrollador
Mensajes: 2,203
 
Fecha de registro: may 2011
Localización: Madrid
Mensajes: 2,203
Tu operador: -
Mencionado: 17 comentarios
Tagged: 2 hilos
Poco que añadir a lo dicho por kriogeN, las URL de las imágenes enteras son del tipo
Código:
http://ffcv.es/ncompeticiones/img/logosClubes/0201157.jpg
Es decir, la base es "http://ffcv.es/ncompeticiones/", tienes que formar la URL completa y descargar la imagen con alguna biblioteca.
Responder Con Cita
Gracias de parte de:
  #4  
Viejo 13/10/15, 15:57:14
Avatar de c2alvaro
c2alvaro c2alvaro no está en línea
Miembro del foro
Mensajes: 67
 
Fecha de registro: may 2015
Localización: Venezuela
Mensajes: 67
Modelo de smartphone: Galaxy S4 mini
Versión de ROM: ROM de fabrica
Tu operador: Movistar
Mencionado: 2 comentarios
Tagged: 0 hilos
Saludos, yo hice algo similar a lo que quiere el amigo merche300, en mi caso use las imagenes de tipo Drawable y en el json que obtenia del webservice venia una indentificación basica de cada imagen, ahora use un imageview y una ArrayAdapter modificado para asignar las imagenes al listview
Responder Con Cita
Gracias de parte de:
Respuesta

Estás aquí
Regresar   HTCMania > Todo sobre Android > Programación y Desarrollo para Android


Reglas de Mensajes
You may not post new threads
You may not post replies
You may not post attachments
You may not edit your posts

BB code is On
Las caritas están On
Código [IMG] está On
Código HTML está Off

Saltar a Foro



Hora actual: 16:45:04 (GMT +1)

Cookies
Powered by vBulletin™
Copyright © vBulletin Solutions, Inc. All rights reserved.
 
HTCMania: líderes desde el 2007