seachview not filtering in recyclerview

笑着哭i 提交于 2019-12-25 00:14:32

问题


I am developing news app and I have implemented search view in recyclerview in fragment on navigation drawer but it is not filtering any news. I have followed following stackoverflow post Implement Searchview with Navigation Drawer and Fragment inside I am calling two ending point first top headlines

below root client class @Module public class SportClient {

private static final String ROOT_URL = "https://newsapi.org";

/**
 * Get Retrofit Instance
 */
private static Retrofit getRetrofitInstance() {
    return new Retrofit.Builder()
            .baseUrl(ROOT_URL)
            .addConverterFactory(GsonConverterFactory.create())
            .build();
}

/**
 * Get API Service
 *
 * @return API Service
 */
@Provides
@ApplicationScope
public static SportInterface getApiService() {
    return getRetrofitInstance().create(SportInterface.class);
}

@Provides
@ApplicationScope
OkHttpClient getOkHttpCleint(HttpLoggingInterceptor httpLoggingInterceptor) {
    return new OkHttpClient.Builder()
            .addInterceptor(httpLoggingInterceptor)
            .build();
}

@Provides
@ApplicationScope
HttpLoggingInterceptor getHttpLoggingInterceptor() {
    HttpLoggingInterceptor httpLoggingInterceptor = new HttpLoggingInterceptor();
    httpLoggingInterceptor.setLevel(HttpLoggingInterceptor.Level.BODY);
    return httpLoggingInterceptor;
}

}

below first ending point

which I am getting top headlines @GET("/v2/top-headlines?sources=bbc-sport&apiKey=d03441ae1be44f9cad8c38a2fa6db215") Call getArticles();

below the second point which I am getting everything @GET("/v2/everything?apiKey=d03441ae1be44f9cad8c38a2fa6db215") Call getSearchViewArticles(@Query("q") String q);

below my articleAdapter where I have implemented recyclerview

public class ArticleAdapter extends RecyclerView.Adapter {

public static final String urlKey = "urlKey";
List<Article> articles;

private ClipboardManager myClipboard;
private ClipData myClip;


public ArticleAdapter(List<Article> articles, SportNews sportNews) {
    this.articles = articles;


}

public ArticleAdapter(ClickListener clickListener) {
}

public ArticleAdapter(List<Article> articleList, Search search) {
}

@NonNull
@Override
public ArticleAdapter.CustomViewHolder onCreateViewHolder(@NonNull ViewGroup viewGroup, int i) {
    View itemView = LayoutInflater.from(viewGroup.getContext()).inflate(R.layout.article_list, null);
    return new ArticleAdapter.CustomViewHolder(itemView);
}

@Override
public void onBindViewHolder(@NonNull edgar.yodgorbek.sportnews.adapter.ArticleAdapter.CustomViewHolder customViewHolder, int position) {
    Article article = articles.get(position);
    SimpleDateFormat input = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSS'Z'");
    SimpleDateFormat output = new SimpleDateFormat("dd/MM/yyyy");

    Date d = new Date();
    try {
        d = input.parse(article.getPublishedAt());
    } catch (ParseException e) {
        e.printStackTrace();
    }


    String formatted = output.format(d);
    customViewHolder.articleTime.setText(formatted);
    customViewHolder.articleAuthor.setText(article.getSource().getName());
    customViewHolder.articleTitle.setText(article.getTitle());
    Picasso.get().load(article.getUrlToImage()).into(customViewHolder.articleImage);
    customViewHolder.itemView.setOnClickListener(v -> {
        Intent intent = new Intent(v.getContext(), DetailActivity.class);

        intent.putExtra("urlKey", article.getUrl());

        v.getContext().startActivity(intent);

    });
    customViewHolder.articleShare.setOnClickListener(v -> {
        Intent sharingIntent = new Intent(android.content.Intent.ACTION_SEND);
        sharingIntent.setType("text/plain");
        String articleDescription = article.getDescription();
        String articleTitle = article.getTitle();
        sharingIntent.putExtra(android.content.Intent.EXTRA_SUBJECT, articleDescription);
        sharingIntent.putExtra(android.content.Intent.EXTRA_TEXT, articleTitle);
        v.getContext().startActivity((Intent.createChooser(sharingIntent, "Share using")));


    });

    customViewHolder.articleFavorite.setOnClickListener(v -> {
        myClipboard = (ClipboardManager) v.getContext().getSystemService(Context.CLIPBOARD_SERVICE);


        myClip = ClipData.newPlainText("label", customViewHolder.articleTitle.getText().toString());
        myClipboard.setPrimaryClip(myClip);
        Toast.makeText(v.getContext(), "Copied to clipboard", Toast.LENGTH_SHORT).show();

    });
}


@Override
public int getItemCount() {
    if (articles == null) return 0;
    return articles.size();
}

public interface ClickListener {
}

public class CustomViewHolder extends RecyclerView.ViewHolder {
    @BindView(R.id.articleAuthor)
    TextView articleAuthor;
    @BindView(R.id.articleTitle)
    TextView articleTitle;
    @BindView(R.id.articleImage)
    ImageView articleImage;
    @BindView(R.id.articleTime)
    TextView articleTime;
    @BindView(R.id.articleShare)
    ImageButton articleShare;
    @BindView(R.id.articleFavorite)
    ImageButton articleFavorite;

    public CustomViewHolder(View view) {
        super(view);
        ButterKnife.bind(this, view);


    }
}

}

below fragment class where I am getting json response public class BBCSportFragment extends Fragment implements ArticleAdapter.ClickListener {

public List<Article> articleList = new ArrayList<>();
@ActivityContext
public Context activityContext;
Search search;
@ApplicationContext
public Context mContext;

@BindView(R.id.recycler_view)
RecyclerView recyclerView;
BBCSportFragmentComponent bbcSportFragmentComponent;
BBCFragmentContextModule bbcFragmentContextModule;
private SportNews sportNews;
private ArticleAdapter articleAdapter;

@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
                         Bundle savedInstanceState) {
    View view = inflater.inflate(R.layout.fragment_bbcsport, container, false);
    ButterKnife.bind(this, view);
    SportInterface sportInterface = SportClient.getApiService();
    Call<SportNews> call = sportInterface.getArticles();
    call.enqueue(new Callback<SportNews>() {
        @Override
        public void onResponse(Call<SportNews> call, Response<SportNews> response) {
            if (response == null) {
                sportNews = response.body();
                if (sportNews != null && sportNews.getArticles() != null) {
                    articleList.addAll(sportNews.getArticles());
                }
                articleAdapter = new ArticleAdapter(articleList, sportNews);
                ApplicationComponent applicationComponent;
                applicationComponent = (ApplicationComponent) MyApplication.get(Objects.requireNonNull(getActivity())).getApplicationContext();
                bbcSportFragmentComponent = (BBCSportFragmentComponent) DaggerApplicationComponent.builder().contextModule(new ContextModule(getContext())).build();
                bbcSportFragmentComponent.injectBBCSportFragment(BBCSportFragment.this);
                RecyclerView.LayoutManager layoutManager = new LinearLayoutManager(getContext(applicationComponent));
                recyclerView.setLayoutManager(layoutManager);
                recyclerView.setAdapter(articleAdapter);
            }
        }

        @Override
        public void onFailure(Call<SportNews> call, Throwable t) {

        }
    });


    SportInterface searchInterface = SportClient.getApiService();
    Call<Search> searchCall = searchInterface.getSearchViewArticles("q");
     searchCall.enqueue(new Callback<Search>() {
         @Override
         public void onResponse(Call<Search> call, Response<Search> response) {
             search = response.body();

             if (search != null && search.getArticles() != null) {
                 articleList.addAll(search.getArticles());
             }

             articleAdapter = new ArticleAdapter(articleList, search);
             RecyclerView.LayoutManager layoutManager = new LinearLayoutManager(getContext());
             recyclerView.setLayoutManager(layoutManager);
             recyclerView.setAdapter(articleAdapter);
         }

         @Override
         public void onFailure(Call<Search> call, Throwable t) {

         }
     });


    return view;


}

private Context getContext(ApplicationComponent applicationComponent) {
    return null;
}

public static void doFilter(String searchQuery) {

}

}

below my MainActivity.java where I have implemetend navigation drawer

public class MainActivity extends AppCompatActivity {
    private DrawerLayout mDrawer;
    private Toolbar toolbar;
    private NavigationView nvDrawer;
    private ActionBarDrawerToggle drawerToggle;
    Context mContext;

    // Default active navigation menu
    int mActiveMenu;

    // TAGS
    public static final int MENU_FIRST = 0;
    public static final int MENU_SECOND = 1;
    public static final int MENU_THIRD = 2;
    public static final int MENU_FOURTH = 3;
    public static final int MENU_FIFTH = 3;
    public static final String TAG = "crash";


    // Action bar search widget
    SearchView searchView;
    String searchQuery = "";


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

        // Set a Toolbar to replace the ActionBar.
        toolbar = (Toolbar) findViewById(R.id.toolbar);
        setSupportActionBar(toolbar);

        // Find our drawer view
        mDrawer = (DrawerLayout) findViewById(R.id.drawer_layout);
        drawerToggle = setupDrawerToggle();

        // Tie DrawerLayout events to the ActionBarToggle
        mDrawer.addDrawerListener(drawerToggle);

        nvDrawer = (NavigationView) findViewById(R.id.nvView);

// Inflate the header view at runtime
        View headerLayout = nvDrawer.inflateHeaderView(R.layout.nav_header);
// We can now look up items within the header if needed
        ImageView ivHeaderPhoto = (ImageView) headerLayout.findViewById((R.id.header_image));
        ivHeaderPhoto.setImageResource(R.drawable.ic_sportnews);
        setupDrawerContent(nvDrawer);
        FragmentManager fragmentManager = getSupportFragmentManager();
        fragmentManager.beginTransaction().replace(R.id.flContent, new BBCSportFragment()).commit();
        fragmentManager.beginTransaction().replace(R.id.flContent, new FoxSportsFragment()).commit();
        fragmentManager.beginTransaction().replace(R.id.flContent, new TalkSportsFragment()).commit();

    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        // The action bar home/up action should open or close the drawer.
        switch (item.getItemId()) {
            case android.R.id.home:
                mDrawer.openDrawer(GravityCompat.START);
                return true;
        }

        return super.onOptionsItemSelected(item);
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        getMenuInflater().inflate(R.menu.menu, menu);

        // Getting search action from action bar and setting up search view
        MenuItem searchItem = menu.findItem(R.id.action_search);
        SearchView searchView = (SearchView) searchItem.getActionView();

        // Setup searchView
        setupSearchView(searchView);
        Log.e(TAG,"crash");
        return true;
    }

    public void setupSearchView(SearchView searchView) {
        SearchManager searchManager = (SearchManager) this.getSystemService(Context.SEARCH_SERVICE);
        if (searchManager != null) {
            SearchableInfo info = searchManager.getSearchableInfo(getComponentName());
            searchView.setSearchableInfo(info);
        }

        searchView.setOnQueryTextListener(new SearchView.OnQueryTextListener() {
            @Override
            public boolean onQueryTextChange(String newText) {
                searchQuery = newText;

                // Load search data on respective fragment
                if (mActiveMenu == MENU_FIRST)   // First
                {
                    BBCSportFragment.doFilter(newText);
                }

                if (mActiveMenu == MENU_SECOND)   // First
                {
                    BBCSportFragment.doFilter(newText);
                }

                if (mActiveMenu == MENU_THIRD)   // First
                {
                    BBCSportFragment.doFilter(newText);
                }

                if (mActiveMenu == MENU_FOURTH)   // First
                {
                    BBCSportFragment.doFilter(newText);
                } else if (mActiveMenu == MENU_FIFTH) // Second
                {
                    ESPNFragment.doFilter(newText);
                }
                return true;
            }

            @Override
            public boolean onQueryTextSubmit(String query) {
                //searchView.clearFocus();
                return false;
            }
        });

        // Handling focus change of search view
        searchView.setOnQueryTextFocusChangeListener(new View.OnFocusChangeListener() {

            @Override
            public void onFocusChange(View v, boolean hasFocus) {

                // Focus changed after pressing back key or pressing done in keyboard
                if (!hasFocus) {
                    searchQuery = "";
                }
            }
        });
    }


    private void setupDrawerContent(NavigationView navigationView) {
        navigationView.setNavigationItemSelectedListener(
                menuItem -> {
                    selectDrawerItem(menuItem);
                    return true;
                });
    }

    public void selectDrawerItem(MenuItem menuItem) {
        // Create a new fragment and specify the fragment to show based on nav item clicked
        Fragment fragment = null;
        Class fragmentClass = null;
        switch (menuItem.getItemId()) {
            case R.id.bbcsports_fragment:
                fragmentClass = BBCSportFragment.class;
                break;
            case R.id.talksports_fragment:
                fragmentClass = TalkSportsFragment.class;
                break;
            case R.id.foxsports_fragment:
                fragmentClass = FoxSportsFragment.class;
                break;

            case R.id.footballitalia_fragment:
                fragmentClass = FootballItaliaFragment.class;
                break;

            case R.id.espn_fragment:
                fragmentClass = ESPNFragment.class;
                break;

            default:

        }

        try {
            fragment = (Fragment) fragmentClass.newInstance();
        } catch (Exception e) {
            e.printStackTrace();
        }

        // Insert the fragment by replacing any existing fragment

        FragmentManager fragmentManager = getSupportFragmentManager();
        fragmentManager.beginTransaction().replace(R.id.flContent, fragment).commit();
        // Highlight the selected item has been done by NavigationView
        menuItem.setChecked(true);
        // Set action bar title
        setTitle(menuItem.getTitle());
        // Close the navigation drawer
        mDrawer.closeDrawers();
    }

    private ActionBarDrawerToggle setupDrawerToggle() {
        // NOTE: Make sure you pass in a valid toolbar reference.  ActionBarDrawToggle() does not require it
        // and will not render the hamburger icon without it.
        return new ActionBarDrawerToggle(this, mDrawer, toolbar, R.string.drawer_open, R.string.drawer_close);
    }


    @Override
    protected void onPostCreate(Bundle savedInstanceState) {
        super.onPostCreate(savedInstanceState);
        // Sync the toggle state after onRestoreInstanceState has occurred.
        drawerToggle.syncState();
    }

    @Override
    public void onConfigurationChanged(Configuration newConfig) {
        super.onConfigurationChanged(newConfig);
        // Pass any configuration change to the drawer toggles
        drawerToggle.onConfigurationChanged(newConfig);
    }


}

below main.xml

<?xml version="1.0" encoding="utf-8"?>
<menu xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto">
    <item
        android:id="@+id/action_search"
        android:icon="@drawable/ic_search_white"
        android:title="@string/search_hint"
        app:showAsAction="collapseActionView|ifRoom"
        app:actionViewClass="android.support.v7.widget.SearchView" />
</menu>

来源:https://stackoverflow.com/questions/56406808/seachview-not-filtering-in-recyclerview

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!