Listview with custom adapter overwriting data from my post

176 views Asked by At

I am new to Java and Android.
I am using a custom adapter to fill my list_view, but then got overwritten, and I don't know what I should do.
By searching on the web I found something about "linkedhashset", but I don't know how to use it.

Adapter Class

     public class OSFuncionarioListAdapter extends ArrayAdapter<OSFuncionario> {
        private List<OSFuncionario> itemList;
        private Context context;


        public OSFuncionarioListAdapter(List<OSFuncionario> itemList, Context ctx) {
            super(ctx,android.R.layout.simple_list_item_1, itemList);
            this.itemList = itemList;
            this.context = ctx;

        }

        public int getCount() {
            if (itemList != null)
                return itemList.size();
            return 0;
        }

        public OSFuncionario getItem(int position) {
            if (itemList != null)
                return itemList.get(position);
            return null;
        }

        public long getItemId(int position) {
            if (itemList != null)
                return itemList.get(position).hashCode();
            return 0;
        }

        @Override
        public View getView(int position, View convertView, ViewGroup parent) {
            View v = convertView;
            if (v == null) {
                LayoutInflater inflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
                v = inflater.inflate(R.layout.osfuncionario_item, parent, false);
                OSFuncionario ositem = itemList.get(position);
                TextView os = (TextView) v.findViewById(R.id.IDOS);
                os.setText("OS Nº " + ositem.OS);
                TextView os1 = (TextView) v.findViewById(R.id.datadaos);
                os1.setText(ositem.Data);
                TextView os2 = (TextView) v.findViewById(R.id.solicitacao);
                os2.setText("Solicitado por: "+ositem.Solicitado);
               TextView os3 = (TextView) v.findViewById(R.id.textoosfunc);
                os3.setText(ositem.Texto+"...");
            }

            return v;

        }

        public List<OSFuncionario> getItemList() {
            return itemList;
        }

        public void setItemList(List<OSFuncionario> itemList) {
            this.itemList = itemList;
        }
    }

the fragment code

    public class OSFuncionarioFragment extends Fragment {
    OSFuncionarioListAdapter adpt;
    OSFuncionario item;
    protected SharedPreferences userLocalDatabase;
    public static final String SP_NOME="UserDetails";
    public static final  int CONNECTION_TIME = 1000 *30;
    public static final  String SERVIDOR = "http://www.creativeriopreto.com.br/app/";


    public OSFuncionarioFragment() {
        // Required empty public constructor
    }
    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        // Inflate the layout for this fragment
        View rootView = inflater.inflate(R.layout.fragment_osfuncionario, container, false);

        userLocalDatabase = getActivity().getSharedPreferences(SP_NOME, 0);
        adpt = new OSFuncionarioListAdapter(new ArrayList<OSFuncionario>(), getActivity());
        ListView lView = (ListView) rootView.findViewById(R.id.listaOSFuncionario);
        int idfuncionario = userLocalDatabase.getInt("id", -1);
        lView.setAdapter(adpt);
        item = new OSFuncionario(idfuncionario);
        (new Carregadados()).execute();
        return rootView;

    }

    private class Carregadados extends AsyncTask<String, Void, List<OSFuncionario>> {

        private final ProgressDialog dialog = new ProgressDialog(getActivity());
        @Override
        protected void onPostExecute(List<OSFuncionario> result) {
            super.onPostExecute(result);
            dialog.dismiss();
            adpt.setItemList(result);
            adpt.notifyDataSetChanged();
        }

        @Override
        protected void onPreExecute() {
            super.onPreExecute();
            dialog.setCancelable(false);
            dialog.setTitle("Carregando");
            dialog.setMessage("Por Favor Aguarde");
            dialog.show();
        }

        @Override
        protected List<OSFuncionario> doInBackground(String... params) {
            List<OSFuncionario> result = new ArrayList<OSFuncionario>();
            ArrayList<NameValuePair> data = new ArrayList<>();
            data.add(new BasicNameValuePair("id",String.valueOf(item.IDFuncionario)));
            HttpParams httprequestparams = new BasicHttpParams();
            HttpConnectionParams.setConnectionTimeout(httprequestparams, CONNECTION_TIME);
            HttpConnectionParams.setSoTimeout(httprequestparams, CONNECTION_TIME) ;
            HttpClient cliente =  new DefaultHttpClient(httprequestparams);
            HttpPost post = new HttpPost(SERVIDOR + "OS/CarregaOSFuncionario");

            try {

                post.setEntity(new UrlEncodedFormEntity(data));
                HttpResponse response =  cliente.execute(post);
                HttpEntity entity =  response.getEntity();
                String JSONResp = EntityUtils.toString(entity);
                JSONArray arr = new JSONArray(JSONResp);
                for (int i=0; i < arr.length(); i++) {
                        result.add(ConvertDados(arr.getJSONObject(i)));
                }

                return result;
            }
            catch(Throwable t) {
                t.printStackTrace();
            }
            return null;
        }

        public OSFuncionario ConvertDados(JSONObject obj) throws       JSONException {
            int OS = obj.getInt("ID");
            String solicitado = obj.getString("solicitado");
            String texto = obj.getString("texto");
            String data = obj.getString("data");
            return new OSFuncionario(OS, item.IDFuncionario, solicitado, texto, data);

        }

    }

Class Code

public class OSItinerarioClass implements Serializable {
public  int  OS, Itinerario, Versao ;
public String Data,  Finalidade, Tecnico, Cliente, Situacao;

public OSItinerarioClass(int os, int itinerario, int versao,
                         String data, String finalidade, String tecnico,   String cliente, String situacao)
  {
    this.OS = os;
    this.Itinerario = itinerario;
    this.Versao = versao;
    this.Data = data;
    this.Finalidade = finalidade;
    this.Tecnico = tecnico;
    this.Cliente = cliente;
    this.Situacao = situacao;
   }

 public OSItinerarioClass(int itinerario)
  {
    this.OS = -1;
    this.Itinerario = itinerario;
    this.Versao = -1;
    this.Data = "";
    this.Finalidade = "";
    this.Tecnico = "";
    this.Cliente = "";
    this.Situacao = "";
  }
}

XML Layout

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:padding="8dp" >

<!-- Thumbnail Image -->
<ImageView
    android:layout_width="56dp"
    android:layout_height="56dp"
    android:background="@drawable/ic_os"
    android:contentDescription="icone"
    android:id="@+id/thumbnail" />


<!-- Movie Title -->
<TextView
    android:id="@+id/IDOS"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_alignTop="@+id/thumbnail"
    android:layout_toRightOf="@+id/thumbnail"
    android:text="Numero de OS"
    android:textSize="18dp"
    android:textColor="@color/colorPrimary"
    android:layout_marginTop="5dp"
    android:textStyle="bold" />



<TextView
    android:id="@+id/solicitacao"
    android:text="Solicitacao"
    android:layout_width="fill_parent"
    android:layout_height="wrap_content"
    android:layout_below="@id/IDOS"
    android:layout_marginTop="5dp"
    android:layout_toRightOf="@+id/thumbnail"
    android:textColor="#666"
    android:textSize="@dimen/genre" />

<!-- Genre -->
<TextView
    android:id="@+id/textoosfunc"
    android:text="Texto da OS"
    android:layout_width="fill_parent"
    android:layout_height="wrap_content"
    android:layout_below="@id/solicitacao"
    android:layout_marginTop="5dp"
    android:layout_toRightOf="@+id/thumbnail"
    android:textColor="#666"
    android:textSize="@dimen/genre" />

<!-- Release Year -->
<TextView
    android:id="@+id/datadaos"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_alignParentTop="true"
    android:text="data da os"
    android:layout_alignParentRight="true"
    android:textColor="#666"
    android:layout_marginTop="5dp"
    android:textSize="@dimen/year" />

the json response from the server

[{"ID":42529,"solicitado":"teste","texto":"teste de apresentação para cliente","data":"29/03/2015"},{"ID":40546,"solicitado":"Rdorigo","texto":"Erro liberação cliente SISTEMA/RADIUS","data":"07/02/2015"},{"ID":37450,"solicitado":"Frank","texto":"Cliente solicita visita no local pois alega ","data":"09/12/2014"},{"ID":35825,"solicitado":"Mirian","texto":"Link  de 20 megas compartilhados por R$ 189,","data":"04/11/2014"},{"ID":35317,"solicitado":"Thiago Belao(teste de erro PC)","texto":"Cliente disse que o tecnico esteve no local ","data":"08/10/2014"},{"ID":33150,"solicitado":"andrea","texto":"conexão lenta","data":"31/07/2014"},{"ID":22920,"solicitado":"Angélica","texto":"Referente à desenvolvimento de site para Cad","data":"10/11/2013"},{"ID":22692,"solicitado":"SUMAIA","texto":"CLIENTE SOLICITOU ALTERAÇÕES NO SITE, FOI RE","data":"27/10/2013"},{"ID":22324,"solicitado":"ANGÉLICA","texto":"ABRINDO O.S PARA DESENVOLVIMENTO DE SITE COM","data":"05/10/2013"},{"ID":22092,"solicitado":"Guilherme","texto":"Instalar ponto de internet ( Air Gridg ) no ","data":"18/09/2013"},{"ID":21994,"solicitado":"Desenvolvimento","texto":"Desenvolvimento de Web Site . R$ 1.100,00 em","data":"11/09/2013"},{"ID":21910,"solicitado":"Ellus Bruno","texto":"Desenvolvimento de Site Gerenciavel R$ 1500,","data":"04/09/2013"},{"ID":21846,"solicitado":"Fabio","texto":"Cliente solicitou manutenção em seu web site","data":"01/09/2013"},{"ID":18986,"solicitado":"Tcharles","texto":"Instalação de Sistema Operacional, Configura","data":"19/02/2013"}]
2

There are 2 answers

1
Salmaan On BEST ANSWER

In your get view put this line on the top.

convertView = null;  

I hope it works, it solved my problem.

2
Muthukrishnan Suresh On

Try calling notifyDataSetChanged() within adapter after "this.itemList = itemList;" in setItemList and remove from onPostExecute.