android - 将 volley 请求的结果使用到 AutocompleteAdapter 中

标签 android autocomplete android-volley

我有一个使用 volley into AutoCompleteAdapter 到服务器的搜索请求,我想将我的请求结果获取到适配器中的结果过滤器中,但在从服务器获取结果之前,将 null 获取到适配器和应用程序中的结果过滤器崩溃,我该如何处理这种情况?谢谢,这是我的代码:

public class AutoCompleteAdapter extends ArrayAdapter<Company> implements Filterable {
private ArrayList<String> mData;

RequestQueue queue;

Context context ;
public AutoCompleteAdapter(Context context, int textViewResourceId) {
    super(context, textViewResourceId);
    mData = new ArrayList<>();
    this.context = context ;
}

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



@Override
public Filter getFilter() {
    Filter myFilter = new Filter() {
        @Override
        protected FilterResults performFiltering(final CharSequence constraint) {
              FilterResults filterResults = new FilterResults();
            if(constraint != null) {


                Log.e("constraint",constraint+"");
                queue = Volley.newRequestQueue(context);
                String url = "http://eteebar.com/api/main/search";
                // Request a string response from the provided URL.

                StringRequest jsonArrayRequest = new StringRequest(Request.Method.POST, url,
                        new Response.Listener<String>() {
                            @Override
                            public void onResponse(String response) {
                                ArrayList<Image> imagesArray;
                                ArrayList<Articles> articlesArray;
                                ArrayList<Comment> commentsArray;
                                ArrayList<Offer> offersArray;

                                try {
                                    ArrayList<String> companies = new ArrayList<>();

                                    JSONArray jsonArray =  new JSONArray(response);
                                    for(int i= 0 ; i < jsonArray.length(); i++){

                                        imagesArray  = new ArrayList<>();
                                        articlesArray  = new ArrayList<>();
                                        commentsArray  = new ArrayList<>();
                                        offersArray  = new ArrayList<>();


                                        JSONObject c = jsonArray.getJSONObject(i);

                                        JSONArray images = c.getJSONArray("images") ;
                                        JSONArray articles = c.getJSONArray("articles") ;
                                        JSONArray comments = c.getJSONArray("comments") ;
                                        JSONArray offers = c.getJSONArray("offers") ;


                                        for(int img = 0 ; img < images.length() ; img ++){

                                            try{
                                                JSONObject im = images.getJSONObject(img);
                                                Image image = new Image(im.getString("id"),im.getString("company_id"),im.getString("link"),
                                                        im.getString("is_deleted"));
                                                imagesArray.add(img,image);
                                            }
                                            catch (JSONException ex){

                                            }
                                        }
                                        for(int art = 0 ; art < articles.length() ; art ++){

                                            try{
                                                JSONObject ar = articles.getJSONObject(art);
                                                Articles article = new Articles(ar.getString("id"),ar.getString("company_id"),ar.getString("link"),ar.getString("subject"),
                                                        ar.getString("description"),ar.getString("is_active"));
                                                articlesArray.add(art,article);
                                            }
                                            catch (JSONException ex){

                                            }
                                        }

                                        for(int com = 0 ; com < comments.length() ; com ++){

                                            try{
                                                JSONObject commen = comments.getJSONObject(com);
                                                Comment comment = new Comment(commen.getString("id"),commen.getString("comment"),commen.getString("company_id"),
                                                        commen.getString("customer_id"),commen.getString("plus_count"),commen.getString("minus_count"),commen.getString("is_active")
                                                        ,commen.getString("is_deleted"),commen.getString("customer_name"));

                                                commentsArray.add(com,comment);
                                            }
                                            catch (JSONException ex){

                                            }
                                        }
                                        for(int off = 0 ; off < offers.length() ; off ++){

                                            try{
                                                JSONObject of = offers.getJSONObject(off);
                                                Offer offer = new Offer(of.getString("id"),of.getString("customer_id"),of.getString("keyfiate_mahsoulat"),
                                                        of.getString("pasokhgouyi"),of.getString("poshtibani"),of.getString("takhassos"),of.getString("tarrahiye_basari"),of.getString("tabliqat"),
                                                        of.getString("tarefeha"),of.getString("qedmat"),of.getString("sorat"),of.getString("standard"),of.getString("peygiri"),
                                                        of.getString("bastebandi"),of.getString("website"),of.getString("amouzesh"),of.getString("berouz_boudan"),of.getString("vosate_brand"),of.getString("vabaste_be_dolat"),
                                                        of.getString("description"),of.getString("description_balance"),of.getString("is_deleted"),of.getString("customer_name"));
                                                offersArray.add(off,offer);
                                            }
                                            catch (JSONException ex){

                                            }
                                        }

                                        Company company = new Company(c.getString("id"),c.getString("customer_id"),c.getString("name"),c.getString("brand"),c.getString("shoar"),c.getString("email"),c.getString("website"),c.getString("employees_count"),c.getString("branchs_count"),
                                                c.getString("tags"),c.getString("customers_count"),c.getString("product_id1"),c.getString("product_id2"),c.getString("product_id3"),c.getString("telegram"),c.getString("instagram"),
                                                c.getString("facebook"),c.getString("linkedin"),c.getString("google"),c.getString("mazaya"),c.getString("goals"),c.getString("description"),c.getString("link"),c.getString("seen_count"),c.getString("comment_balance"),c.getString("fields_balance"),c.getString("customer_balance"),c.getString("etebar_balance"),c.getString("main_balance")
                                                ,c.getString("sharing_count"),c.getString("is_active"),c.getString("is_deleted"),c.getString("created_at_jalali"),c.getString("updated_at_jalali"),c.getString("created_at"),c.getString("updated_at"),c.getString("category_name"),c.getString("customer_name"),c.getString("product_name1"),c.getString("product_name2"),c.getString("product_name3"),imagesArray,articlesArray,commentsArray,offersArray);

                                        companies.add(company.name);

                                    }
                                    Log.e("companySize:",companies.size()+"");
                                    if(companies.size()>0){
                                       FilterResults filter = new FilterResults();
                                       mData = companies ;
                                        Log.e("mData",mData.size()+" " + mData);

                                        filter.values = mData;
                                        filter.count = mData.size();

                                        //    Log.e("filterResult",filterResults.values+"");


                                    }

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

                            }
                        }, new Response.ErrorListener() {
                    @Override
                    public void onErrorResponse(VolleyError error) {
                        Log.e("Volley",error.toString());
                    }
                }) {

                    @Override
                    protected Map<String, String> getParams() throws AuthFailureError {


                        Map<String, String> params = new HashMap<String, String>();

                        Log.e("searchText",constraint.toString());
                        if(constraint.length()>0){
                            params.put("key", constraint.toString());
                        }

                        params.put("offset", "0");
                        params.put("limit","20");

                        return params;
                    }

                };
                jsonArrayRequest.setTag("tag");
                jsonArrayRequest.setRetryPolicy(new DefaultRetryPolicy(
                        400000,
                        DefaultRetryPolicy.DEFAULT_MAX_RETRIES,
                        DefaultRetryPolicy.DEFAULT_BACKOFF_MULT));
                // Add the request to the RequestQueue.
                queue.add(jsonArrayRequest);

                // Now assign the values and count to the FilterResults object

            }
            return filterResults;

        }

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

最佳答案

方法performFiltering()在辅助线程中调用。您再次通过 Volley 进行异步调用。因此,performFiltering() 方法在响应到达之前返回,从而导致崩溃。您所需要做的就是阻止 performFiltering() 直到响应到达。

这可以通过Volley提供的RequestFuture来实现。

queue = Volley.newRequestQueue(context);
String url = "http://eteebar.com/api/main/search";
RequestFuture<String> future = RequestFuture.newFuture();
StringRequest request = new StringRequest(Method.POST, url, reqBody, future, future);
queue.add(request);

try {
    String response = future.get(); // this is a blocking call
    // write your body of onResponse() here
} catch (InterruptedException e) {
} catch (ExecutionException e) {
    // if something went wrong
}

关于android - 将 volley 请求的结果使用到 AutocompleteAdapter 中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45127962/

相关文章:

android - react native 中的 "resource android:attr/fontVariationSettings not found."

android - notifyDataSetChanged() 后焦点丢失

android - 带参数的 Volley GET

java - Jetty - 9 BAD REQUEST ERROR with Volley 服务器

android - LayoutParams 返回 null

javascript - jquery在自动完成选择事件中调用其他自声明函数

Angular 4 : Binding dropdown with huge data set(10000+ records)

python - PyCharm:指定返回变量的类型?

Android Volley 无法为使用 OkHttp3 作为其传输的特定请求禁用缓存

android - 如何在 Android 的 Firebase 身份验证中更改登录的电话号码?