1

Estimados, estoy intentando hacer una app que refresque los datos que estoy mostrando en un listview, pero cada vez que vuelve a ejecutar la consulta, los datos en pantalla se borran y vuelven actualizados solo si cambio de fragmento. favor me pueden ayudar?

fragmento

import android.os.Bundle;
import android.os.Handler;
import java.util.Random;
import android.support.v4.app.Fragment;
import android.os.AsyncTask;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.app.ProgressDialog;
import java.util.ArrayList;
import java.util.List;

import android.widget.AdapterView;
import android.util.Log;
import android.widget.Toast;

import org.json.JSONException;
import org.json.JSONObject;
import org.json.JSONArray;
import org.apache.http.NameValuePair;
import org.apache.http.message.BasicNameValuePair;


import android.widget.AdapterView.OnItemClickListener;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.TextView;


public class TabFragment2 extends Fragment {

    private static final String TAG_ID = "id";
    private static final String TAG_NOMBRE = "nombre";
    private static final String TAG_STATUS = "status";
    private static final String TAG_ICO = "ico";


    private ListView lista;
    JSONArray sensores = null;

    ArrayList<Sensores> datos;

    private String URL_LISTA = "http://nahuel.sideralsmarthome.cl/ajax/listar.php";
    ProgressDialog pDialog;

    Handler myHandler = new Handler();
    final Handler handler = new Handler();

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        final View view = inflater.inflate(R.layout.listado, container, false);
        /*SuccessActivity activity = (SuccessActivity) getActivity();
        String recibeDato = activity.getsensores();*/


    datos = new ArrayList<Sensores>();


    new Getsensores().execute();


    ListView lista = (ListView) view.findViewById(R.id.ListView_listado);

    lista.setAdapter(new Lista_adaptador(getContext(), R.layout.tab_fragment_2, datos) {

        @Override
        public void onEntrada(Object tab_fragment_2, View view) {
            TextView texto_superior_entrada = (TextView) view.findViewById(R.id.textView_superior);
            texto_superior_entrada.setText(((Sensores) tab_fragment_2).get_textoEncima());

            TextView texto_inferior_entrada = (TextView) view.findViewById(R.id.textView_inferior);
            texto_inferior_entrada.setText(((Sensores) tab_fragment_2).get_textoDebajo());

            ImageView imagen_entrada = (ImageView) view.findViewById(R.id.imageView_imagen);
            imagen_entrada.setImageResource(R.drawable.opendoor);

        }



    });


    lista.setOnItemClickListener(new AdapterView.OnItemClickListener() {
        @Override
        public void onItemClick(AdapterView<?> pariente, View view, int posicion, long id) {
            Sensores elegido = (Sensores) pariente.getItemAtPosition(posicion);

            CharSequence texto = "Seleccionado: " + elegido.get_textoEncima();
            Toast toast = Toast.makeText(getContext(), texto, Toast.LENGTH_LONG);
            toast.show();
        }
    });
    return view;
}


private class Getsensores extends AsyncTask<Void, Void, Void> {

    ServiceHandler sh = new ServiceHandler();
    List<NameValuePair> params = new ArrayList<NameValuePair>();

    @Override
    protected void onPreExecute() {
        super.onPreExecute();
        /*pDialog = new ProgressDialog(getActivity());
        pDialog.setMessage("Obtencion de los sensores..");
        pDialog.setCancelable(true);
        pDialog.show();*/
        params.add(new BasicNameValuePair("deviceid", "2e001d000a47353138383138"));


    }

    @Override
    protected Void doInBackground(Void... arg0) {
        ServiceHandler jsonParser = new ServiceHandler();
        String json = jsonParser.makeServiceCall(URL_LISTA, ServiceHandler.POST, params);

        Log.e("Response: ", "> " + json);

        if (json != null) {
            try {
                JSONObject jsonObj = new JSONObject(json);
                if (jsonObj != null) {
                    JSONArray sensores = jsonObj
                            .getJSONArray("sensores");

                    for (int i = 0; i < sensores.length(); i++) {
                        JSONObject catObj = (JSONObject) sensores.get(i);
                        String id = catObj.getString(TAG_ID);
                        String nombre = catObj.getString(TAG_NOMBRE);
                        String status = catObj.getString(TAG_STATUS);
                        String ico = catObj.getString(TAG_ICO);


                        datos.add(new Sensores(ico, nombre, status));

                    }
                }

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

        } else {
            Log.e("JSON Data", "¿No ha recibido ningún dato desde el servidor!");
        }

        return null;
    }


}



@Override
public void onResume(){
super.onResume();
    myHandler.postDelayed(new Runnable() {
        @Override
        public void run() {

            datos = new ArrayList<Sensores>();

            new Getsensores().execute();


            ListView lista = (ListView) getActivity().findViewById(R.id.ListView_listado);

            lista.setAdapter(new Lista_adaptador(getContext(), R.layout.tab_fragment_2, datos) {

                @Override
                public void onEntrada(Object tab_fragment_2, View view) {
                    TextView texto_superior_entrada = (TextView) view.findViewById(R.id.textView_superior);
                    texto_superior_entrada.setText(((Sensores) tab_fragment_2).get_textoEncima());

                    TextView texto_inferior_entrada = (TextView) view.findViewById(R.id.textView_inferior);
                    texto_inferior_entrada.setText(((Sensores) tab_fragment_2).get_textoDebajo());

                    ImageView imagen_entrada = (ImageView) view.findViewById(R.id.imageView_imagen);
                    imagen_entrada.setImageResource(R.drawable.opendoor);

                }


            });

            handler.postDelayed(this, 5000);

        }
    }, 0);
}

}

sensores

public class Sensores {
private String idImagen;
private String textoEncima;
private String textoDebajo;

public Sensores (String idImagen, String textoEncima, String textoDebajo) {
    this.idImagen = idImagen;
    this.textoEncima = textoEncima;
    this.textoDebajo = textoDebajo;
}

public String get_textoEncima() {
    return textoEncima;
}

public String get_textoDebajo() {
    return textoDebajo;
}

public String get_idImagen() {
    return idImagen;


   }
}


    import java.util.ArrayList;

import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;



public abstract class Lista_adaptador extends BaseAdapter {

    private ArrayList<?> entradas;
    private int R_layout_IdView;
    private Context contexto;

    public Lista_adaptador(Context contexto, int R_layout_IdView, ArrayList<?> entradas) {
        super();
        this.contexto = contexto;
        this.entradas = entradas;
        this.R_layout_IdView = R_layout_IdView;
    }

    @Override
    public View getView(int posicion, View view, ViewGroup pariente) {
        if (view == null) {
            LayoutInflater vi = (LayoutInflater) contexto.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
            view = vi.inflate(R_layout_IdView, null);
        }
        onEntrada (entradas.get(posicion), view);
        return view;
    }

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

    @Override
    public Object getItem(int posicion) {
        return entradas.get(posicion);
    }

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

    /** Devuelve cada una de las entradas con cada una de las vistas a la que debe de ser asociada
     * @param entrada La entrada que será la asociada a la view. La entrada es del tipo del paquete/handler
     * @param view View particular que contendrá los datos del paquete/handler
     */
    public abstract  void onEntrada (Object tab_fragment_2, View view);
3
  • si alguien me puede ayudar seria ideal el 5 may. 2017 a las 16:43
  • lo tratas de realizar en onResume() ? porque razón?
    – Jorgesys
    el 5 may. 2017 a las 17:47
  • lo que probado en todas partes, siempre lo he tenido en onCreated(), pero lo pase a onResume pensando que no me borraria el contenido. pero lo hace igual el 6 may. 2017 a las 4:49

1 respuesta 1

-1

Cuando defines un Adapter con nuevos datos, debes mandar recargar los datos en la vista que tiene configurado el Adapter por medio del método .notifyDataSetChanged(), realiza este cambio :

        ListView lista = (ListView) getActivity().findViewById(R.id.ListView_listado);


Lista_adaptador myAdapter = new Lista_adaptador(getContext(), R.layout.tab_fragment_2, datos) {

            @Override
            public void onEntrada(Object tab_fragment_2, View view) {
                TextView texto_superior_entrada = (TextView) view.findViewById(R.id.textView_superior);
                texto_superior_entrada.setText(((Sensores) tab_fragment_2).get_textoEncima());

                TextView texto_inferior_entrada = (TextView) view.findViewById(R.id.textView_inferior);
                texto_inferior_entrada.setText(((Sensores) tab_fragment_2).get_textoDebajo());

                ImageView imagen_entrada = (ImageView) view.findViewById(R.id.imageView_imagen);
                imagen_entrada.setImageResource(R.drawable.opendoor);

            }
        }

        lista.setAdapter(myAdapter);

        //RECARGA DATOS NUEVAMENTE!
        myAdapter.notifyDataSetChanged();
2
  • muchas gracias, hice los cambios, pero me pasa lo mismo. carga el fragmento con los datos, luego pasan los 5 segundos del run(), queda en blanco y al cambiar de fragmento aparecen los datos nuevamente. lo que quiero lograr es que se actualice automaticamente. tipo ajax. no estoy agregando mas campos, estoy cambiando el texto que dice "texto abajo" desde la base de datos. el 6 may. 2017 a las 4:48
  • Si asignan -1 , al menos agreguen una razón.
    – Jorgesys
    el 8 may. 2017 a las 18:11

Tu Respuesta

By clicking “Publica tu respuesta”, you agree to our terms of service and acknowledge you have read our privacy policy.

¿No es la respuesta que buscas? Examina otras preguntas con la etiqueta o formula tu propia pregunta.