Using SearchView on ListView with SimpleCursorAdapter - java

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);
}
}
}

Related

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[]{});

Android: Add searchView on the Action Bar

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;
}

How to create a search bar in android with a suggestion drop down appearing upon typing text in search bar?

I want to create a search bar with a drop down suggestion list, which appears upon typing text in the search bar. The suggestion list should completely or partially cover the activity screen(The drop down is not a new activity itself). The result should be populated from the backend, which contains a list of hard coded strings. I cannot find a solution for such a problem. Can someone please help me out here?
My MainActivity looks like this:-
import android.app.ActionBar;
import android.app.SearchManager;
import android.content.Intent;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.support.v7.widget.SearchView;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.widget.ArrayAdapter;
import android.widget.ImageView;
import android.widget.ListView;
import java.util.ArrayList;
import java.util.Arrays;
public class MainActivity extends AppCompatActivity
{
ArrayAdapter<String> adapter;
#Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
ListView lv = (ListView)findViewById(R.id.listViewBuilding);
ArrayList<String> arrayBuilding = new ArrayList<>();
arrayBuilding.addAll(Arrays.asList(getResources().getStringArray(R.array.array_buildings)));
adapter = new ArrayAdapter<>(MainActivity.this, android.R.layout.simple_dropdown_item_1line, arrayBuilding);
lv.setAdapter(adapter);
lv.setVisibility(View.GONE);
lv.setTextFilterEnabled(true);
if(getSupportActionBar()!=null) {
getSupportActionBar().setDisplayShowTitleEnabled(false);
}
}
#Override
public boolean onCreateOptionsMenu(Menu menu)
{
MenuInflater inflater = getMenuInflater();
inflater.inflate(R.menu.menu_search, menu);
MenuItem item = menu.findItem(R.id.menu_search);
SearchView searchView = (SearchView)item.getActionView();
searchView.setOnQueryTextListener(new SearchView.OnQueryTextListener(){
#Override
public boolean onQueryTextSubmit(String query)
{
return false;
}
#Override
public boolean onQueryTextChange(String newText)
{
ListView lv = (ListView)findViewById(R.id.listViewBuilding);
lv.setVisibility(View.VISIBLE);
adapter.getFilter().filter(newText);
return false;
}
});
return super.onCreateOptionsMenu(menu);
}
}

How can i find last fragment in the mainActivity

I want to make my viewPager support Rtl, and set the current item on the last fragment, but when I write this code in my MainActivity.java, I don't know how I can access the last fragment.
According to this post, I want make my viewPager to Rtl:
iViewPager.setCurrentItem();
MainActivity.java, where I define the viewPager:
package com.example.imajid.grid2.activities;
import android.support.design.widget.NavigationView;
import android.support.design.widget.TabLayout;
import android.support.v4.view.GravityCompat;
import android.support.v4.view.ViewPager;
import android.support.v4.widget.DrawerLayout;
import android.support.v7.app.ActionBar;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.support.v7.widget.Toolbar;
import android.view.Menu;
import android.view.MenuItem;
import android.widget.Toast;
import com.example.imajid.grid2.R;
import com.example.imajid.grid2.adapters.PagerAdapter;
import java.util.ArrayList;
public class MainActivity extends AppCompatActivity {
private DrawerLayout mDrawerLayout;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
//----------------------- set toolbar
Toolbar iToolbar = (Toolbar) findViewById(R.id.xmlToolbar);
setSupportActionBar(iToolbar);
//------------------------------ initialize toolbar
ActionBar actionBar = getSupportActionBar();
actionBar.setHomeAsUpIndicator(R.drawable.menu);
actionBar.setDisplayHomeAsUpEnabled(true);
//**************************** find tablayout *****************************//
TabLayout iTabLayout = (TabLayout) findViewById(R.id.xmlTabLayout);
iTabLayout.addTab(iTabLayout.newTab());
iTabLayout.addTab(iTabLayout.newTab());
iTabLayout.addTab(iTabLayout.newTab());
iTabLayout.setTabGravity(TabLayout.GRAVITY_FILL);
//******************************* Array list for sending titles *********************************//
ArrayList<String> viewPagersTitle = new ArrayList<String>();
viewPagersTitle.add("صفحه اصلی");
viewPagersTitle.add("فیلم");
viewPagersTitle.add("آهنگ");
//******************************* find view pager in xml *****************************//
ViewPager iViewPager = (ViewPager) findViewById(R.id.xmlViewPager);
//************************************** Rtlizer view pager ************************************
====>iViewPager.setCurrentItem();
//************************************** find adapter for view pager *******************************//
PagerAdapter viewPagerAdapter = new PagerAdapter(getSupportFragmentManager(), iTabLayout.getTabCount(), viewPagersTitle);
//************************************ set adapter for view pager *******************************//
iViewPager.setAdapter(viewPagerAdapter);
//*********************************** setup tablayout to view pager********************************//
iTabLayout.setupWithViewPager(iViewPager);
mDrawerLayout = (DrawerLayout) findViewById(R.id.xmlDrawerLayoutRoot);
//-------------------------------------- find navigation view
NavigationView navigationView = (NavigationView)findViewById(R.id.xmlNavigation);
navigationView.setNavigationItemSelectedListener(new NavigationView.OnNavigationItemSelectedListener() {
#Override
public boolean onNavigationItemSelected(MenuItem menuItem) {
menuItem.setChecked(true);
mDrawerLayout.closeDrawers();
Toast.makeText(MainActivity.this, menuItem.getTitle(), Toast.LENGTH_SHORT).show();
return true;
}
});
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.main_menu, menu);
return true;
}
//onoptionItemSelected
#Override
public boolean onOptionsItemSelected(MenuItem item) {
int itemId = item.getItemId();
String btnName = null;
switch (itemId){
case android.R.id.home:
mDrawerLayout.openDrawer(GravityCompat.START);
return true;
case R.id.menu_setting:
btnName = "Setting";
break;
case R.id.menu_compass:
btnName = "Compass";
break;
case R.id.menu_help:
btnName = "Help";
break;
}
Toast.makeText(MainActivity.this, "You clicked at " + btnName, Toast.LENGTH_SHORT).show();
return true;
}
}
Finally, this is my view pager adapter:
package com.example.imajid.grid2.adapters;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentStatePagerAdapter;
import com.example.imajid.grid2.fragments.TabFragment1;
import com.example.imajid.grid2.fragments.TabFragment2;
import com.example.imajid.grid2.fragments.TabFragment3;
import java.util.ArrayList;
/**
* Created by imajid on 12/8/2015.
*/
public class PagerAdapter extends FragmentStatePagerAdapter {
private ArrayList<String> titles;
int numOfTabs;
public PagerAdapter(FragmentManager fm, int numOfTabs, ArrayList<String> titles) {
super(fm);
this.numOfTabs = numOfTabs;
this.titles = titles;
}
#Override
public Fragment getItem(int position) {
switch (position) {
case 0:
TabFragment1 tab1 = new TabFragment1();
return tab1;
case 1:
TabFragment2 tab2 = new TabFragment2();
return tab2;
case 2:
TabFragment3 tab3 = new TabFragment3();
return tab3;
default:
return null;
}
}
#Override
public int getCount() {
return this.numOfTabs;
}
#Override
public CharSequence getPageTitle(int position) {
return titles.get(position);
}
}
becuse i use :
setCurrentItem(viewPagerAdapter.getCount());
before the setting the adapter it's not working and i should write this code after the setting the adpter , thanks to Kevin Chris and K Neeraj Lal .

Android Intent doesnt work

so I have these code
main.java
package com.example.kamusinggris_indonesiaidiom;
import android.app.Activity;
import android.app.SearchManager;
import android.content.Context;
import android.content.Intent;
import android.database.Cursor;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ListView;
import android.widget.SearchView;
import android.widget.SimpleCursorAdapter;
import android.widget.TextView;
import android.widget.AdapterView.OnItemClickListener;
public class Main extends Activity {
private TextView teks;
private ListView list;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
teks = (TextView) findViewById(R.id.text);
list = (ListView) findViewById(R.id.list);
}
protected void onNewIntent(Intent intent) {
handleIntent(getIntent());
}
private void handleIntent(Intent intent) {
// TODO Auto-generated method stub
handleIntent(intent);
if (Intent.ACTION_VIEW.equals(intent.getAction())) {
Intent wordIntent = new Intent(this, Definisi.class);
wordIntent.setData(intent.getData());
startActivity(wordIntent);
} else if (Intent.ACTION_SEARCH.equals(intent.getAction())) {
String query = intent.getStringExtra(SearchManager.QUERY);
showResults(query);
}
}
private void showResults(String query) {
// TODO Auto-generated method stub
Cursor cursor = managedQuery(Provider.CONTENT_URI, null, null,
new String[] {query}, null);
if (cursor == null) {
// There are no results
teks.setText(getString(R.string.no_results, new Object[] {query}));
} else {
// Display the number of results
int count = cursor.getCount();
String countString = getResources().getQuantityString(R.plurals.search_results,
count, new Object[] {count, query});
teks.setText(countString);
// Specify the columns we want to display in the result
String[] from = new String[] { Database.KATA,
Database.DEFINISI };
// Specify the corresponding layout elements where we want the columns to go
int[] to = new int[] { R.id.kata,
R.id.definisi };
// Create a simple cursor adapter for the definitions and apply them to the ListView
SimpleCursorAdapter words = new SimpleCursorAdapter(this,
R.layout.hasil_pencarian, cursor, from, to);
list.setAdapter(words);
list.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View tmp,
int posisi, long id) {
// TODO Auto-generated method stub
Intent definisi = new Intent(getApplicationContext(), Definisi.class);
Uri data = Uri.withAppendedPath(Provider.CONTENT_URI,
String.valueOf(id));
definisi.setData(data);
startActivity(definisi);
}
});
}
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
MenuInflater inflater = getMenuInflater();
inflater.inflate(R.menu.main, menu);
if(Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB){
SearchManager searchManager = (SearchManager) getSystemService(Context.SEARCH_SERVICE);
SearchView searchView = (SearchView) menu.findItem(R.id.search).getActionView();
searchView.setSearchableInfo(searchManager.getSearchableInfo(getComponentName()) );
searchView.setIconifiedByDefault(false);
}
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case R.id.search:
onSearchRequested();
return true;
default:
return false;
}
}
}
definisi.java
package com.example.kamusinggris_indonesiaidiom;
import android.app.ActionBar;
import android.app.Activity;
import android.app.SearchManager;
import android.content.Context;
import android.content.Intent;
import android.database.Cursor;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.widget.SearchView;
import android.widget.TextView;
public class Definisi extends Activity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_definisi);
if(Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB){
ActionBar actionBar = getActionBar();
actionBar.setDisplayHomeAsUpEnabled(true);
}
Uri uri = getIntent().getData();
Cursor kursor = managedQuery(uri, null, null, null, null);
if (kursor == null) {
finish();
} else {
kursor.moveToFirst();
TextView kata = (TextView) findViewById(R.id.kata);
TextView definisi= (TextView) findViewById(R.id.definisi);
int wIndex = kursor.getColumnIndexOrThrow(Database.KATA);
int dIndex = kursor.getColumnIndexOrThrow(Database.DEFINISI);
kata.setText(kursor.getString(wIndex));
definisi.setText(kursor.getString(dIndex));
} }
#Override
public boolean onCreateOptionsMenu(Menu menu) {
MenuInflater inflater = getMenuInflater();
inflater.inflate(R.menu.main, menu);
if(Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB){
SearchManager searchManager = (SearchManager) getSystemService(Context.SEARCH_SERVICE);
SearchView searchView = (SearchView) menu.findItem(R.id.search).getActionView();
searchView.setSearchableInfo(searchManager.getSearchableInfo(getComponentName()));
searchView.setIconifiedByDefault(false);
}
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case R.id.search:
onSearchRequested();
return true;
case android.R.id.home:
Intent a = new Intent(this, Main.class);
a.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
startActivity(a);
return true;
default:
return false;
}
}
}
its a dictionary, so when a search suggestion on a listview is clicked, it supposed to open the definisi.java and display the definition. But what I got here is when I clicked the search suggestion it displayed the main.java (its just go back to the previous activity). what's wrong on the intent part? please help me
Use passed intent variable in onNewIntent
protected void onNewIntent(Intent intent) {
handleIntent(intent);
}
You should also remove call to handleIntent from within handleIntent method

Categories