Android: Add searchView on the Action Bar - java

My Complete Project Is As Follows: There is a listView connnected to database and a search option with suggestion. I wanna shift this search bar to the action bar and format it just like Google Play Store Search bar. Please help me, my complete codes are:
MainActivity.java
package com.GurbaniAndSikh.MahaanKosh;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.DefaultItemAnimator;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.support.v7.widget.SearchView;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.LinkedHashMap;
import java.util.Map;
/*
* Created by GurbaniAndSikh
*/
public class DictionaryMainActivity extends AppCompatActivity {
private static RecyclerView.Adapter adapter;
private RecyclerView.LayoutManager layoutManager;
private static RecyclerView recyclerView;
public static ArrayList<DictObjectModel> data;
DatabaseHelper db ;
ArrayList<String> wordcombimelist;
ArrayList<String> meancombimelist;
LinkedHashMap<String,String> namelist;
SearchView searchView;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
recyclerView = (RecyclerView) findViewById(R.id.my_recycler_view);
recyclerView.setHasFixedSize(true);
db= new DatabaseHelper(this);
searchView = (SearchView) findViewById(R.id.searchView);
searchView.setQueryHint("Search Here");
searchView.setQueryRefinementEnabled(true);
layoutManager = new LinearLayoutManager(this);
recyclerView.setLayoutManager(layoutManager);
recyclerView.setItemAnimator(new DefaultItemAnimator());
data = new ArrayList<DictObjectModel>();
fetchData();
searchView.setOnQueryTextListener(new SearchView.OnQueryTextListener() {
#Override
public boolean onQueryTextSubmit(String query) {return false; }
#Override
public boolean onQueryTextChange(String newText) {
newText = newText.toLowerCase();
final ArrayList<DictObjectModel> filteredList = new ArrayList<DictObjectModel>();
for (int i = 0; i < wordcombimelist.size(); i++) {
final String text = wordcombimelist.get(i).toLowerCase();
if (text.contains(newText)) {
filteredList.add(new DictObjectModel(wordcombimelist.get(i),meancombimelist.get(i)));
}
}
adapter = new CustomAdapter(filteredList);
recyclerView.setAdapter(adapter);
return true;
}
});
}
public void fetchData()
{
db =new DatabaseHelper(this);
try {
db.createDataBase();
db.openDataBase();
}
catch (Exception e)
{
e.printStackTrace();
}
namelist=new LinkedHashMap<>();
int ii;
SQLiteDatabase sd = db.getReadableDatabase();
Cursor cursor = sd.query("Dictionary1" ,null, null, null, null, null, null);
ii=cursor.getColumnIndex("word");
wordcombimelist=new ArrayList<String>();
meancombimelist= new ArrayList<String>();
while (cursor.moveToNext()){
namelist.put(cursor.getString(ii), cursor.getString(cursor.getColumnIndex("definition")));
}
Iterator entries = namelist.entrySet().iterator();
while (entries.hasNext()) {
Map.Entry thisEntry = (Map.Entry) entries.next();
wordcombimelist.add(String.valueOf(thisEntry.getKey()));
meancombimelist.add("- "+String.valueOf(thisEntry.getValue()));
}
for (int i = 0; i < wordcombimelist.size(); i++) {
data.add(new DictObjectModel(wordcombimelist.get(i), meancombimelist.get(i)));
}
adapter = new CustomAdapter(data);
recyclerView.setAdapter(adapter);
}
}
I use these codes to add searchView to action bar but getfilter() doesn't work.
#Override
public boolean onCreateOptionsMenu(Menu menu) {
MenuInflater inflater = getMenuInflater();
inflater.inflate(R.menu.menu_search, menu);
MenuItem item = menu.findItem(R.id.menuSearch);
SearchView searchView = (SearchView)item.getActionView();
searchView.setOnQueryTextListener(new SearchView.OnQueryTextListener() {
#Override
public boolean onQueryTextSubmit(String query) {
return false;
}
#Override
public boolean onQueryTextChange(String newText) {
adapter.getFilter().filter(newText);
return false;
}
});
return super.onCreateOptionsMenu(menu);
}
Please Tell Me How I Approach To My Target Please Help Me

Create a search view in option menu then use it by overriding onCreateOptionsMenu() programmatically.
<menu xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
tools:context=".MainActivity">
<item
android:id="#+id/action_search"
android:icon="#android:drawable/ic_menu_search"
app:showAsAction="always"
app:actionViewClass="android.support.v7.widget.SearchView"
android:title="Search"/>
</menu>
Later in Activity class,
#Override
public boolean onCreateOptionsMenu( Menu menu) {
getMenuInflater().inflate( R.menu.menu_main, menu);
MenuItem myActionMenuItem = menu.findItem( R.id.action_search);
final SearchView searchView = (SearchView) myActionMenuItem.getActionView();
searchView.setOnQueryTextListener(new SearchView.OnQueryTextListener() {
#Override
public boolean onQueryTextSubmit(String query) {
return false;
}
#Override
public boolean onQueryTextChange(String newText) {
if (TextUtils.isEmpty(newText)) {
adapter.filter("");
listView.clearTextFilter();
} else {
adapter.filter(newText);
}
return true;
}
});
return true;
}

Related

Can't resolve method .getFilter()

I can't seem to find what is the issue with my Adapter that I can't use .getFilter() method on OnQueryTextChange. I called my adapter called mAdapter and there's no method for .getFilter(). I believe that there is some issue with my Adapter but I have spent quite awhile to figure it out.
Here is my Adapter
package Adapters;
import android.com.example.weddingappfinale.MuaView;
import android.com.example.weddingappfinale.R;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Filter;
import android.widget.Filterable;
import android.widget.ImageButton;
import android.widget.TextView;
import androidx.annotation.NonNull;
import androidx.recyclerview.widget.RecyclerView;
import java.util.ArrayList;
import java.util.List;
public class MuaAdapter extends RecyclerView.Adapter<MuaAdapter.MuaViewHolder> implements Filterable {
private List<MuaView> mMuaView;
private List<MuaView> mMuaViewFull;
public static class MuaViewHolder extends RecyclerView.ViewHolder {
public ImageButton mImageButton;
public TextView mTextView1;
public MuaViewHolder(#NonNull View itemView) {
super(itemView);
mImageButton = itemView.findViewById(R.id.mua_imageButton);
mTextView1 = itemView.findViewById(R.id.mua_title);
}
}
public MuaAdapter(List<MuaView> muaView) {
this.mMuaView = muaView;
mMuaViewFull = new ArrayList<>(muaView);
}
#NonNull
#Override
public MuaViewHolder onCreateViewHolder(#NonNull ViewGroup parent, int viewType) {
View v = LayoutInflater.from(parent.getContext()).inflate(R.layout.mua_view, parent, false);
MuaViewHolder mvh = new MuaViewHolder(v);
return mvh;
}
#Override
public void onBindViewHolder(#NonNull MuaViewHolder holder, int position) {
MuaView currentView = mMuaView.get(position);
holder.mImageButton.setImageResource(currentView.getImageResource());
holder.mTextView1.setText(currentView.getText1());
}
#Override
public int getItemCount() {
return mMuaView.size();
}
#Override
public Filter getFilter() {
return MuaFilter;
}
private Filter MuaFilter = new Filter() {
#Override
protected FilterResults performFiltering(CharSequence constraint) {
List<MuaView> filteredList = new ArrayList<>();
if (constraint == null || constraint.length() == 0) {
filteredList.addAll(mMuaViewFull);
} else {
String filterPattern = constraint.toString().toLowerCase().trim();
for (MuaView item : mMuaViewFull) {
if (item.getText1().toLowerCase().contains(filterPattern)) {
filteredList.add(item);
}
}
}
FilterResults results = new FilterResults();
results.values = filteredList;
return results;
}
#Override
protected void publishResults(CharSequence constraint, FilterResults results) {
mMuaView.clear();
mMuaView.addAll((ArrayList) results.values);
notifyDataSetChanged();
}
};
}
Here is my Activity
package android.com.example.weddingappfinale;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.inputmethod.EditorInfo;
import androidx.appcompat.app.AppCompatActivity;
import androidx.appcompat.widget.SearchView;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import java.util.ArrayList;
import Adapters.MuaAdapter;
public class MuaActivity extends AppCompatActivity {
private RecyclerView mRecyclerView;
private RecyclerView.Adapter mAdapter;
private RecyclerView.LayoutManager mLayoutManager;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.mua_list);
getSupportActionBar().setTitle("Make Up Artists");
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
ArrayList<MuaView> muaView = new ArrayList<>();
muaView.add(new MuaView(R.drawable.mua_image, "Make Up Artist Pte Ltd"));
muaView.add(new MuaView(R.drawable.mua_image, "Aake Up Artist Pte Ltd"));
muaView.add(new MuaView(R.drawable.mua_image, "Lake Up Artist 3Pte Ltd"));
muaView.add(new MuaView(R.drawable.mua_image, "f Up Artist Pte Ltd"));
// ArrayList
mRecyclerView = findViewById(R.id.recycler_view_list);
mRecyclerView.setHasFixedSize(true);
mLayoutManager = new LinearLayoutManager(this);
mAdapter = new MuaAdapter(muaView);
mRecyclerView.setLayoutManager(mLayoutManager);
mRecyclerView.setAdapter(mAdapter);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
MenuInflater inflater = getMenuInflater();
inflater.inflate(R.menu.search, menu);
MenuItem searchItem = menu.findItem(R.id.action_search);
SearchView searchView = (SearchView) searchItem.getActionView();
searchView.setImeOptions(EditorInfo.IME_ACTION_DONE);
searchView.setOnQueryTextListener(new SearchView.OnQueryTextListener() {
#Override
public boolean onQueryTextSubmit(String query) {
return false;
}
#Override
public boolean onQueryTextChange(String newText) {
mAdapter.getFilter().filter(newText);
});
return true;
}
}
private RecyclerView.Adapter mAdapter;
replace
private MuaAdapter mAdapter;
The problem was that the getFilter method is only present in the MuaAdapter class, and the RecyclerView.Adapte does not know anything about getFilter
The #Override annotation tells the compiler you're want to override the getFilter method in RecyclerView.Adapter - but there is no such method. Remove the annotation.
// #Override <-- REMOVE THIS
public Filter getFilter() {
return MuaFilter;
}
You also need to change the member variable declaration in your activity.
private MuaAdapter mAdapter;

RecyclerView search filter getting wrong position after filtering result

Hello friend please help me i am using Recylerview and implemented searchfilter but problem is that after searching the item in recylerview when i click on item it always return 0 position of the item i want actual position of list item please me help here is my code how get actual position recylerview after searching item in recylerview
here is my code
package bible.swordof.God;
import android.content.Intent;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.os.Bundle;
import android.speech.RecognizerIntent;
import android.support.design.widget.NavigationView;
import android.support.v4.app.Fragment;
import android.support.v4.view.GravityCompat;
import android.support.v4.view.MenuItemCompat;
import android.support.v4.widget.DrawerLayout;
import android.support.v7.app.ActionBarDrawerToggle;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.support.v7.widget.SearchView;
import android.support.v7.widget.Toolbar;
import android.text.TextUtils;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ListView;
import android.widget.Toast;
import java.util.ArrayList;
import java.util.List;
import java.util.Locale;
public class MainActivity extends AppCompatActivity implements NavigationView.OnNavigationItemSelectedListener, SearchView.OnQueryTextListener {
private ListView listView;
private ArrayList<String> books;
private ArrayList<String> bookid;
private ListViewAdapter adapter;
private DatabaseHelper mDBHelper = null;
private SQLiteDatabase mDb = null;
BookRecyclerAdopter bookRecyclerAdopter;
//life is awesome
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
ActionBarDrawerToggle toggle = new ActionBarDrawerToggle(
this, drawer, toolbar, R.string.navigation_drawer_open, R.string.navigation_drawer_close);
drawer.addDrawerListener(toggle);
toggle.syncState();
NavigationView navigationView = (NavigationView) findViewById(R.id.nav_view);
navigationView.setNavigationItemSelectedListener(this);
setData();
RecyclerView bookanme = findViewById(R.id.list);
bookanme.setLayoutManager(new LinearLayoutManager(this));
bookRecyclerAdopter = new BookRecyclerAdopter(this, books);
bookanme.setAdapter(bookRecyclerAdopter);
/* adapter = new ListViewAdapter(MainActivity.this, R.layout.item_listview, books, bookid);
listView.setAdapter(adapter);*/
/* listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
int booknumber=position;
String bookname=bookid.get(position);
Toast.makeText(MainActivity.this, ""+bookname, Toast.LENGTH_SHORT).show();
*//* Intent intent=new Intent(MainActivity.this,Chapters.class);
intent.putExtra("booknumber",booknumber);
intent.putExtra("bookname",bookname);
startActivity(intent);*//*
}
});
}
*/
}
#Override
public void onBackPressed() {
DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
if (drawer.isDrawerOpen(GravityCompat.START)) {
drawer.closeDrawer(GravityCompat.START);
} else {
super.onBackPressed();
}
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case R.id.search_voice_btn:
Intent intent = new Intent(RecognizerIntent.ACTION_RECOGNIZE_SPEECH);
intent.putExtra(RecognizerIntent.EXTRA_LANGUAGE_MODEL, RecognizerIntent.LANGUAGE_MODEL_FREE_FORM);
intent.putExtra(RecognizerIntent.EXTRA_LANGUAGE, Locale.getDefault());
if (intent.resolveActivity(getPackageManager()) != null) {
startActivityForResult(intent, 10);
} else {
Toast.makeText(this, "Your Device Don't Support Speech Input", Toast.LENGTH_SHORT).show();
}
break;
}
return super.onOptionsItemSelected(item);
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
switch (requestCode) {
case 10:
if (resultCode == RESULT_OK && data != null) {
ArrayList<String> result = data.getStringArrayListExtra(RecognizerIntent.EXTRA_RESULTS);
Toast.makeText(this, "" + result.get(0), Toast.LENGTH_SHORT).show();
}
break;
}
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.main, menu);
MenuItem myActionMenuItem = menu.findItem(R.id.action_search);
final SearchView searchView = (SearchView) MenuItemCompat.getActionView(myActionMenuItem);
searchView.setOnQueryTextListener(this);
return true;
}
#SuppressWarnings("StatementWithEmptyBody")
#Override
public boolean onNavigationItemSelected(MenuItem item) {
// Handle navigation view item clicks here.
Fragment fragment;
int id = item.getItemId();
if (id == R.id.home) {
Intent intent = new Intent(this, MainActivity.class);
startActivity(intent);
} else if (id == R.id.favoruite) {
Intent intent = new Intent(this, Favourite.class);
startActivity(intent);
} else if (id == R.id.nav_manage) {
} else if (id == R.id.nav_share) {
} else if (id == R.id.nav_send) {
}
DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
drawer.closeDrawer(GravityCompat.START);
return true;
}
private void setData() {
books = new ArrayList<>();
bookid = new ArrayList<>();
mDBHelper = new DatabaseHelper(this);
mDb = mDBHelper.getReadableDatabase();
Cursor cursor = mDb.rawQuery("select b,n from key_english", new String[]{});
if (cursor != null && cursor.getCount() > 0) {
if (cursor.moveToFirst()) {
do {
books.add(cursor.getString(1));
bookid.add(cursor.getString(0));
} while (cursor.moveToNext());
}
}
}
#Override
public boolean onQueryTextSubmit(String s) {
return false;
}
#Override
public boolean onQueryTextChange(String newtext) {
String userinput = newtext.toLowerCase();
List<String> newlist = new ArrayList<>();
for (String name : books) {
if (name.toLowerCase().contains(userinput)) {
newlist.add(name);
}
}
bookRecyclerAdopter.updatelist(newlist);
return true;
}
}
package bible.swordof.God;
import android.app.Activity;
import android.content.Context;
import android.support.annotation.NonNull;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Filter;
import android.widget.Filterable;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;
import com.amulyakhare.textdrawable.TextDrawable;
import com.amulyakhare.textdrawable.util.ColorGenerator;
import java.util.ArrayList;
import java.util.List;
public class BookRecyclerAdopter extends RecyclerView.Adapter<BookRecyclerAdopter.Booksholder>{
private List<String> bookname;
Context context;
public BookRecyclerAdopter(Context context,List<String> bookname) {
this.bookname = bookname;
this.context=context;
}
public class Booksholder extends RecyclerView.ViewHolder {
private ImageView imageView;
private TextView bookname;
public Booksholder(#NonNull View itemView) {
super(itemView);
imageView = (ImageView) itemView.findViewById(R.id.image_view);
bookname = (TextView) itemView.findViewById(R.id.text);
itemView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
}
});
}
}
#Override
public Booksholder onCreateViewHolder(#NonNull ViewGroup viewGroup, int i) {
LayoutInflater inflater = LayoutInflater.from(viewGroup.getContext());
View view = inflater.inflate(R.layout.item_listview, viewGroup, false);
return new Booksholder(view);
}
#Override
public void onBindViewHolder(#NonNull Booksholder booksholder, final int i) {
booksholder.bookname.setText(bookname.get(i));
//get first letter of each String item
String firstLetter = String.valueOf(bookname.get(i).charAt(0));
ColorGenerator generator = ColorGenerator.MATERIAL; // or use DEFAULT
// generate random color
int color = generator.getColor(bookname.get(i));
TextDrawable drawable = TextDrawable.builder()
.buildRound(firstLetter, color); // radius in px
booksholder.imageView.setImageDrawable(drawable);
}
#Override
public int getItemCount() {
return bookname.size();
}
public void updatelist(List<String>newlist){
bookname=new ArrayList<>();
bookname.addAll(newlist);
notifyDataSetChanged();
}
}
You will need to maintain a separate list of bookname. Let's call it filteredBookname. Initially set it as bookname.
public class BookRecyclerAdopter extends RecyclerView.Adapter<BookRecyclerAdopter.Booksholder>{
private List<String> bookname;
private List<String> filteredBookname;
Context context;
public BookRecyclerAdopter(Context context,List<String> bookname) {
this.bookname = bookname;
this.filteredBookname = bookname
this.context=context;
}
...
// other pieces of code.
and instead of using bookname to populate RecyclerView items, use filteredBookname
and your update list method will be,
public void updatelist(List<String>newlist){
filteredBookname=new ArrayList<>();
filteredBookname.addAll(newlist);
notifyDataSetChanged();
}
Using the above approach, you can always find the proper position of your item in the original list bookname
The reason is that you are picking the wrong list, pick your data from filtered adapter list/model.
listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
Books booksdata= (Books)adapterName.bookname.get(position);
Toast.makeText(MainActivity.this, ""+booksdata.bookname, Toast.LENGTH_SHORT).show();
Intent intent=new Intent(MainActivity.this,Chapters.class);
intent.putExtra("booknumber",booksdata.booknumber);
intent.putExtra("bookname",booksdata.bookname);
startActivity(intent);
}
});
}
holder.cardView_title.setOnClickListener {
when (holder.tv_number.text) {
"1" -> {
(context as Activity).startActivity(Intent(context, Ma1::class.java))
}
"2" -> {
(context as Activity).startActivity(Intent(context, Ma2::class.java))
}
"3" -> {
(context as Activity).startActivity(Intent(context, Ma3::class.java))
}
}
}

Listview selected item highlight coming from database?

I am beginner in android creating religious book I have two activities both have listview the data is coming from sqlite database when i click any particular item from first activity switch to second activity show all detail in second activity which also have listview my question how to highlight second list item row only particular item is highlighted ! here example shown in picture what actually i want
here if anyone click on verse 13 all verse 1-25 is all show but only highlight verse 13 in next activity how this can be done here is my code
import android.content.Context;
import android.content.Intent;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.support.v7.widget.SearchView;
import android.support.v7.widget.Toolbar;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;
import java.util.ArrayList;
public class Chapters extends AppCompatActivity {
private ListView listView;
private ArrayList<String> stringArrayList;
private ArrayAdapter<String> adapter;
private DatabaseHelper mDBHelper;
private SQLiteDatabase mDb;
private int booknumber;
private String bookname;
TextView setbookname;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_chapters);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setbookname=(TextView)findViewById(R.id.bookname);
Intent mIntent = getIntent();
booknumber= mIntent.getIntExtra("booknumber", 0);
bookname=mIntent.getStringExtra("bookname");
setbookname.setText(bookname);
toolbar.setTitle("");
setSupportActionBar(toolbar);
if (getSupportActionBar() != null) {
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
getSupportActionBar().setDisplayShowHomeEnabled(true);
}
Toast.makeText(this, ""+booknumber, Toast.LENGTH_SHORT).show();
setData();
listView =findViewById(R.id.list);
adapter = new ChapterAdopter(Chapters.this, R.layout.item_listview, stringArrayList);
listView.setAdapter(adapter);
listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
int chapternumber=position+1;
Toast.makeText(Chapters.this, ""+chapternumber, Toast.LENGTH_SHORT).show();
Intent intent=new Intent(Chapters.this,Verse.class);
intent.putExtra("Booknumber",booknumber);
intent.putExtra("Chapternumber",chapternumber);
startActivity(intent);
}
});
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// handle arrow click here
if (item.getItemId() == android.R.id.home) {
onBackPressed();
}
return super.onOptionsItemSelected(item);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
MenuInflater inflater=getMenuInflater();
inflater.inflate(R.menu.chapter,menu);
MenuItem menuItem=menu.findItem(R.id.chapter_search);
SearchView searchView=(SearchView)menuItem.getActionView();
searchView.setOnQueryTextListener(new SearchView.OnQueryTextListener() {
#Override
public boolean onQueryTextSubmit(String s) {
return false;
}
#Override
public boolean onQueryTextChange(String s) {
return false;
}
});
return super.onCreateOptionsMenu(menu);
}
private void setData() {
stringArrayList = new ArrayList<>();
mDBHelper = new DatabaseHelper(this);
mDb = mDBHelper.getReadableDatabase();
Cursor cursor = mDb.rawQuery("select DISTINCT c from t_asv where b="+booknumber, new String[]{});
if(cursor!=null && cursor.getCount() > 0)
{
if (cursor.moveToFirst())
{
do {
stringArrayList.add(cursor.getString(0));
} while (cursor.moveToNext());
}
}
}
}
package bible.swordof.God;
import android.content.Intent;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.support.v7.widget.SearchView;
import android.support.v7.widget.Toolbar;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.widget.ArrayAdapter;
import android.widget.ListView;
import android.widget.Toast;
import java.util.ArrayList;
public class Verse extends AppCompatActivity {
private ListView listView;
private ArrayList<String> stringArrayList;
private ArrayAdapter<String> adapter;
private DatabaseHelper mDBHelper;
private SQLiteDatabase mDb;
private int booknumber;
private int chapternumber;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_verse);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
Intent mIntent = getIntent();
booknumber = mIntent.getIntExtra("Booknumber", 0);
chapternumber= mIntent.getIntExtra("Chapternumber", 0);
toolbar.setTitle("");
setSupportActionBar(toolbar);
if (getSupportActionBar() != null) {
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
getSupportActionBar().setDisplayShowHomeEnabled(true);
}
setData();
listView = findViewById(R.id.list);
adapter = new VerseAdopter(Verse.this, R.layout.item_listview, stringArrayList);
Toast.makeText(this, ""+booknumber, Toast.LENGTH_SHORT).show();
listView.setAdapter(adapter);
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// handle arrow click here
if (item.getItemId() == android.R.id.home) {
onBackPressed();
}
return super.onOptionsItemSelected(item);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
MenuInflater inflater = getMenuInflater();
inflater.inflate(R.menu.chapter, menu);
MenuItem menuItem = menu.findItem(R.id.chapter_search);
SearchView searchView = (SearchView) menuItem.getActionView();
searchView.setOnQueryTextListener(new SearchView.OnQueryTextListener() {
#Override
public boolean onQueryTextSubmit(String s) {
return false;
}
#Override
public boolean onQueryTextChange(String s) {
return false;
}
});
return super.onCreateOptionsMenu(menu);
}
private void setData() {
stringArrayList = new ArrayList<>();
mDBHelper = new DatabaseHelper(this);
mDb = mDBHelper.getReadableDatabase();
Cursor cursor = mDb.rawQuery("select v FROM t_asv where b="+booknumber+" AND c="+chapternumber+";", new String[]{});
if (cursor != null && cursor.getCount() > 0) {
if (cursor.moveToFirst()) {
do {
stringArrayList.add(cursor.getString(0));
} while (cursor.moveToNext());
}
}
}
}
It appears that you are passing the selected verse as a chapter and then in the query Cursor cursor = mDb.rawQuery("select v FROM t_asv where b="+booknumber+" AND c="+chapternumber+";", new String[]{}); therefore selecting all verses from the passed book/chapter.
You perhaps need to pass the clicked value as the verse as well as the book and chapter and use a query that includes the verse in the WHERE clause, perhaps cursor = mDb.rawQuery("select v FROM t_asv where b="+booknumber+" AND c="+chapternumber+" AND v=" + versenumber + " ;", new String[]{});

Using SearchView on ListView with SimpleCursorAdapter

So I am trying to create a simple activity page that shows all contacts. Using the search view in the action bar, they should be able to filter the contacts. The contacts are correctly being populated into the ListView but the SearchView is not filtering the list. The list never updates.
This is my contacts activity:
package com.example.android.whereyouat;
import android.app.SearchManager;
import android.content.Context;
import android.database.Cursor;
import android.os.Bundle;
import android.provider.ContactsContract;
import android.support.v4.app.NavUtils;
import android.support.v4.view.MenuItemCompat;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.SearchView;
import android.support.v7.widget.Toolbar;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.widget.ListView;
import android.widget.SimpleCursorAdapter;
public class Contacts extends AppCompatActivity {
Cursor cursor1;
SimpleCursorAdapter adapter;
SearchView searchView;
ListView lv;
MenuItem searchMenuItem;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_contacts);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
lv = (ListView) findViewById(R.id.list);
cursor1 = getContentResolver().query(ContactsContract.CommonDataKinds.Phone.CONTENT_URI, null, null, null, ContactsContract.CommonDataKinds.Phone.DISPLAY_NAME + " ASC");
startManagingCursor(cursor1);
String[] from = {ContactsContract.CommonDataKinds.Phone.DISPLAY_NAME, ContactsContract.CommonDataKinds.Phone.NUMBER, ContactsContract.CommonDataKinds.Phone._ID};
int[] to = {android.R.id.text1, android.R.id.text2};
adapter = new SimpleCursorAdapter(this, android.R.layout.simple_list_item_multiple_choice, cursor1, from, to);
lv.setAdapter(adapter);
lv.setChoiceMode(lv.CHOICE_MODE_MULTIPLE);
lv.setTextFilterEnabled(true);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
MenuInflater inflater = getMenuInflater();
inflater.inflate(R.menu.menu_contacts, menu);
searchMenuItem = menu.findItem(R.id.action_search);
searchView = (SearchView) MenuItemCompat.getActionView(searchMenuItem);
SearchManager SManager = (SearchManager) getSystemService(Context.SEARCH_SERVICE);
android.support.v7.widget.SearchView searchViewAction = (android.support.v7.widget.SearchView) MenuItemCompat.getActionView(searchMenuItem);
searchViewAction.setSearchableInfo(SManager.getSearchableInfo(getComponentName()));
searchViewAction.setIconifiedByDefault(true);
searchView.setOnQueryTextListener(new SearchView.OnQueryTextListener() {
#Override
public boolean onQueryTextSubmit(String query) {
return false;
}
#Override
public boolean onQueryTextChange(String newText) {
adapter.getFilter().filter(newText);
return false;
}
});
return super.onCreateOptionsMenu(menu);
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case android.R.id.home:
NavUtils.navigateUpFromSameTask(this);
return true;
case R.id.action_search:
//openSearch();
return true;
default:
return super.onOptionsItemSelected(item);
}
}
}

converting class into interface

please help me about that how i can convert my class into interface so other classes can use main menu . or let me know if there is easy way to call the same menu in the main class except extends bcz there are classes which already are extending other classes. here is the sample code
package com.droidnova.android.howto.optionmenu;
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.widget.Toast;
public class ControlMenu extends Activity {
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
MenuInflater inflater = getMenuInflater();
inflater.inflate(R.menu.menu, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case R.id.settings:
Intent intent = new Intent(this, ShowSettings.class);
startActivity(intent);
break;
case R.id.services:
Intent intent2 = new Intent(this, Test.class);
startActivity(intent2);
break;
case R.id.Quit:
finish();
break;
default:
break;
}
return true;
}
}
i want to call these menus into other classes (one of them are listed below) so that option menu is available on every activity without using extends.
public class Test extends ListActivity {
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.listplaceholder);
ArrayList<HashMap<String, String>> mylist = new ArrayList<HashMap<String, String>>();
JSONObject json = JSONfunctions.getJSONfromURL("http://midsweden.gofreeserve.com/fetch.php");
try{
JSONArray earthquakes = json.getJSONArray("earthquakes");
for(int i=0;i<earthquakes.length();i++){
HashMap<String, String> map = new HashMap<String, String>();
JSONObject e = earthquakes.getJSONObject(i);
map.put("id", String.valueOf(i));
map.put("name", "Earthquake name:" + e.getString("name"));
map.put("password", "Magnitude: " + e.getString("password"));
mylist.add(map);
}
}catch(JSONException e) {
Log.e("log_tag", "Error parsing data "+e.toString());
}
ListAdapter adapter = new SimpleAdapter(this, mylist , R.layout.test,
new String[] { "name", "magnitude" },
new int[] { R.id.item_title, R.id.item_subtitle });
setListAdapter(adapter);
final ListView lv = getListView();
lv.setTextFilterEnabled(true);
lv.setOnItemClickListener(new OnItemClickListener() {
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
#SuppressWarnings("unchecked")
HashMap<String, String> o = (HashMap<String, String>) lv.getItemAtPosition(position);
Toast.makeText(Test.this, "ID '" + o.get("id") + "' was clicked.", Toast.LENGTH_SHORT).show();
}
});
}
}
now i am following this way
package com.droidnova.android.howto.optionmenu;
import android.app.Activity;
import android.content.Intent;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.content.Intent;
public class MenuHandler extends Activity{
private Activity activity;
public MenuHandler(Activity activity) {
this.activity = activity;
}
public boolean onCreateOptionsMenu(Menu menu) {
MenuInflater inflater = activity.getMenuInflater();
inflater.inflate(R.menu.menu, menu);
return true;
}
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case R.id.settings:
Intent intent = new Intent(this, ShowSettings.class);
startActivity(intent);
break;
case R.id.services:
Intent intent2 = new Intent(this, Test.class);
startActivity(intent2);
break;
case R.id.Quit:
finish();
break;
default:
break;
}
return true;
}
}
and Test class is
package com.droidnova.android.howto.optionmenu;
import java.util.ArrayList;
import java.util.HashMap;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.NodeList;
import android.app.ListActivity;
import android.content.Intent;
import android.os.Bundle;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ListAdapter;
import android.widget.ListView;
import android.widget.SimpleAdapter;
import android.widget.Toast;
public class Test extends ListActivity {
private MenuHandler menuHandler;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.listplaceholder);
menuHandler = new MenuHandler(this);
ArrayList<HashMap<String, String>> mylist = new ArrayList<HashMap<String, String>>();
JSONObject json = JSONfunctions.getJSONfromURL("http://midsweden.gofreeserve.com/fetch.php");
try{
JSONArray earthquakes = json.getJSONArray("earthquakes");
for(int i=0;i<earthquakes.length();i++){
HashMap<String, String> map = new HashMap<String, String>();
JSONObject e = earthquakes.getJSONObject(i);
map.put("id", String.valueOf(i));
map.put("name", "Earthquake name:" + e.getString("name"));
map.put("password", "Magnitude: " + e.getString("password"));
mylist.add(map);
}
}catch(JSONException e) {
Log.e("log_tag", "Error parsing data "+e.toString());
}
ListAdapter adapter = new SimpleAdapter(this, mylist , R.layout.test,
new String[] { "name", "magnitude" },
new int[] { R.id.item_title, R.id.item_subtitle });
setListAdapter(adapter);
final ListView lv = getListView();
lv.setTextFilterEnabled(true);
lv.setOnItemClickListener(new OnItemClickListener() {
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
#SuppressWarnings("unchecked")
HashMap<String, String> o = (HashMap<String, String>) lv.getItemAtPosition(position);
Toast.makeText(Test.this, "ID '" + o.get("id") + "' was clicked.", Toast.LENGTH_SHORT).show();
}
});
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
return menuHandler.onCreateOptionsMenu(menu);
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
return menuHandler.onOptionsItemSelected(item);
}
}
menu are perfectly appearing on the screen but when i am clicking on any menu it "Force to stop" pops up
Now i am able to get logat errors Here they are
What I would do is create a special class to handle menu creation and events and delegate everythng to it. The code will look like this:
public class MenuHandler {
private Activity activity;
public MenuHandler(Activity activity) {
this.activity = activity;
}
public boolean onCreateOptionsMenu(Menu menu) {
MenuInflater inflater = activity.getMenuInflater();
inflater.inflate(R.menu.menu, menu);
return true;
}
public boolean onOptionsItemSelected(MenuItem item) {
//Handle events here
}
}
Then when you need to have a menu in your Activity, you create MenuHandler and delegate method calls to it:
public MyActivity extends Activity {
private MenuHandler menuHandler;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
menuHandler = new MenuHandler(this);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
return menuHandler.onCreateOprionsMenu(menu);
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
return menuHandler.onOptionsItemSelected(item);
}
}
An interface does not have an implementation, so I don't think that will do what you want.
What you can do is make an activity that extends your ControlMenu. It will be an Activity (because controlmenu itself extends activity), and it will be able to use the code you have provided here. It will look something like
public class yourActivity extends ControlMenu{
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState); //oncreate of controlmenu
LayoutInflater inflater = getLayoutInflater();
RelativeLayout ll = (RelativeLayout) findViewById(R.id.main);
ListView lv = (ListView) inflater.inflate(R.layout.yourlistview, ll, false);
ll.addView(lv);
lv.setAdapter(new YourAdapter(this));
}
}
and you'll have an adapter that goes like (quick mock-up)
public abstract class YourAdapter extends BaseAdapter {
final public int getCount() {}
final public Object getItem(int position) {}
final public long getItemId(int position) {}
final public void onItemClick() {}
}

Categories