根据在Autocompletetextview中选择的项目获取其他值 [英] get other values according to the item selected in Autocompletetextview

查看:122
本文介绍了根据在Autocompletetextview中选择的项目获取其他值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的AutoCompleteTextView效果很好.但是我无法根据从AutoCompleteTextView中选择的值来获取其他值(例如plantqty等).

My AutoCompleteTextView works very well. But I can't get the other values (for example plant, qty, etc.) according to the selected value from the AutoCompleteTextView.

我的JSON响应

{
    "feed": [{
        "material": "2000000",
        "plant": "2100",
        "qty": "4",
        "ton": "13.68",
        "val": "5333.44",
        "des": "4.00-08 06PR C.AUTO ZEETEX",
        "matgrp": "FG0002"
    }, {
        "material": "2000001",
        "plant": "2100",
        "qty": "13",
        "ton": "46.15",
        "val": "20566.52",
        "des": "4.00-08 06PR C.M - ZEETEX",
        "matgrp": "FG0002"
    }]
}

JsonParse类. AutoCompleteTextView完美运行.

JsonParse class. AutoCompleteTextView works perfectly.

public List<Product> getParseJsonWCF(String sName) {
    List<Product> ListData = new ArrayList<Product>();
    try {
        String temp = sName.replace(" ", "%20");
        URL js = new URL(url + temp);
        URLConnection jc = js.openConnection();
        BufferedReader reader = new BufferedReader(new InputStreamReader(jc.getInputStream()));
        String line = reader.readLine();

        JSONObject jsonResponse = new JSONObject(line);
        JSONArray jsonArray = jsonResponse.getJSONArray("feed");
        for (int i = 0; i < jsonArray.length(); i++) {
            JSONObject r = jsonArray.getJSONObject(i);
            ListData.add(new Product(r.getInt("qty"), r.getString("des"), r.getString("plant"), r.getString("matgrp")));

        }
    } catch (Exception e1) {
        // TODO Auto-generated catch block
        e1.printStackTrace();
    }
    return ListData;

}

这是我的MaterialSuggestionAdapter类.

This is my MaterialSuggestionAdapter class.

public class MaterialSuggestionAdapter extends ArrayAdapter<String> {
            private List<String> suggestions;
            private List<String> originals;
            private List<Product> new_suggestions;
            private String matCodeName;

            public MaterialSuggestionAdapter(Activity context, String matFilter) {
                super(context, android.R.layout.simple_dropdown_item_1line);
                suggestions = new ArrayList<String>();
                originals = new ArrayList<String>();
            }

            @Override
            public int getCount() {
                return suggestions.size();
            }

            @Override
            public String getItem(int position) {
                return suggestions.get(position);
            }

            @Override
            public Filter getFilter() {
                Filter filter = new Filter() {
                    @Override
                    protected FilterResults performFiltering(CharSequence charSequence) {
                        FilterResults filterResults = new FilterResults();
                        JsonParseMaterial jp = new JsonParseMaterial();
                        if ((charSequence == null || charSequence.length() == 0)) {
                            filterResults.values = originals;
                            filterResults.count = originals.size();

                        } else {
                            // A class that queries a web API, parses the data and
                            // returns an ArrayList<Product>
                            new_suggestions = jp.getParseJsonWCF(charSequence.toString());
                            suggestions.clear();
                            for (int i = 0; i < new_suggestions.size(); i++) {
                                if (new_suggestions.get(i).getMatName().toUpperCase().startsWith(charSequence.toString().toUpperCase())) {
                                    suggestions.add(new_suggestions.get(i).getMatName());
                                }
                            }

                            // Now assign the values and count to the FilterResults
                            // object
                            filterResults.values = suggestions;
                            filterResults.count = suggestions.size();
                        }
                        return filterResults;
                    }

                    @Override
                    protected void publishResults(CharSequence charSequence, FilterResults filterResults) {
                        if (filterResults != null && filterResults.count > 0) {
                            notifyDataSetChanged();
                        } else {
                            notifyDataSetInvalidated();
                        }
                    }
                };
                return filter;

            }
        }

这是我的AutoCompleteTextView.

final AutoCompleteTextView acTextView = (AutoCompleteTextView) findViewById(R.id.autoCompleteTextView);
final MaterialSuggestionAdapter adapter = new MaterialSuggestionAdapter(this, acTextView.getText().toString());
acTextView.setAdapter(adapter);
Bundle gt = getIntent().getExtras();
dealerName = gt.getString("abc");
//textView.setText(dealerName);
getSupportActionBar().setTitle(dealerName);
acTextView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
    @Override
    public void onItemClick(AdapterView < ? > adapterView, View view, int i, long l) {
        //vPager = (ViewPager) findViewById(R.id.viewPager);
        //vPager.setAdapter(new MyViewPagerAdapter(getSupportFragmentManager()));
        String newName = adapterView.getItemAtPosition(i).toString();
        //selectItemAdapter.add();
        //String s = item.getItemName();
        if (!newName.equals("")) {
            if (myRecyclerViewAdapter.getItemCount() > 1) {
                myRecyclerViewAdapter.add(1, newName);
            } else {
                myRecyclerViewAdapter.add(0, newName);
            }
        }
    }
});

这是我的堆栈跟踪朋友.

This is my stack trace friend.

02-26 04:36:53.030 6428-6428/? I/art: Late-enabling -Xcheck:jni
02-26 04:36:53.358 6428-6428/com.ceatkelanisrilanka.dushanmadushanka.ceat I/AppCompatViewInflater: app:theme is now deprecated. Please move to using android:theme instead.
02-26 04:36:53.456 6428-6464/com.ceatkelanisrilanka.dushanmadushanka.ceat D/OpenGLRenderer: Use EGL_SWAP_BEHAVIOR_PRESERVED: true
02-26 04:36:53.469 6428-6428/com.ceatkelanisrilanka.dushanmadushanka.ceat D/Atlas: Validating map...
02-26 04:36:53.526 6428-6464/com.ceatkelanisrilanka.dushanmadushanka.ceat D/libEGL: loaded /system/lib/egl/libEGL_emulation.so
02-26 04:36:53.527 6428-6464/com.ceatkelanisrilanka.dushanmadushanka.ceat D/libEGL: loaded /system/lib/egl/libGLESv1_CM_emulation.so
02-26 04:36:53.539 6428-6464/com.ceatkelanisrilanka.dushanmadushanka.ceat D/libEGL: loaded /system/lib/egl/libGLESv2_emulation.so
02-26 04:36:53.598 6428-6464/com.ceatkelanisrilanka.dushanmadushanka.ceat I/OpenGLRenderer: Initialized EGL, version 1.4
02-26 04:36:53.654 6428-6464/com.ceatkelanisrilanka.dushanmadushanka.ceat D/OpenGLRenderer: Enabling debug mode 0
02-26 04:36:53.685 6428-6464/com.ceatkelanisrilanka.dushanmadushanka.ceat W/EGL_emulation: eglSurfaceAttrib not implemented
02-26 04:36:53.685 6428-6464/com.ceatkelanisrilanka.dushanmadushanka.ceat W/OpenGLRenderer: Failed to set EGL_SWAP_BEHAVIOR on surface 0xeec35700, error=EGL_SUCCESS
02-26 04:36:54.369 6428-6428/com.ceatkelanisrilanka.dushanmadushanka.ceat I/Choreographer: Skipped 35 frames!  The application may be doing too much work on its main thread.
02-26 04:36:57.891 6428-6428/com.ceatkelanisrilanka.dushanmadushanka.ceat I/AppCompatViewInflater: app:theme is now deprecated. Please move to using android:theme instead.
02-26 04:36:57.969 6428-6464/com.ceatkelanisrilanka.dushanmadushanka.ceat W/EGL_emulation: eglSurfaceAttrib not implemented
02-26 04:36:57.969 6428-6464/com.ceatkelanisrilanka.dushanmadushanka.ceat W/OpenGLRenderer: Failed to set EGL_SWAP_BEHAVIOR on surface 0xf3fff200, error=EGL_SUCCESS
02-26 04:37:00.002 6428-6464/com.ceatkelanisrilanka.dushanmadushanka.ceat W/EGL_emulation: eglSurfaceAttrib not implemented
02-26 04:37:00.002 6428-6464/com.ceatkelanisrilanka.dushanmadushanka.ceat W/OpenGLRenderer: Failed to set EGL_SWAP_BEHAVIOR on surface 0xe247a380, error=EGL_SUCCESS
02-26 04:37:01.481 6428-6464/com.ceatkelanisrilanka.dushanmadushanka.ceat W/EGL_emulation: eglSurfaceAttrib not implemented
02-26 04:37:01.481 6428-6464/com.ceatkelanisrilanka.dushanmadushanka.ceat W/OpenGLRenderer: Failed to set EGL_SWAP_BEHAVIOR on surface 0xe247aee0, error=EGL_SUCCESS
02-26 04:37:01.990 6428-6428/com.ceatkelanisrilanka.dushanmadushanka.ceat I/AppCompatViewInflater: app:theme is now deprecated. Please move to using android:theme instead.
02-26 04:37:02.107 6428-6464/com.ceatkelanisrilanka.dushanmadushanka.ceat W/EGL_emulation: eglSurfaceAttrib not implemented
02-26 04:37:02.107 6428-6464/com.ceatkelanisrilanka.dushanmadushanka.ceat W/OpenGLRenderer: Failed to set EGL_SWAP_BEHAVIOR on surface 0xf3ffffa0, error=EGL_SUCCESS
02-26 04:37:03.220 6428-6428/com.ceatkelanisrilanka.dushanmadushanka.ceat D/AndroidRuntime: Shutting down VM
02-26 04:37:03.220 6428-6428/com.ceatkelanisrilanka.dushanmadushanka.ceat E/AndroidRuntime: FATAL EXCEPTION: main
                                                                                            Process: com.ceatkelanisrilanka.dushanmadushanka.ceat, PID: 6428
                                                                                            java.lang.ClassCastException: java.lang.String cannot be cast to com.ceatkelanisrilanka.dushanmadushanka.ceat.Product
                                                                                                at com.ceatkelanisrilanka.dushanmadushanka.ceat.MaterialSuggestionAdapter.getItem(MaterialSuggestionAdapter.java:130)
                                                                                                at com.ceatkelanisrilanka.dushanmadushanka.ceat.MaterialSuggestionAdapter.getItem(MaterialSuggestionAdapter.java:110)
                                                                                                at android.widget.AutoCompleteTextView.buildImeCompletions(AutoCompleteTextView.java:1131)
                                                                                                at android.widget.AutoCompleteTextView.showDropDown(AutoCompleteTextView.java:1091)
                                                                                                at android.widget.AutoCompleteTextView.updateDropDownForFilter(AutoCompleteTextView.java:974)
                                                                                                at android.widget.AutoCompleteTextView.onFilterComplete(AutoCompleteTextView.java:956)
                                                                                                at android.widget.Filter$ResultsHandler.handleMessage(Filter.java:285)
                                                                                                at android.os.Handler.dispatchMessage(Handler.java:102)
                                                                                                at android.os.Looper.loop(Looper.java:135)
                                                                                                at android.app.ActivityThread.main(ActivityThread.java:5254)
                                                                                                at java.lang.reflect.Method.invoke(Native Method)
                                                                                                at java.lang.reflect.Method.invoke(Method.java:372)
                                                                                                at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:903)
                                                                                                at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:698)

更新新

public class MaterialSuggestionAdapter extends BaseAdapter implements Filterable {
    private static final int MAX_RESULTS = 5;
    private Context mContext;
    private static final String url = AppConfig.URL_JSON_AVAILABLE_PRODUCTS;
    //replace this with your List<Product>
    private List<Product> mResults = new ArrayList<>();
    private List<String> locations;

    public MaterialSuggestionAdapter(Context context) {
        mContext = context;
        locations = new ArrayList<String>();
    }

    @Override
    public int getCount() {
        return mResults.size();
    }

    @Override
    public Product getItem(int index) {
        return mResults.get(index);
    }

    @Override
    public long getItemId(int position) {
        return position;
    }

    @Override
    public View getView(int position, View convertView, ViewGroup parent) {
        if (convertView == null) {
            LayoutInflater inflater = (LayoutInflater) mContext.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
            convertView = inflater.inflate(R.layout.custom_row_selected_item, parent, false);
        }

        TextView tvResult = ButterKnife.findById(convertView, R.id.txtProductName);
        tvResult.setText(getItem(position).getMatName().toString());

        return convertView;
    }


    @Override
    public Filter getFilter() {
        return new Filter() {
            @Override
            protected FilterResults performFiltering(CharSequence constraint) {
                FilterResults filterResults = new FilterResults();
                if ((constraint == null || constraint.length() == 0)) {
                    filterResults.values = locations;
                    filterResults.count = locations.size();

                } else {
                    mResults = getParseJsonWCF(constraint.toString());
                    // Assign the data to the FilterResults

                    locations.clear();
                    for (int i = 0; i < mResults.size(); i++) {
                        if (mResults.get(i).getMatName().toUpperCase().startsWith(constraint.toString().toUpperCase())) {
                            //a  = new_suggestions.get(i).getMatNo();
                            locations.add(mResults.get(i).getMatName());

                        }
                    }
                    // Assign the data to the FilterResults
                    filterResults.values = locations;
                    filterResults.count = locations.size();
                }
                return filterResults;
            }

            @SuppressWarnings("unchecked cast")
            @Override
            protected void publishResults(CharSequence constraint, FilterResults results) {
                if (results != null && results.count > 0) {
                    mResults = (List<Product>) results.values;
                    notifyDataSetChanged();
                } else {
                    notifyDataSetInvalidated();
                }
            }
        };
    }

    public List<Product> getParseJsonWCF(String sName) {
        List<Product> ListData = new ArrayList<Product>();
        try {
            String temp = sName.replace(" ", "%20");
            URL js = new URL(url + temp);
            URLConnection jc = js.openConnection();
            BufferedReader reader = new BufferedReader(new InputStreamReader(jc.getInputStream()));
            String line = reader.readLine();

            //HashMap<String, String> map_name_value = new HashMap<String, String>();

            JSONObject jsonResponse = new JSONObject(line);
            JSONArray jsonArray = jsonResponse.getJSONArray("feed");
            for (int i = 0; i < jsonArray.length(); i++) {
                JSONObject r = jsonArray.getJSONObject(i);
                ListData.add(new Product(r.getInt("qty"), r.getString("des"), r.getString("plant"), r.getString("matgrp"), r.getString("material")));

                //ListData.add(r.getString("des"));
                //map_name_value.put(r.getString("des"), r.getString("qty"));


            }
        } catch (Exception e1) {
            // TODO Auto-generated catch block
            e1.printStackTrace();
        }
        return ListData;

    }
}

这是MaterialSuggestionAdapter.java:第130行

返回mResults.get(index);

return mResults.get(index);

推荐答案

在您的MaterialSuggestionAdapter中创建如下所示的方法

In your MaterialSuggestionAdapter create a method like following

public Product getProduct(int position){
    return new_suggestions.get(position);
}

然后使用它来检索这样的产品

then use it to retrieve the product like this

//creating and setting the MaterialSuggestionAdapter
final MaterialSuggestionAdapter adapter = new MaterialSuggestionAdapter(this, acTextView.getText().toString());
acTextView.setAdapter(adapter);

acTextView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
    @Override
    public void onItemClick(AdapterView < ? > adapterView, View view, int i, long l) {
        MyViewPagerAdapter(getSupportFragmentManager()));
        String newName = adapterView.getItemAtPosition(i).toString();

        // getting the product. you can access all the details inside the 
        // Product object. Ex: selectedProduct.getQty();

        Product selectedProduct = adapter.getProduct(position);


        if (!newName.equals("")) {
            if (myRecyclerViewAdapter.getItemCount() > 1) {
                myRecyclerViewAdapter.add(1, newName);
            } else {
                myRecyclerViewAdapter.add(0, newName);
            }
        }
    }
});

更新

按如下所示重构您的MaterialSuggestionsAdapter.我正在发布对地理位置进行地理编码的我的适配器类之一.您可以简单地将其替换为您的逻辑和模型

Refactor your MaterialSuggestionsAdapter like below. I am posting one of my adapter classes that geocodes locations. You can simply replace it with your logic and model

public class GeoCodeAutoCompleteAdapter extends BaseAdapter implements Filterable {
    private static final int MAX_RESULTS = 5;
    private Context mContext;
    //replace this with your List<Product>
    private List<GeoCodeAutoCompleteResult> mResults = new ArrayList<>();

    public GeoCodeAutoCompleteAdapter(Context context) {
        mContext = context;
    }

    @Override
    public int getCount() {
        return mResults.size();
    }

    @Override
    public GeoCodeAutoCompleteResult getItem(int index) {
        return mResults.get(index);
    }

    @Override
    public long getItemId(int position) {
        return position;
    }

    @Override
    public View getView(int position, View convertView, ViewGroup parent) {
        if (convertView == null) {
            LayoutInflater inflater = (LayoutInflater) mContext.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
            convertView = inflater.inflate(R.layout.list_item_geo_code_result, parent, false);
        }

        TextView tvResult = ButterKnife.findById(convertView, R.id.tvResult);
        tvResult.setText(getItem(position).getAddress());

        return convertView;
    }


    @Override
    public Filter getFilter() {
        return new Filter() {
            @Override
            protected FilterResults performFiltering(CharSequence constraint) {
                FilterResults filterResults = new FilterResults();
                if (constraint != null) {
                    //replace findLocations method with your search logic
                    List locations = findLocations(mContext, constraint.toString());

                    // Assign the data to the FilterResults
                    filterResults.values = locations;
                    filterResults.count = locations.size();
                }
                return filterResults;
            }

            @SuppressWarnings("unchecked cast")
            @Override
            protected void publishResults(CharSequence constraint, FilterResults results) {
                if (results != null && results.count > 0) {
                    mResults = (List<GeoCodeAutoCompleteResult>) results.values;
                    notifyDataSetChanged();
                } else {
                    notifyDataSetInvalidated();
                }
            }
        };
    }

    // replace this method with your own search logic, Return the  list of model you want
    private List<GeoCodeAutoCompleteResult> findLocations(Context context, String queryText) {

        List<GeoCodeAutoCompleteResult> searchResults = new ArrayList<>();

        Geocoder geocoder = new Geocoder(context, context.getResources().getConfiguration().locale);
        List<Address> addresses;

        try {
            addresses = geocoder.getFromLocationName(queryText, MAX_RESULTS);

            for (int i = 0; i < addresses.size(); i++) {
                Address address = addresses.get(i);
                if (address.getMaxAddressLineIndex() != -1) {
                    searchResults.add(new GeoCodeAutoCompleteResult(address));
                }
            }


        } catch (IOException e) {
            e.printStackTrace();
        }

        return searchResults;
    }
}

设置适配器并检索单击的项目

Setting the adapter and retrieving clicked item

 mGeoCodeAutoCompleteAdapter = new GeoCodeAutoCompleteAdapter(getActivity());
 atvPlaceSearch.setAdapter(mGeoCodeAutoCompleteAdapter);
 atvPlaceSearch.setOnItemClickListener(new AdapterView.OnItemClickListener() {
    @Override
    public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
        GeoCodeAutoCompleteResult result = mGeoCodeAutoCompleteAdapter.getItem(position);
        //set the text to clicked result
        atvPlaceSearch.setText(result.getShortAddress());
     }
 });

这篇关于根据在Autocompletetextview中选择的项目获取其他值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆