Autocompletetextview with suggestions, from a web service

Asked

Viewed 52 times

0

I have a Autocompletetextview that from a php api returns suggestions to the user based on values contained in my database.

php autocomplete.:

include_once('../includes/config.php');
    $connection = new PDO("mysql:host=$host;dbname=$database;charset=utf8", $user, $pass);
      $sql = 'SELECT * from tbl_estoque';
      $statement = $connection->prepare($sql);
      $statement->execute();
      if($statement->rowCount())
      {
            $row_all = $statement->fetchall(PDO::FETCH_ASSOC);
            header('Content-type: application/json');
            echo json_encode($row_all);

      }  
      elseif(!$statement->rowCount())
      {
          echo "no rows";
      }

inserir a descrição da imagem aqui

I want that when selecting the suggestion the Edittext for the price is filled also based on the price column of my database.

Fragmentopedidos.java

 private void AddProdutoDialog(){

    LayoutInflater inflater = LayoutInflater.from(getActivity());
    View subView = inflater.inflate(R.layout.layout_adc_produto, null);
    new AutoCompletar(getActivity(), subView).execute();
    ...

private class AutoCompletar extends AsyncTask<String, String, String> {
    private String result;
    private Context mContext;
    private View rootView;
    ProgressDialog pdLoading = new ProgressDialog(getActivity());

    public AutoCompletar(Context context, View rootView){
        this.mContext=context;
        this.rootView=rootView;
    }

    @Override
    protected void onPreExecute() {
        super.onPreExecute();

        //this method will be running on UI thread
        pdLoading.setMessage("\tAguarde...");
        pdLoading.setCancelable(false);
        pdLoading.show();

    }

    @Override
    protected String doInBackground(String... params) {
        result = null;
        PutUtility put = new PutUtility();
        try {
            result = put.postData(ADMIN_PANEL_URL + "public/autocomplete-app.php");

           /* put.setParam("UserId", params[0].toString());
            put.setParam("Latitude", params[1].toString());
            put.setParam("Longitude", params[2].toString());
            put.setParam("DateTime", params[3].toString()); */

            Log.v("result", result);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return result;

    }

    @Override
    protected void onPostExecute(String result) {
        //this method will be running on UI thread
        //ArrayList<String> dataList = new ArrayList<String>();
        List<String> dataList=new ArrayList<>();
        pdLoading.dismiss();


        if(result.equals("no rows")) {

            // Do some action if no data from database

        }else{

            try {

                JSONArray jArray = new JSONArray(result);

                // Extract data from json and store into ArrayList
                for (int i = 0; i < jArray.length(); i++) {
                    JSONObject json_data = jArray.getJSONObject(i);
                    dataList.add(json_data.getString("produto_nome"));
                }

                final AutoCompleteTextView text = (AutoCompleteTextView)
                        rootView.findViewById(R.id.tvProduto_Nome);

                ArrayAdapter<String> dataAdapter = new ArrayAdapter<String>
                        (mContext.getApplicationContext(), android.R.layout.simple_spinner_item, dataList);

                dataAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
                text.setThreshold(1);
                text.setAdapter(dataAdapter);

            } catch (JSONException e) {
                // You to understand what actually error is and handle it appropriately
                DynamicToast.makeError(getActivity(),"Não foi possível contatar o servidor.", Toast.LENGTH_LONG).show();
            }

        }

    }

}

As seen, the results are obtained by the "autocomplete" class. I just want the product name to receive suggestions but I want the price for the selected product to be filled in as well.

Here’s an example of how I want it to work:

inserir a descrição da imagem aqui

1 answer

1


I solved the problem by adding a click event to the spinner dropdown, and a hashmap.

In Arraylist it contains only the product name and in Hashmap it contains the name and the price, then in Hashmap the value (price) that corresponds to the key (product) clicked. Follow the code of the updated Autocomplete class:

private class AutoCompletar extends AsyncTask<String, String, String> {
    private String result;
    private Context mContext;
    private View rootView;
    ProgressDialog pdLoading = new ProgressDialog(getActivity());

    public AutoCompletar(Context context, View rootView){
        this.mContext=context;
        this.rootView=rootView;
    }

    @Override
    protected void onPreExecute() {
        super.onPreExecute();

        //this method will be running on UI thread
        pdLoading.setMessage("\tAguarde...");
        pdLoading.setCancelable(false);
        pdLoading.show();

    }

    @Override
    protected String doInBackground(String... params) {
        result = null;
        PutUtility put = new PutUtility();
        try {
            result = put.postData(ADMIN_PANEL_URL + "public/autocomplete-app.php");

            Log.v("result", result);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return result;

    }

    @Override
    protected void onPostExecute(String result) {
        List<String> dataList=new ArrayList<>();
        final HashMap <String, String> produtosMap = new HashMap<>();
        pdLoading.dismiss();



        if(result.equals("no rows")) {

            // Do some action if no data from database

        }else{

            try {

                JSONArray jArray = new JSONArray(result);

                // Extract data from json and store into ArrayList
                for (int i = 0; i < jArray.length(); i++) {
                    JSONObject json_data = jArray.getJSONObject(i);

                    //dataList.add(json_data.getString("produto_nome"));
                    produtosMap.put(json_data.getString("produto_nome"), json_data.getString("produto_preco"));
                    dataList.add(json_data.getString("produto_nome"));
                }

                final AutoCompleteTextView text = (AutoCompleteTextView)
                        rootView.findViewById(R.id.tvProduto_Nome);

                final EditText preco = (EditText)
                        rootView.findViewById(R.id.tvProduto_Preco);


                ArrayAdapter<String> dataAdapter = new ArrayAdapter<String>
                        (mContext.getApplicationContext(), android.R.layout.simple_spinner_item, dataList);

                dataAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
                text.setThreshold(1);
                text.setAdapter(dataAdapter);

                text.setOnItemClickListener(new AdapterView.OnItemClickListener() {
                    @Override
                    public void onItemClick (AdapterView<?> parent, View view, int position, long id) {
                        String produto = (String) parent.getAdapter().getItem(position);
                        String preco_produto = produtosMap.get(produto);
                        preco.setText(preco_produto);
                    }
                });

            } catch (JSONException e) {
                // You to understand what actually error is and handle it appropriately
                DynamicToast.makeError(getActivity(),"Não foi possível contatar o servidor.", Toast.LENGTH_LONG).show();
            }

        }

    }

}

Browser other questions tagged

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