过滤的Spannable文本在我的情况下不起作用

时间:2016-11-14 05:05:34

标签: android android-recyclerview spannable

您好我已按照此链接How to highlight filtered text in RecyclerView when using SearchView widget在recyclerview中制作自定义过滤列表。但它对我的情况不起作用,我的代码有什么问题?如果你能看起来和帮助我,我真的会感到骄傲。

感谢SaravInfern关注我的案例,过滤是成功但不改变颜色

这是我的适配器:

public class TanamanAdapter extends RecyclerView.Adapter<DaftarTanamanVH>{
private List<Tanaman> mTanaman;
private ImageLoader imageLoader;
private Context context;
String searchText = "";

public TanamanAdapter(List<Tanaman> mTanaman, Context context){
    this.mTanaman = mTanaman;
    this.context = context;
}

@Override
public DaftarTanamanVH onCreateViewHolder(ViewGroup parent, int viewType) {
    View v = LayoutInflater.from(parent.getContext()).inflate(R.layout.list_tanaman,parent,false);
    return new DaftarTanamanVH(v);
}

@Override
public void onBindViewHolder(DaftarTanamanVH holder, int position) {
    final Tanaman tanaman = mTanaman.get(position);
    String namaTanaman = tanaman.getNama_tanaman();
    String namaIlmiah = tanaman.getNama_ilmiah();
    String urlGambar = tanaman.getUrlGambar();


    imageLoader = CustomVolleyRequest.getInstance(context).getImageLoader();
    imageLoader.get(urlGambar,ImageLoader.getImageListener(holder.networkImageView,R.mipmap.ic_launcher,android.R.drawable.ic_dialog_alert));

    //holder.bind(tanaman);
    holder.tv_nama_tanaman.setText(namaTanaman);
    holder.networkImageView.setImageUrl(urlGambar,imageLoader);

    if(searchText.length() > 0){
        int index = namaIlmiah.indexOf(searchText);
        while(index > 0){
            SpannableStringBuilder sb = new SpannableStringBuilder(namaIlmiah);
            ForegroundColorSpan fcs = new ForegroundColorSpan(Color.BLUE);
            sb.setSpan(fcs,index,searchText.length(),Spanned.SPAN_INCLUSIVE_EXCLUSIVE);
            index = namaIlmiah.indexOf(searchText,index+1);
            holder.tv_nama_ilmiah.setText(sb);
        }
    }else{
        holder.tv_nama_ilmiah.setText(namaIlmiah);
    }


    /*
    holder.cardView.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            Intent intent = new Intent(v.getContext(), DetailTanaman.class);
            intent.putExtra("KEY_ID",tanaman.getId_tanaman());
            intent.putExtra("KEY_NAMA",tanaman.getNama_tanaman());
            intent.putExtra("KEY_ILMIAH",tanaman.getNama_ilmiah());
            intent.putExtra("KEY_GAMBAR",tanaman.getUrlGambar());
            v.getContext().startActivity(intent);
        }
    });*/

}

@Override
public int getItemCount() {
    return mTanaman.size();
}

public void setFilter(List<Tanaman> tanamanList, String searchText){
    mTanaman = new ArrayList<>();
    mTanaman.addAll(tanamanList);
    this.searchText = searchText;
    notifyDataSetChanged();
}

}

这是我的活动:

public class DaftarTanaman extends AppCompatActivity implements SearchView.OnQueryTextListener{

private RecyclerView recyclerView;
private List<Tanaman> mTanaman;
private TanamanAdapter tanamanAdapter;


@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_daftar_tanaman);

    Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
    setSupportActionBar(toolbar);
    ActionBar actionBar = getSupportActionBar();
    actionBar.setDisplayHomeAsUpEnabled(true);


    recyclerView = (RecyclerView) findViewById(R.id.rv_daftar_tanaman);
    LinearLayoutManager layoutManager = new LinearLayoutManager(this);
    recyclerView.setLayoutManager(layoutManager);

    mTanaman = new ArrayList<>();

    getDataTanaman();
}


private void getDataTanaman() {
    final ProgressDialog loading = ProgressDialog.show(this,"Mohon tunggu ...","Sedang mengambil data...",false,false);

    JsonArrayRequest jsonArrayRequest = new JsonArrayRequest(ConfigTanaman.DATA_URL_TANAMAN, new Response.Listener<JSONArray>() {
        @Override
        public void onResponse(JSONArray jsonArray) {
            loading.dismiss();
            parseData(jsonArray);
        }
    }, new Response.ErrorListener() {
        @Override
        public void onErrorResponse(VolleyError volleyError) {

        }
    });
    RequestQueue requestQueue = Volley.newRequestQueue(this);
    requestQueue.add(jsonArrayRequest);
}

private void parseData(JSONArray jsonArray) {
    for(int i=0;i<jsonArray.length();i++){
        Tanaman tanaman = new Tanaman();
        JSONObject jsonObject = null;
        try{
            jsonObject = jsonArray.getJSONObject(i);
            tanaman.setId_tanaman(jsonObject.getString(ConfigTanaman.TAG_ID));
            tanaman.setNama_tanaman(jsonObject.getString(ConfigTanaman.TAG_NAMA));
            tanaman.setNama_ilmiah(jsonObject.getString(ConfigTanaman.TAG_ILMIAH));
            tanaman.setUrlGambar(jsonObject.getString(ConfigTanaman.TAG_URL_GAMBAR));
        }catch(JSONException e){
            e.printStackTrace();
        }
        mTanaman.add(tanaman);
    }
    tanamanAdapter = new TanamanAdapter(mTanaman,this);
    recyclerView.setAdapter(tanamanAdapter);
}

@Override
public boolean onQueryTextSubmit(String query) {
    final List<Tanaman> filteredTanaman = filter(mTanaman,query);
    tanamanAdapter.setFilter(filteredTanaman,query);
    if(filteredTanaman.size() == 0){
        Toast.makeText(DaftarTanaman.this, "Maaf, data dengan kata kunci "+query+" tidak ditemukan", Toast.LENGTH_SHORT).show();
        return false;
    }
    return true;
}

private List<Tanaman> filter(List<Tanaman> models, String query) {
    query = query.toLowerCase();
    final List<Tanaman> filteredTanaman = new ArrayList<>();
    KMP kmp = new KMP();
    for(Tanaman model: models){
        final String source = model.getNama_tanaman().toLowerCase();
        int pos = kmp.postMatch(source,query);
        if(pos != -1){
            filteredTanaman.add(model);
        }
    }
    return filteredTanaman;
}


@Override
public boolean onQueryTextChange(String newText) {
    return false;
}

@Override
public boolean onCreateOptionsMenu(Menu menu) {
    MenuInflater inflater = getMenuInflater();
    inflater.inflate(R.menu.menu_main,menu);
    final MenuItem item = menu.findItem(R.id.action_search);
    final SearchView searchView = (SearchView) MenuItemCompat.getActionView(item);
    searchView.setOnQueryTextListener(this);

    MenuItemCompat.setOnActionExpandListener(item, new MenuItemCompat.OnActionExpandListener() {
        @Override
        public boolean onMenuItemActionExpand(MenuItem item) {
            return true;
        }

        @Override
        public boolean onMenuItemActionCollapse(MenuItem item) {
            tanamanAdapter.setFilter(mTanaman,"");
            return true;
        }
    });
    return super.onCreateOptionsMenu(menu);
}
}

这是显示错误的日志猫:

FATAL EXCEPTION: main
                                                                             Process: id.tanamanobat.skripsi.qori.ensiklopeditanamanobat, PID: 2927
                                                                                              java.lang.NullPointerException: Attempt to invoke virtual method 'int java.lang.String.length()' on a null object reference
                                                                                                  at id.tanamanobat.skripsi.qori.ensiklopeditanamanobat.Adapter.TanamanAdapter.onBindViewHolder(TanamanAdapter.java:67)
                                                                                                  at id.tanamanobat.skripsi.qori.ensiklopeditanamanobat.Adapter.TanamanAdapter.onBindViewHolder(TanamanAdapter.java:35)
                                                                                                  at android.support.v7.widget.RecyclerView$Adapter.onBindViewHolder(RecyclerView.java:5471)
                                                                                                  at android.support.v7.widget.RecyclerView$Adapter.bindViewHolder(RecyclerView.java:5504)
                                                                                                  at android.support.v7.widget.RecyclerView$Recycler.getViewForPosition(RecyclerView.java:4741)
                                                                                                  at android.support.v7.widget.RecyclerView$Recycler.getViewForPosition(RecyclerView.java:4617)
                                                                                                  at android.support.v7.widget.LinearLayoutManager$LayoutState.next(LinearLayoutManager.java:1994)
                                                                                                  at android.support.v7.widget.LinearLayoutManager.layoutChunk(LinearLayoutManager.java:1390)
                                                                                                  at android.support.v7.widget.LinearLayoutManager.fill(LinearLayoutManager.java:1353)
                                                                                                  at android.support.v7.widget.LinearLayoutManager.onLayoutChildren(LinearLayoutManager.java:574)
                                                                                                  at android.support.v7.widget.RecyclerView.dispatchLayoutStep2(RecyclerView.java:3028)
                                                                                                  at android.support.v7.widget.RecyclerView.dispatchLayout(RecyclerView.java:2906)
                                                                                                  at android.support.v7.widget.RecyclerView.onLayout(RecyclerView.java:3283)
                                                                                                  at android.view.View.layout(View.java:15596)
                                                                                                  at android.view.ViewGroup.layout(ViewGroup.java:4966)
                                                                                                  at android.widget.RelativeLayout.onLayout(RelativeLayout.java:1076)
                                                                                                  at android.view.View.layout(View.java:15596)
                                                                                                  at android.view.ViewGroup.layout(ViewGroup.java:4966)
                                                                                                  at android.widget.FrameLayout.layoutChildren(FrameLayout.java:573)
                                                                                                  at android.widget.FrameLayout.onLayout(FrameLayout.java:508)
                                                                                                  at android.view.View.layout(View.java:15596)
                                                                                                  at android.view.ViewGroup.layout(ViewGroup.java:4966)
                                                                                                  at android.widget.LinearLayout.setChildFrame(LinearLayout.java:1703)
                                                                                                  at android.widget.LinearLayout.layoutVertical(LinearLayout.java:1557)
                                                                                                  at android.widget.LinearLayout.onLayout(LinearLayout.java:1466)
                                                                                                  at android.view.View.layout(View.java:15596)
                                                                                                  at android.view.ViewGroup.layout(ViewGroup.java:4966)
                                                                                                  at android.widget.FrameLayout.layoutChildren(FrameLayout.java:573)
                                                                                                  at android.widget.FrameLayout.onLayout(FrameLayout.java:508)
                                                                                                  at android.view.View.layout(View.java:15596)
                                                                                                  at android.view.ViewGroup.layout(ViewGroup.java:4966)
                                                                                                  at android.widget.LinearLayout.setChildFrame(LinearLayout.java:1703)
                                                                                                  at android.widget.LinearLayout.layoutVertical(LinearLayout.java:1557)
                                                                                                  at android.widget.LinearLayout.onLayout(LinearLayout.java:1466)
                                                                                                  at android.view.View.layout(View.java:15596)
                                                                                                  at android.view.ViewGroup.layout(ViewGroup.java:4966)
                                                                                                  at android.widget.FrameLayout.layoutChildren(FrameLayout.java:573)
                                                                                                  at android.widget.FrameLayout.onLayout(FrameLayout.java:508)
                                                                                                  at android.view.View.layout(View.java:15596)
                                                                                                  at android.view.ViewGroup.layout(ViewGroup.java:4966)
                                                                                                  at android.view.ViewRootImpl.performLayout(ViewRootImpl.java:2072)
                                                                                                  at android.view.ViewRootImpl.performTraversals(ViewRootImpl.java:1829)
                                                                                                  at android.view.ViewRootImpl.doTraversal(ViewRootImpl.java:1054)
                                                                                                  at android.view.ViewRootImpl$TraversalRunnable.run(ViewRootImpl.java:5779)
                                                                                                  at android.view.Choreographer$CallbackRecord.run(Choreographer.java:767)
                                                                                                  at android.view.Choreographer.doCallbacks(Choreographer.java:580)
                                                                                                  at android.view.Choreographer.doFrame(Choreographer.java:550)
                                                                                                  at android.view.Choreographer$FrameDisplayEventReceiver.run(Choreographer.java:753)
                                                                                                  at android.os.Handler.handleCallback(Handler.java:739)
                                                                                                  at android.os.Handler.dispatchMessage(Handler.java:95)
                                                                                                  at android.os.Looper.loop(Looper.java:135)
                                                                                                  at android.app.ActivityThread.main(ActivityThread.java:5221)
                                                                                                  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:899)
                                                                                                at com.android.internal.os.ZygoteInit.main(ZygoteInit.jav

以下是截图:

filtered text is not change

2 个答案:

答案 0 :(得分:0)

错误Attempt to invoke virtual method 'int java.lang.String.length()' on a null object reference我可以说,当您创建适配器时,searchText为空,您在调用setFilter时将值存储在其中,因此最简单的解决方案是为您的searchText

指定空白值
String searchText = "";

答案 1 :(得分:0)

您必须像这样String searchText = "";初始化searchText或进行空检查

if(searchText.length() > 0 && searchText!=null){
        int index = namaIlmiah.indexOf(searchText);
        while(index > 0){
            SpannableStringBuilder sb = new SpannableStringBuilder(namaIlmiah);
            ForegroundColorSpan fcs = new ForegroundColorSpan(Color.BLUE);
            sb.setSpan(fcs,index,searchText.length(),Spanned.SPAN_INCLUSIVE_EXCLUSIVE);
            index = namaIlmiah.indexOf(searchText,index+1);
            holder.tv_nama_ilmiah.setText(sb);
        }
    }else{
        holder.tv_nama_ilmiah.setText(namaIlmiah);
    }