2016-05-16 9 views
0

custom adapterを作成し、web APIからデータを読み込むことができますが、提案はドロップダウンに表示されません。私は私のカスタムは、これはこれはのためxmlファイルである私のカスタムAdapterカスタムAPIを使用してAutoCompleteTextViewのWeb APIからデータを取得する

public class SearchAdapter extends BaseAdapter implements Filterable { 

    private static final int MAX_RESULTS = 10; 
    private Context mContext; 
    private List<User> resultList = new ArrayList<User>(); 

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

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

    @Override 
    public User getItem(int index) { 
     return resultList.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.search_results, parent, false); 
     } 
     ((TextView) convertView.findViewById(R.id.user_name)).setText(getItem(position).getName()); 
     ((TextView) convertView.findViewById(R.id.user_phone)).setText(getItem(position).getPhone()); 
     return convertView; 
    } 

    @Override 
    public Filter getFilter() { 
     Filter filter = new Filter() { 
      @Override 
      protected FilterResults performFiltering(CharSequence constraint) { 
       FilterResults filterResults = new FilterResults(); 
       if (constraint != null) { 
        List<User> users = findUsers(mContext, constraint.toString()); 

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

      @Override 
      protected void publishResults(CharSequence constraint, FilterResults results) { 
       if (results != null && results.count > 0) { 
        resultList = (List<User>) results.values; 
        notifyDataSetChanged(); 
       } else { 
        notifyDataSetInvalidated(); 
       } 
      }}; 
     return filter; 
    } 

    /** 
    * Returns a search result for the given book title. 
    */ 
    private List<User> findUsers(Context context, String query) { 
     // GoogleBooksProtocol is a wrapper for the Google Books API 
     SearchUser request = new SearchUser(context); 
     return request.sendRequest(query); 
    } 

} 

あるAutoCompleteTextView

public class AutoCompleteDelay extends AutoCompleteTextView { 

    private static final int MESSAGE_TEXT_CHANGED = 100; 
    private static final int DEFAULT_AUTOCOMPLETE_DELAY = 750; 

    private int mAutoCompleteDelay = DEFAULT_AUTOCOMPLETE_DELAY; 
    private ProgressBar mLoadingIndicator; 

    private final Handler mHandler = new Handler() { 
     @Override 
     public void handleMessage(Message msg) { 
      AutoCompleteDelay.super.performFiltering((CharSequence) msg.obj, msg.arg1); 
     } 
    }; 

    public AutoCompleteDelay(Context context, AttributeSet attrs) { 
     super(context, attrs); 
    } 

    public void setLoadingIndicator(ProgressBar progressBar) { 
     mLoadingIndicator = progressBar; 
    } 

    public void setAutoCompleteDelay(int autoCompleteDelay) { 
     mAutoCompleteDelay = autoCompleteDelay; 
    } 

    @Override 
    protected void performFiltering(CharSequence text, int keyCode) { 
     if (mLoadingIndicator != null) { 
      mLoadingIndicator.setVisibility(View.VISIBLE); 
     } 
     mHandler.removeMessages(MESSAGE_TEXT_CHANGED); 
     mHandler.sendMessageDelayed(mHandler.obtainMessage(MESSAGE_TEXT_CHANGED, text), mAutoCompleteDelay); 
    } 

    @Override 
    public void onFilterComplete(int count) { 
     if (mLoadingIndicator != null) { 
      mLoadingIndicator.setVisibility(View.GONE); 
     } 
     super.onFilterComplete(count); 
    } 
} 

です。ここ

http://makovkastar.github.io/blog/2014/04/12/android-autocompletetextview-with-suggestions-from-a-web-service/

でチュートリアルを追いました

<?xml version="1.0" encoding="utf-8"?> 
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" 
    android:layout_width="match_parent" 
    android:layout_height="match_parent" 
    android:padding="16dp" 
    android:orientation="vertical"> 

    <TextView 
     android:id="@+id/user_name" 
     android:layout_width="match_parent" 
     android:layout_height="wrap_content" 
     android:text="Name" 
     android:textSize="18dp" 
     android:textIsSelectable="false" 
     android:layout_marginBottom="4dp" 
     android:textColor="@color/abc_background_cache_hint_selector_material_dark" /> 

    <TextView 
     android:id="@+id/user_phone" 
     android:layout_width="match_parent" 
     android:layout_height="wrap_content" 
     android:text="0000000000" 
     android:textSize="16dp" 
     android:textIsSelectable="false" 
     android:layout_marginBottom="4dp" 
     android:textColor="@color/switch_thumb_disabled_material_dark" /> 

</LinearLayout> 

これは私がAutoCompleteTextView`

<?xml version="1.0" encoding="utf-8"?> 
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" 
    android:layout_width="match_parent" 
    android:layout_height="match_parent" 
    android:orientation="vertical" 
    android:padding="16dp"> 

    <TextView 
     android:id="@+id/error_text" 
     android:layout_width="match_parent" 
     android:layout_height="wrap_content" 
     android:text="User already exists" 
     android:visibility="gone" 
     android:textStyle="bold" 
     android:textColor="@color/design_textinput_error_color_light" 
     android:singleLine="true" 
     android:layout_marginTop="8dp" 
     android:layout_marginBottom="8dp" /> 

    <RelativeLayout 
     android:layout_width="match_parent" 
     android:layout_height="wrap_content"> 

     <android.support.design.widget.TextInputLayout 
      android:layout_width="match_parent" 
      android:layout_height="wrap_content"> 

      <com.example.krazz.futsaladmin.classes.AutoCompleteDelay 
       android:id="@+id/query" 
       android:layout_width="match_parent" 
       android:layout_height="wrap_content" 
       android:imeOptions="actionNext" 
       android:inputType="textAutoComplete"></com.example.krazz.futsaladmin.classes.AutoCompleteDelay> 

     </android.support.design.widget.TextInputLayout> 

     <ProgressBar 
      android:id="@+id/pb_loading_indicator" 
      style="?android:attr/progressBarStyleSmall" 
      android:layout_width="wrap_content" 
      android:layout_height="wrap_content" 
      android:layout_alignParentRight="true" 
      android:layout_centerVertical="true" 
      android:visibility="gone" /> 

    </RelativeLayout> 

</LinearLayout> 

これはArrayList<User>

public ArrayList<User> sendRequest(final String query) { 

     RequestQueue requestQueue = VolleySingleton.getsInstance().getmRequestQueue(); 

     //mErrorText.setVisibility(View.GONE); 

     String url = String.format(AppConfig.URL_SEARCH_USERS, query, AppConfig.APP_KEY, 4); 
     debug.L(url); 

     StringRequest strReq = new StringRequest(Request.Method.GET, url, new Response.Listener<String>() { 
      @Override 
      public void onResponse(String response) { 

       try { 
        debug.L(response.toString()); 
        JSONObject jObj = new JSONObject(response); 
        JSONArray jsonArray = jObj.getJSONArray("results"); 

        if(jsonArray != null){ 
         for(int i=0; i<jsonArray.length(); i++){ 
          JSONObject currentUser = jsonArray.getJSONObject(i); 

          int id = currentUser.getInt("id"); 
          String name = currentUser.getString("name"); 
          String phone = currentUser.getString("phone"); 
          User users = new User(id, name, phone); 
          searchArrayList.add(users); 
         } 
        } 
        else{ 
         /*mErrorText.setText("Users not found."); 
         mErrorText.setVisibility(View.VISIBLE);*/ 
         debug.L("users not found"); 
        } 
       } catch (JSONException e) { 
        /*mErrorText.setText(e.getMessage()); 
        mErrorText.setVisibility(View.VISIBLE);*/ 
        debug.L(e.toString()); 
       } 

      } 
     }, new Response.ErrorListener() { 
      @Override 
      public void onErrorResponse(VolleyError error) { 
       /*mErrorText.setText(R.string.error_try_again); 
       mErrorText.setVisibility(View.VISIBLE);*/ 
       debug.L(error.toString()); 
      } 
     }); 

     requestQueue.add(strReq); 
     return searchArrayList; 
    } 

を返し、最終的にここに私はを使用していますところである方法である」を使用していますxmlファイルですAutoCompleteTextView

mQueryInputView = (AutoCompleteDelay) view.findViewById(R.id.query); 
     mErrorText = (TextView) view.findViewById(R.id.error_text); 

     mQueryInputView.setThreshold(THRESHOLD); 
     mQueryInputView.setAdapter(new SearchAdapter(mContext)); 
     mQueryInputView.setLoadingIndicator((ProgressBar) view.findViewById(R.id.pb_loading_indicator)); 
     mQueryInputView.setOnItemClickListener(new AdapterView.OnItemClickListener() { 
      @Override 
      public void onItemClick(AdapterView<?> adapterView, View view, int position, long id) { 
       User book = (User) adapterView.getItemAtPosition(position); 
       mQueryInputView.setText(book.getPhone()); 
      } 
     }); 

APIが値を返しても、ドロップダウン候補リストが表示されません。エラーはありません。私は間違って何をしていますか?

答えて

0

問題は、空のArrayListを返すことです。

Volley Queにリクエストを追加すると、リクエストは別のスレッドで実行され、サーバーが応答するたびにデータが返されます。それは時間がかかるでしょう。 しかし、あなたは正確にQueの

あなたは何をすべき
requestQueue.add(strReq); 
return searchArrayList; 

に要求を追加した後、配列のリストを返すされています。また、あなたのSearchAdapterのコンストラクタを変更してみてください

if(jsonArray != null){ 
     for(int i=0; i<jsonArray.length(); i++){ 
      ... 
      searchArrayList.add(users); 
     } 
    // RENEW YOUR ADAPTER HERE OR ASSIGN IT AGAIN TO THE EDITTEXT 
    mAdapter.notifydataSetChanged(); 
    } 

。私は、フラグメントアダプタと同様の問題があった後は:私は `searchAdapter.updateAdapter(searchArrayList)を加え

private List<User> resultList = new ArrayList<User>(); 

public SearchAdapter(Context context,List<User> data) { 
    mContext = context; 
    resultList = data; 
} 
+0

大丈夫、応答がサーバから受信された後に'。 'updateAdapter()'には 'searchArrayList = arraylist;があります。 this.notifyDataSetChanged(); '。しかし、まだドロップダウンリストが表示されていません。これで私を助けてください。 –

+0

try searchAdapter.updateAdapter(searchArrayList); runOnUiThreadで多分それは問題を解決するでしょう。また、あなたのupdateAdapter関数には、この 'resultList = searchArrayList'が必要です! @LalitThapa –

+0

あなたは@Smartizに言ったことをやったが、まだドロップダウンリストを取得していません。 –

関連する問題