本文介绍了获得autocompletetextview位置的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有两个autocompletetextviews,在第一autocompletetextview我使用JSON正从服务器的项目,对于下面是响应

<$p$p><$c$c>{\"status\":\"success\",\"clientlist\":[{\"cid\":\"1\",\"name\":\"margi\"},{\"cid\":\"2\",\"name\":\"steven\"}],\"productboxtype\":[{\"pbxid\":\"1\",\"pbxname\":\"1打,qtyperbox:12},{pbxid:2,pbxname:2数十,qtyperbox:24},{pbxid:3,pbxname :3数十,qtyperbox:36}]}

我能够在我的第一个自动完成获得的名称和它工作正常,

现在的问题是假设用户选择项摩尔吉,其CID是1,所以我再次发送请求到服务器,并试图让摩尔吉的productnames,其响应

  {地位:成功,clientproduct:[{PID:4,名:康安pair\",\"unitprice\":\"1500\",\"boxqty\":\"1\",\"bulkprice\":[{\"minqty\":\"10\",\"price\":\"1500\"},{\"minqty\":\"15\",\"price\":\"1470\"},{\"minqty\":\"20\",\"price\":\"1460\"}]}]}

MYActivity.java

 公共类MainActivity延伸活动{
私人AutoCompleteTextView acTextView;
私人字符串catidtemp;
JSONParser jsonParser =新JSONParser();
私人AutoCompleteTextView autoproduct;
私有静态最后弦乐FEEDBACK_URL =;
私有静态最后弦乐FEEDBACK_SUCCESS =身份;
@覆盖
保护无效的onCreate(捆绑savedInstanceState){
    super.onCreate(savedInstanceState);
    的setContentView(R.layout.activity_main);    acTextView =(AutoCompleteTextView)findViewById(R.id.autocmplte_clorder_clname);
    acTextView.setAdapter(新SuggestionAdapterClientList(在此,acTextView.getText()的toString())。);    autoproduct =(AutoCompleteTextView)findViewById(R.id.autocmplte_clorder_product);
    autoproduct.setAdapter(新SuggestionAdapterClientProduct(在此,autoproduct.getText()的toString())。);    acTextView.setOnItemClickListener(新OnItemClickListener(){        @覆盖
        公共无效onItemClick(适配器视图&LT;&GT;母公司,观景,
                INT位置,长的id){
            // TODO自动生成方法存根
            JsonParseClientProduct JP =新JsonParseClientProduct();
              清单&LT; SuggestGetSetClientProduct&GT; list1的= jp.getParseJsonWCF(
                                                。autoproduct.getText()的toString());
              新AttemptLogin(list1.get(位置).getId())执行();
        }
    });}  类AttemptLogin扩展的AsyncTask&LT;字符串,字符串,字符串&GT; {    布尔失败= F​​ALSE;
    私人ProgressDialog pDialog;    私人INT selected_cid = 1;
    AttemptLogin(INT selected_cid){
    this.selected_cid = selected_cid;
    }
    @覆盖
    在preExecute保护无效(){
        super.on preExecute();
        pDialog =新ProgressDialog(MainActivity.this);
        pDialog.setMessage(发送..);
        pDialog.setIndeterminate(真);
      // pDialog.setIndeterminateDrawable(getResources()getDrawable(R.drawable.custom_progress));
        pDialog.setCancelable(真);
        pDialog.show();
    }    @燮pressWarnings(未使用)
    @覆盖
    保护字符串doInBackground(字符串参数... args){
        //检查成功标记
        // INT成功;
        尺蠖prepare()。         尝试{             JsonParseClientList JP =新JsonParseClientList();
                清单&LT;&的NameValuePair GT; PARAMS =新的ArrayList&LT;&的NameValuePair GT;();
             清单&LT; SuggestGetSetClientList&GT;清单= jp.getParseJsonWCF(acTextView.getText()的toString());                 的for(int i = 0; I&LT;则为list.size();我++)
                 {
                   如果(list.get(I).getName()。等于(acTextView.getText()。的toString()))
                   // params.add(新BasicNameValuePair(CID,list.get(ⅰ).getId()));                       params.add(新BasicNameValuePair(CID,selected_cid);                     // CATID = list.get(ⅰ).getId();
                  // catidtemp = list.get(ⅰ).getId();
                 }                 catidtemp = list.get(0).id.toString();
            // catidtemp = list.get(ⅰ).getId();
             的System.out.println(cattttttiiiiddd ????+ catidtemp);
             params.add(新BasicNameValuePair(行动,clientproduct));             的System.out.println(苏gayu服务器马????+参数);             Log.d(!要求,出发);
             //通过HTTP请求获得产品的详细信息
             JSONObject的JSON = jsonParser.makeHtt prequest(
                 FEEDBACK_URL,POST,则params);
             //检查你的日志,JSON响应
             Log.d(登录尝试,json.toString());             JSONObject的jobj =新的JSONObject(json.toString());
             最后弦乐味精= jobj.getString(味精);
             返回json.getString(FEEDBACK_SUCCESS);         }赶上(JSONException E){
             e.printStackTrace();
         }
         返回null;
    }    //后台完成任务后辞退进度对话框    保护无效onPostExecute(字符串FILE_URL){
        //关闭该对话框一旦产品被删除
        pDialog.dismiss();        //parentcat.getText()清()。
}}
  公共类SuggestGetSetClientProduct {        串ID,名称;
        公共SuggestGetSetClientProduct(ID字符串,字符串名称){
            this.setId(ID);
            this.setName(名);
        }
        公共字符串的getId(){
            返回ID;
        }        公共无效SETID(字符串ID){
            this.id = ID;
        }        公共字符串的getName(){
            返回名称;
        }        公共无效setname可以(字符串名称){
            this.name =名称;
        }
    }   公共类JsonParseClientProduct {
        双current_latitude,current_longitude;
        公共JsonParseClientProduct(){}
        公共JsonParseClientProduct(双current_latitude,双current_longitude){
            this.current_latitude = current_latitude;
            this.current_longitude = current_longitude;
        }
        公开名单&LT; SuggestGetSetClientProduct&GT; getParseJsonWCF(字符串SNAME)
           {
            清单&LT; SuggestGetSetClientProduct&GT;的ListData =新的ArrayList&LT; SuggestGetSetClientProduct&GT;();
            尝试{
               串临时= sName.replace(,%20);
               URL = JS新的URL();               的System.out.println(什么他妈的+ JS);
               URLConnection的JC = js.openConnection();
               读者的BufferedReader =新的BufferedReader(新的InputStreamReader(jc.getInputStream()));
               串行= reader.readLine();
               JSONObject的jsonResponse =新的JSONObject(线);
               JSONArray jsonArray = jsonResponse.getJSONArray(clientproduct);
               的for(int i = 0; I&LT; jsonArray.length();我++){
                   的JSONObject R = jsonArray.getJSONObject(ⅰ);
                   ListData.add(新SuggestGetSetClientProduct(r.getString(PID),r.getString(名称)))​​;
               }
           }赶上(例外E1){
               // TODO自动生成catch块
               e1.printStackTrace();
           }
            返回的ListData;           }
    }
    公共类SuggestionAdapterClientProduct扩展ArrayAdapter&LT;串GT; {
        受保护的静态最后弦乐TAG =SuggestionAdapter;
        私人列表&LT;串GT;建议;
        公共SuggestionAdapterClientProduct(Activity上下文,弦乐nameFilter){
            超(背景下,android.R.layout.simple_dropdown_item_1line);
            建议=新的ArrayList&LT;串GT;();
        }        @覆盖
        公众诠释的getCount(){
            返回suggestions.size();
        }        @覆盖
        公共字符串的getItem(INT指数){
            返回suggestions.get(索引);
        }        @覆盖
        公共过滤用getFilter(){
            过滤myFilter =新的过滤器(){
                @覆盖
                保护FilterResults performFiltering(CharSequence的约束){
                    FilterResults filterResults =新FilterResults();
                    JsonParseClientProduct JP =新JsonParseClientProduct();
                    如果(约束!= NULL){
                        //用于查询的Web API的类,分析数据和
                        //返回一个ArrayList&LT; GoEuroGetSet&GT;
                        清单&LT; SuggestGetSetClientProduct&GT; new_suggestions = jp.getParseJsonWCF(constraint.toString());
                        suggestions.clear();
                        / *的for(int i = 0; I&LT; new_suggestions.size();我++){
                        suggestions.add(new_suggestions.get(ⅰ).getName());
                    } * /                    的for(int i = 0; I&LT; new_suggestions.size();我++){
                        字符串名称= new_suggestions.get(I).getName();
                        串ID = new_suggestions.get(ⅰ).getId();
                        的System.out.println(checis ID+ ID);
                        如果(name.contains(约束)){
                        suggestions.add(new_suggestions.get(ⅰ).getName());
                           }
                    }
                        //现在分配值,并计算到FilterResults
                        //对象
                        filterResults.values​​ =建议;
                        filterResults.count = suggestions.size();
                    }
                    返回filterResults;
                }                @覆盖
                保护无效publishResults(CharSequence的约束实现的,
                        FilterResults结果){
                    如果(结果= NULL&放大器;!&安培; results.count大于0){
                        notifyDataSetChanged();
                    }其他{
                        notifyDataSetInvalidated();
                    }
                }
            };
            返回myFilter;
        }
    }

}

问题here..I我不能够得到的ID的位置。

  {尝试             JsonParseClientList JP =新JsonParseClientList();
                清单&LT;&的NameValuePair GT; PARAMS =新的ArrayList&LT;&的NameValuePair GT;();
             清单&LT; SuggestGetSetClientList&GT;清单= jp.getParseJsonWCF(acTextView.getText()的toString());                 的for(int i = 0; I&LT;则为list.size();我++)
                 {
                   如果(list.get(I).getName()。等于(acTextView.getText()。的toString()))
                    params.add(新BasicNameValuePair(CID,list.get(ⅰ).getId()));                     // CATID = list.get(ⅰ).getId();                 }                 对于(INT B = 0; B&LT;则为list.size(); B ++)
                 {
                     catidtemp = list.get(0).id.toString();
                     的System.out.println(cattttttiiiiddd ????+ catidtemp);
                 }


解决方案

使用 list1的获取选定 CID 从ListView的:

  @覆盖
  公共无效onItemClick(适配器视图&LT;&GT;母公司,观景,
                INT位置,长的id){
            // TODO自动生成方法存根
      JsonParseClientProduct JP =新JsonParseClientProduct();
      清单&LT; SuggestGetSetClientProduct&GT; list1的= jp.getParseJsonWCF(
                                        。autoproduct.getText()的toString());
      新AttemptLogin(list1.get(位置).getId())执行();
}

和创建 AttemptLogin 构造类:

 类AttemptLogin扩展的AsyncTask&LT;字符串,字符串,字符串&GT; {    布尔失败= F​​ALSE;
    私人ProgressDialog pDialog;
    私人INT selected_cid = 1;
    AttemptLogin(INT selected_cid){
    this.selected_cid = selected_cid;
    }
   // ...您code
}

现在使用 selected_cid 的补充 CID 作为参数:

  params.add(新BasicNameValuePair(CID,selected_cid);

I have two autocompletetextviews,in first autocompletetextview i am getting items from server using json,the following is response for that

{"status":"success","clientlist":[{"cid":"1","name":"margi"},{"cid":"2","name":"steven"}],"productboxtype":[{"pbxid":"1","pbxname":"1 Dozen","qtyperbox":"12"},{"pbxid":"2","pbxname":"2 Dozens","qtyperbox":"24"},{"pbxid":"3","pbxname":"3 Dozens","qtyperbox":"36"}]}

i am able to get names in my first autocomplete and it works fine,

Now issue is suppose user select item "margi" and its cid is 1,so again i am sending request to server and trying to get productnames of 'margi',and its response is

{"status":"success","clientproduct":[{"pid":"4","name":"kangan pair","unitprice":"1500","boxqty":"1","bulkprice":[{"minqty":"10","price":"1500"},{"minqty":"15","price":"1470"},{"minqty":"20","price":"1460"}]}]}

MYActivity.java

public class MainActivity extends Activity {
private AutoCompleteTextView acTextView;
private String catidtemp;
JSONParser jsonParser = new JSONParser();
private AutoCompleteTextView autoproduct;
private static final String FEEDBACK_URL = "";
private static final String FEEDBACK_SUCCESS = "status";
@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    acTextView = (AutoCompleteTextView) findViewById(R.id.autocmplte_clorder_clname);
    acTextView.setAdapter(new SuggestionAdapterClientList(this,acTextView.getText().toString()));

    autoproduct=(AutoCompleteTextView)findViewById(R.id.autocmplte_clorder_product);
    autoproduct.setAdapter(new SuggestionAdapterClientProduct(this, autoproduct.getText().toString()));

    acTextView.setOnItemClickListener(new OnItemClickListener() {



        @Override
        public void onItemClick(AdapterView<?> parent, View view,
                int position, long id) {
            // TODO Auto-generated method stub
            JsonParseClientProduct jp=new JsonParseClientProduct();
              List<SuggestGetSetClientProduct> list1 =jp.getParseJsonWCF(
                                                autoproduct.getText().toString());
              new AttemptLogin(list1.get(position).getId()).execute();
        }
    });

}

  class AttemptLogin extends AsyncTask<String, String, String> {

    boolean failure = false;
    private ProgressDialog pDialog;

    private int selected_cid=1;
    AttemptLogin(int selected_cid){
    this.selected_cid=selected_cid;
    }


    @Override
    protected void onPreExecute() {
        super.onPreExecute();
        pDialog = new ProgressDialog(MainActivity.this);
        pDialog.setMessage("Sending..");
        pDialog.setIndeterminate(true);
      //  pDialog.setIndeterminateDrawable(getResources().getDrawable(R.drawable.custom_progress));
        pDialog.setCancelable(true);
        pDialog.show();
    }

    @SuppressWarnings("unused")
    @Override
    protected String doInBackground(String...args) {
        //Check for success tag
        //int success;
        Looper.prepare();



         try {

             JsonParseClientList jp=new JsonParseClientList();
                List<NameValuePair> params = new ArrayList<NameValuePair>();
             List<SuggestGetSetClientList> list =jp.getParseJsonWCF(acTextView.getText().toString());

                 for(int i = 0;i<list.size();i++)
                 {
                   if(list.get(i).getName().equals(acTextView.getText().toString()))
                   // params.add(new BasicNameValuePair("cid",list.get(i).getId()));

                       params.add(new BasicNameValuePair("cid",selected_cid);

                     //  catid=list.get(i).getId();
                  // catidtemp=list.get(i).getId();


                 }

                 catidtemp=list.get(0).id.toString();
            // catidtemp=list.get(i).getId();
             System.out.println("cattttttiiiiddd????"+catidtemp);
             params.add(new BasicNameValuePair("action", "clientproduct"));

             System.out.println("su gayu server ma????"+params);

             Log.d("request!", "starting");
             // getting product details by making HTTP request
             JSONObject json = jsonParser.makeHttpRequest (
                 FEEDBACK_URL, "POST", params);
             //check your log for json response
             Log.d("Login attempt", json.toString());

             JSONObject jobj = new JSONObject(json.toString());
             final String msg = jobj.getString("msg");




             return json.getString(FEEDBACK_SUCCESS);

         }catch (JSONException e) {
             e.printStackTrace();
         }
         return null;
    }

    // After completing background task Dismiss the progress dialog

    protected void onPostExecute(String file_url) {
        //dismiss the dialog once product deleted
        pDialog.dismiss();

        //parentcat.getText().clear();
}}
  public class SuggestGetSetClientProduct {

        String id,name;
        public SuggestGetSetClientProduct(String id, String name){
            this.setId(id);
            this.setName(name);
        }
        public String getId() {
            return id;
        }

        public void setId(String id) {
            this.id = id;
        }

        public String getName() {
            return name;
        }

        public void setName(String name) {
            this.name = name;
        }
    }

   public class JsonParseClientProduct {


        double current_latitude,current_longitude;
        public JsonParseClientProduct(){}
        public JsonParseClientProduct(double current_latitude,double current_longitude){
            this.current_latitude=current_latitude;
            this.current_longitude=current_longitude;
        }
        public List<SuggestGetSetClientProduct> getParseJsonWCF(String sName)
           {
            List<SuggestGetSetClientProduct> ListData = new ArrayList<SuggestGetSetClientProduct>();
            try {
               String temp=sName.replace(" ", "%20");
               URL js = new URL("");

               System.out.println("what the fuck"+js);
               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("clientproduct");
               for(int i = 0; i < jsonArray.length(); i++){
                   JSONObject r = jsonArray.getJSONObject(i);
                   ListData.add(new SuggestGetSetClientProduct(r.getString("pid"),r.getString("name")));
               }


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

           }
    }
    public class SuggestionAdapterClientProduct extends ArrayAdapter<String>{


        protected static final String TAG = "SuggestionAdapter";
        private List<String> suggestions;
        public SuggestionAdapterClientProduct(Activity context, String nameFilter) {
            super(context, android.R.layout.simple_dropdown_item_1line);
            suggestions = new ArrayList<String>();
        }

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

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

        @Override
        public Filter getFilter() {
            Filter myFilter = new Filter() {
                @Override
                protected FilterResults performFiltering(CharSequence constraint) {
                    FilterResults filterResults = new FilterResults();
                    JsonParseClientProduct jp=new JsonParseClientProduct();
                    if (constraint != null) {
                        // A class that queries a web API, parses the data and
                        // returns an ArrayList<GoEuroGetSet>
                        List<SuggestGetSetClientProduct> new_suggestions =jp.getParseJsonWCF(constraint.toString());
                        suggestions.clear();
                        /*for (int i=0;i<new_suggestions.size();i++) {
                        suggestions.add(new_suggestions.get(i).getName());
                    }*/

                    for (int i=0;i<new_suggestions.size();i++) {
                        String name=new_suggestions.get(i).getName();
                        String id=new_suggestions.get(i).getId();
                        System.out.println("checis id"+id);
                        if(name.contains(constraint)){
                        suggestions.add(new_suggestions.get(i).getName());


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

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

}

issue is here..I am not able to get position of id..

 try {

             JsonParseClientList jp=new JsonParseClientList();
                List<NameValuePair> params = new ArrayList<NameValuePair>();
             List<SuggestGetSetClientList> list =jp.getParseJsonWCF(acTextView.getText().toString());

                 for(int i = 0;i<list.size();i++)
                 {
                   if(list.get(i).getName().equals(acTextView.getText().toString()))
                    params.add(new BasicNameValuePair("cid",list.get(i).getId()));

                     //  catid=list.get(i).getId();

                 }

                 for(int b=0;b<list.size();b++)
                 {
                     catidtemp=list.get(0).id.toString();
                     System.out.println("cattttttiiiiddd????"+catidtemp);
                 }
解决方案

Use list1 for getting selected cid from ListView:

@Override
  public void onItemClick(AdapterView<?> parent, View view,
                int position, long id) {
            // TODO Auto-generated method stub
      JsonParseClientProduct jp=new JsonParseClientProduct();
      List<SuggestGetSetClientProduct> list1 =jp.getParseJsonWCF(
                                        autoproduct.getText().toString());
      new AttemptLogin(list1.get(position).getId()).execute();
}

and create constructor in AttemptLogin class:

class AttemptLogin extends AsyncTask<String, String, String> {

    boolean failure = false;
    private ProgressDialog pDialog;
    private int selected_cid=1;
    AttemptLogin(int selected_cid){
    this.selected_cid=selected_cid;
    }
   //... your code
}

now use selected_cid for to add cid as parameter :

params.add(new BasicNameValuePair("cid",selected_cid);

这篇关于获得autocompletetextview位置的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

09-02 17:36