Search Data in a Listview with Arrayadapter

Asked

Viewed 180 times

0

I have a listview with Jsontask to search in my database is everything OK.

In this listview I have several fields, Plate, Brand, 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 license plate of the vehicle.

Look at 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 something is missing in the search on the Adapter... can anyone lend a hand in this case?... thanks

  • Have you thought about using Recycler view? is a simpler way to implement.... just put the mandatory methods that everything will appear... there is not much error

1 answer

1


Well, it’s not very clear what kind of mistake you’re making, but I believe you may have found something that could get in your way. In his method getView you are starting the Activity before the setText of your textViews. Then try to set the textViews first and then starte the Activity.

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

startActivity(intent)

I hope it might have helped :D

Browser other questions tagged

You are not signed in. Login or sign up in order to post.