Finding Data in a ListView with ArrayAdapter

0

I have a listView with JSONTask to fetch from my database everything is Ok.

In this listView I have several fields, Card, Tag, Model, Year, etc.

I saw some examples on the net but it is for simple search of a single line I tried to put in my code but it did not work very well, in my case I just need to get the vehicle's license plate.

See my code I made ...

       private ListView lvRevistas;

public static String CodigoAcessoEmpresa;
public static String PlacaVeiculo;
private EditText etSearch;
// Search EditText


RevistaAdpter adapter;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    lvRevistas = (ListView)findViewById(R.id.lvRevista);

    etSearch = (EditText)findViewById(R.id.etSearch);


    Intent intent = getIntent();

    PlacaVeiculo = (intent.getStringExtra("Placa"));

    // Add Text Change Listener to EditText
    etSearch.addTextChangedListener(new TextWatcher() {

        @Override
        public void onTextChanged(CharSequence s, int start, int before, int count) {
            // Call back the Adapter with current character to Filter
            adapter.getFilter().filter(s.toString());
        }

        @Override
        public void beforeTextChanged(CharSequence s, int start, int count,int after) {
        }

        @Override
        public void afterTextChanged(Editable s) {
        }
    });

//Restaura as preferencias gravadas
    SharedPreferences settings = getSharedPreferences(Login_Empresa.PREFS_NAME, 0);
    CodigoAcessoEmpresa = (settings.getString("PrefUsuario", ""));

    if(CodigoAcessoEmpresa != null && !CodigoAcessoEmpresa.trim().isEmpty()) {
        CodigoAcessoEmpresa ="M001P4";
    }

    if(isNetworkAvailable()){
        new JSONTask().execute("http://www.promastersolution.com.br/x7890_IOS/garageiro/listar_veiculos.php?tipo_os=android&id_empresa="+CodigoAcessoEmpresa);

    } else {
        AlertDialog.Builder Checkbuilder = new AlertDialog.Builder(MainActivity.this);
        Checkbuilder.setIcon(R.drawable.error);
        Checkbuilder.setTitle("Erro");
        Checkbuilder.setMessage("Sem conexão com internet...");

        Checkbuilder.setPositiveButton("Tentar novamente", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {

                new JSONTask().execute("http://www.promastersolution.com.br/x7890_IOS/garageiro/listar_veiculos.php?tipo_os=android&id_empresa="+CodigoAcessoEmpresa);

               Intent intent = getIntent();
               finish();
               startActivity(intent);
            }
        });

        Checkbuilder.setNegativeButton("Sair", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                finish();
            }
        });
        AlertDialog alert = Checkbuilder.create();
        alert.show();
    }
 }
private boolean isNetworkAvailable(){
    ConnectivityManager cm = (ConnectivityManager)this.getSystemService(Context.CONNECTIVITY_SERVICE);
    NetworkInfo activeNeworkInfo = cm.getActiveNetworkInfo();

    return activeNeworkInfo != null;
}



public class JSONTask extends AsyncTask<String, String, List<RevistaModel>> {

    protected void onPreExecute(){
        super.onPreExecute();
      //  dialog.show();

    }

    @Override
    protected List<RevistaModel> doInBackground(String... params) {

        HttpURLConnection connection = null;
        BufferedReader reader = null;

        try {
            URL url = new URL(params[0]);
            connection = (HttpURLConnection) url.openConnection();
            connection.connect();

            InputStream stream = connection.getInputStream();

            reader = new BufferedReader(new InputStreamReader(stream));

            StringBuffer buffer = new StringBuffer();

            String line = "";

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

            String finalJson = buffer.toString();

            JSONObject parentObject = new JSONObject(finalJson);

            JSONArray parentArray = parentObject.getJSONArray("entrega");


                StringBuffer finalBuferedData = new StringBuffer();

                List<RevistaModel> revistaModelList = new ArrayList<>();

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

                    JSONObject finalObject = parentArray.getJSONObject(i);

                    RevistaModel revistaModel = new RevistaModel();
                    ///recebe os dados
                    revistaModel.setId(finalObject.getInt("Id_veiculo"));
                    revistaModel.setEdicao(finalObject.getString("Placa"));
                    revistaModel.setModelo(finalObject.getString("marca_modelo"));
                    revistaModel.setNome_cambio(finalObject.getString("Nome_cambio"));
                    revistaModel.setNome_Combustivel(finalObject.getString("Nome_Combustivel"));
                    revistaModel.setNome_cor(finalObject.getString("Nome_cor"));
                    revistaModel.setKM(finalObject.getString("KM"));
                    revistaModel.setVersao(finalObject.getString("Versao"));
                    revistaModel.setValor_deVenda(finalObject.getString("Valor_deVenda"));
                    revistaModel.setObservacoes(finalObject.getString("Observacoes"));

                    revistaModelList.add(revistaModel);
                }

                return revistaModelList;

            } // Try
            catch(MalformedInputException e){
                e.printStackTrace();
            }catch(IOException e){
                e.printStackTrace();
            }catch(JSONException e){
                e.printStackTrace();

            }finally{
                if (connection != null) {
                    connection.disconnect();
                }
                try {
                    if (reader != null) {
                        reader.close();
                    }
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            return null;

    }

    @Override
    protected void onPostExecute(List<RevistaModel> result) {
        super.onPostExecute(result);
        //dialog.dismiss();
        adapter = new RevistaAdpter(getApplicationContext(), R.layout.row, result);
        lvRevistas.setAdapter(adapter);

    }
}
public class RevistaAdpter extends ArrayAdapter implements Filterable {

    private List<RevistaModel> revistaModelList;
    private int resource;
    private LayoutInflater inflater;

    public RevistaAdpter(Context context, int resource, List<RevistaModel> objects){
        super(context, resource, objects);

        revistaModelList = objects;
        this.resource = resource;
        inflater = (LayoutInflater) getSystemService(LAYOUT_INFLATER_SERVICE);
    }

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

        ViewHolder holder = null;

        final String[] UrlRevista = new String[1];

        if (convertView == null){
            holder = new ViewHolder();
            convertView = inflater.inflate(resource, null);

            holder.txPlaca         = (TextView)convertView.findViewById(R.id.txPlaca);
            holder.txMarca_Modelo  = (TextView)convertView.findViewById(R.id.txMarcaModelo);

            lvRevistas.setOnItemClickListener(new AdapterView.OnItemClickListener() {
                @Override
                public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                    String Id_veiculo = String.valueOf(revistaModelList.get(position).getId());
                    String Placa = revistaModelList.get(position).getEdicao();
                    String MarcaModelo = revistaModelList.get(position).getModelo();
                    String Cambio = revistaModelList.get(position).getNome_cambio();
                    String Combustivel = revistaModelList.get(position).getNome_Combustivel();
                    String Cor = revistaModelList.get(position).getNome_cor();
                    String KM = revistaModelList.get(position).getKM();
                    String Versao = revistaModelList.get(position).getVersao();
                    String Valor_Venda = revistaModelList.get(position).getValor_deVenda();
                    String Observacao = revistaModelList.get(position).getObservacoes();

                    Intent intent = new Intent(MainActivity.this, detalhes_veiculo.class);

                    intent.putExtra("Id_veiculo", Id_veiculo); //Optional parameters
                    intent.putExtra("Placa", Placa); //Optional parameters
                    intent.putExtra("MarcaModelo", MarcaModelo); //Optional parameters
                    intent.putExtra("Cambio", Cambio); //Optional parameters
                    intent.putExtra("Combustivel", Combustivel); //Optional parameters
                    intent.putExtra("Cor", Cor); //Optional parameters
                    intent.putExtra("KM", KM); //Optional parameters
                    intent.putExtra("Versao", Versao); //Optional parameters
                    intent.putExtra("Valor_Venda", Valor_Venda); //Optional parameters
                    intent.putExtra("Observacao", Observacao); //Optional parameters
                    intent.putExtra("Id_Empresa", CodigoAcessoEmpresa); //Optional parameters

                    startActivity(intent);
                }
            });

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

        }
holder.txPlaca.setText(revistaModelList.get(position).getEdicao());
holder.txMarca_Modelo.setText(revistaModelList.get(position).getModelo());
          return convertView;
    }
    class ViewHolder{

        private TextView txPlaca;
        private TextView txMarca_Modelo;

    }
} } <code/> 

In this case here I know that something is missing in the search on the adapter ... can someone lend a hand in this case? ... thanks!

    
asked by anonymous 23.03.2017 / 01:01

1 answer

1

Well, it was not very clear what mistake you're having, but I think you may have found something that might get in the way. In your getView method you are starting the Activity before the setText of your textViews. Then try to set the textViews first and then start the activity.

iholder.txPlaca.setText(revistaModelList.get(position).getEdicao());
holder.txMarca_Modelo.setText(revistaModelList.get(position).getModelo());

startActivity(intent)

I hope you have helped: D

    
28.03.2017 / 16:07