Refresh listview android in fragment

1

Dear, I'm trying to make an app that refreshes the data I'm showing in a listview, but every time you re-run the query, the data on the screen is erased and updated only if you change the fragment. can you help me?

Shard

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);
}

}

sensors

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);
    
asked by Patricio Caceres Morales 05.05.2017 в 18:43
source

1 answer

-1

When you define a Adapter with new data, you should send reload the data in the view that you have set Adapter by means of the method . notifyDataSetChanged () , make this change:

        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();
    
answered by 05.05.2017 в 19:45