Can't display my custom suggestion using SearchView - android

I'm using a SearchView and I have added the search feature (that works) and now I'm trying to add a custom suggestion. The provider is created but when i type something query() is never called for some reasons.
Where am I wrong?
Here my manifest:
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.chefme.chefme">
<uses-feature
android:name="android.hardware.sensor.accelerometer"
android:required="true" />
<uses-feature
android:name="android.permission-group.MICROPHONE"
android:required="true"/>
<uses-feature android:name="android.hardware.camera"
android:required="true" />
<!-- <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"
android:maxSdkVersion="18" />-->
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>
<application
android:allowBackup="true"
android:icon="#mipmap/ic_launcher"
android:label="#string/app_name"
android:supportsRtl="true"
android:theme="#style/AppTheme">
<provider
android:name=".RecipeIngredientTabs.SuggestionProvider"
android:authorities="com.chefme.chefme.RecipeIngredientTabs.SuggestionProvider">
</provider>
<activity
android:name=".Startup"
android:theme="#style/AppTheme.NoActionBar">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<activity
android:name=".RecipeIngredientTabs.Main"
android:label="#string/app_name"
android:launchMode="singleTop"
android:theme="#style/AppTheme.NoActionBar" >
<intent-filter>
<action android:name="android.intent.action.SEARCH" />
</intent-filter>
<meta-data android:name="android.app.searchable"
android:resource="#xml/searchable"/>
</activity>
<activity
android:name=".RecipeStep"
android:label="#string/title_activity_recipe_steps"
android:launchMode="singleInstance"
android:theme="#style/AppTheme.NoActionBar" />
<activity
android:name=".RecipePreview.RecipePreview"
android:label="#string/title_activity_recipe_preview"
android:launchMode="singleInstance"
android:theme="#style/AppTheme.NoActionBar" />
<activity
android:name=".ShoppingList.ShoppingList"
android:label="#string/title_activity_shopping_list"
android:launchMode="singleInstance"
android:theme="#style/AppTheme.NoActionBar" />
<activity
android:name=".Settings.Diets"
android:label="#string/title_activity_diets"
android:launchMode="singleInstance"
android:theme="#style/AppTheme.NoActionBar"/>
<activity
android:name=".Favorite.FavoriteActivity"
android:label="#string/title_activity_favorite"
android:launchMode="singleInstance"
android:theme="#style/AppTheme.NoActionBar"/>
<activity
android:name=".ownRecipesCamera.TakePicture"
android:label="#string/title_activity_take_picture"
android:launchMode="singleInstance"
android:theme="#style/AppTheme.NoActionBar"/>
<activity
android:name=".Settings.Credits"
android:label="#string/title_activity_credits"
android:launchMode="singleInstance"
android:theme="#style/AppTheme.NoActionBar"/>
</application>
</manifest>
Here my Provider:
package com.chefme.chefme.RecipeIngredientTabs;
import android.content.ContentProvider;
import android.content.ContentValues;
import android.database.Cursor;
import android.database.MatrixCursor;
import android.net.Uri;
import android.support.annotation.Nullable;
import DBUtility.Data;
public class SuggestionProvider extends ContentProvider{
#Override
public boolean onCreate() {
System.out.println("Creation Provider");
return true;
}
#Nullable
#Override
public Cursor query(Uri uri, String[] projection, String selection, String[] selectionArgs, String sortOrder) {
String query = uri.getLastPathSegment().toLowerCase(); //Dovrebbe essere chiamato tramite searchable.xml
System.out.println("write: "+ query);
String[] columns = new String[]{"_ID", "SUGGEST_COLUMN_TEXT_1", "SUGGEST_COLUMN_ICON_1", "SUGGEST_COLUMN_INTENT_DATA"};
MatrixCursor cursor = new MatrixCursor(columns);
Object[] row = new Object[]{0, Data.currentIngredients.get(0).getName(), Data.currentIngredients.get(0).getImage(), "Gigi"};
cursor.addRow(row);
return cursor;
}
#Nullable
#Override
public String getType(Uri uri) {
return null;
}
#Nullable
#Override
public Uri insert(Uri uri, ContentValues contentValues) {
return null;
}
#Override
public int delete(Uri uri, String s, String[] strings) {
return 0;
}
#Override
public int update(Uri uri, ContentValues contentValues, String s, String[] strings) {
return 0;
}
}
Here my searchable.xml:
<?xml version="1.0" encoding="utf-8"?>
<searchable xmlns:android="http://schemas.android.com/apk/res/android"
android:label="#string/app_name"
android:hint="#string/action_search" >
android:searchSuggestAuthority="com.chefme.chefme.RecipeIngredientTabs.SuggestionProvider
android:searchSuggestIntentAction="android.Intent.action.VIEW" >
</searchable>
Here my main:
package com.chefme.chefme.RecipeIngredientTabs;
import android.Manifest;
import android.app.Activity;
import android.app.SearchManager;
import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.os.Bundle;
import android.os.Environment;
import android.support.design.widget.TabLayout;
import android.support.v4.app.ActivityCompat;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentPagerAdapter;
import android.support.v4.view.ViewPager;
import android.support.design.widget.NavigationView;
import android.support.v4.widget.DrawerLayout;
import android.support.v7.app.ActionBarDrawerToggle;
import android.support.v7.widget.SearchView;
import android.support.v7.widget.Toolbar;
import android.view.Menu;
import android.view.MenuItem;
import android.widget.Toast;
import com.chefme.chefme.NavbarActivity;
import com.chefme.chefme.R;
import java.io.File;
import DBUtility.Data;
public class Main extends NavbarActivity {
private SectionsPagerAdapter selectorPagerAdapter;
private ViewPager mViewPager;
private TabLayout tabLayout;
private Toast backtoast;
// Storage Permissions
private static final int REQUEST_EXTERNAL_STORAGE = 1;
private static String[] PERMISSIONS_STORAGE = {
Manifest.permission.READ_EXTERNAL_STORAGE,
Manifest.permission.WRITE_EXTERNAL_STORAGE
};
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
super.replaceContentLayout(R.layout.main_content, super.CONTENT_LAYOUT_ID);
verifyDirectoryExists();
verifyStoragePermissions(this);
handleIntent(getIntent());
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
ActionBarDrawerToggle toggle = new ActionBarDrawerToggle(
this, //host activity
drawer, //drawerLayout object
toolbar, //nav drawer icon to replace
R.string.navigation_drawer_open,
R.string.navigation_drawer_close);
drawer.setDrawerListener(toggle);
toggle.syncState();
NavigationView navigationView = (NavigationView) findViewById(R.id.nav_view);
navigationView.setNavigationItemSelectedListener(this);
// Create the adapter that will return a fragment for each of the three
// primary sections of the activity.
selectorPagerAdapter = new SectionsPagerAdapter(getSupportFragmentManager());
// Set up the ViewPager with the sections adapter.
mViewPager = (ViewPager) findViewById(R.id.container);
mViewPager.setAdapter(selectorPagerAdapter);
tabLayout = (TabLayout) findViewById(R.id.tabs);
tabLayout.setupWithViewPager(mViewPager);
}
#Override
protected void onResume(){
super.onResume();
Data.active_main = true;
}
#Override
protected void onPause(){
super.onPause();
Data.active_main = false;
}
public void onBackPressed() {
if(backtoast!=null&&backtoast.getView().getWindowToken()!=null) {
finish();
} else {
backtoast = Toast.makeText(this, "Press back to exit", Toast.LENGTH_SHORT);
backtoast.show();
}
}
#Override
protected void onNewIntent(Intent intent) {
setIntent(intent);
handleIntent(intent);
}
private void handleIntent(Intent intent) {
if (Intent.ACTION_SEARCH.equals(intent.getAction())) {
String query = intent.getStringExtra(SearchManager.QUERY);
System.out.println("Searched: " + query);
}
else if (Intent.ACTION_VIEW.equals(intent.getAction())) { //Intent partito da SuggestionProvider
String query = intent.getDataString();
System.out.println("Suggested: " + query);
}
}
//------------------------------------------------------------------------------------------
// TAB SELECTOR FUNCTIONS
//------------------------------------------------------------------------------------------
public class SectionsPagerAdapter extends FragmentPagerAdapter {
public SectionsPagerAdapter(FragmentManager fm) {
super(fm);
}
#Override
public Fragment getItem(int position) {
// getItem is called to instantiate the fragment for the given page.
if(position == 0)
return new TabFragmentIngredients();
if(position == 1)
return new TabFragmentRecipes();
else
return null;
}
#Override
public int getCount() {
// Show 2 total pages.
return 2;
}
#Override
public CharSequence getPageTitle(int position) {
switch (position) {
case 0:
return getString(R.string.name_ingredients_hint);
case 1:
return getString(R.string.name_recipes_hint);
}
return null;
}
}
//------------------------------------------------------------------------------------------
// MENU FUNCTIONS
//------------------------------------------------------------------------------------------
#Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.main, menu);
// Get the SearchView and set the searchable configuration
SearchManager searchManager = (SearchManager) getSystemService(Context.SEARCH_SERVICE);
SearchView searchView = (SearchView) menu.findItem(R.id.action_search).getActionView();
// Assumes current activity is the searchable activity
searchView.setSearchableInfo(searchManager.getSearchableInfo(getComponentName()));
searchView.setIconifiedByDefault(false); // Do not iconify the widget; expand it by default
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case R.id.action_settings: showOrderbyDialog();
return true;
}
return super.onOptionsItemSelected(item);
}
private void showOrderbyDialog() {
FragmentManager fm = getSupportFragmentManager();
OrderByDialog orderbyDialogDialog = new OrderByDialog();
orderbyDialogDialog.show(fm, "");
}
public static void verifyDirectoryExists(){
String folder_main = "GnammyRecipes";
File f = new File(Environment.getExternalStorageDirectory()+"/Pictures/", folder_main);
if (!f.exists()) {
f.mkdirs();
}
}
public static void verifyStoragePermissions(Activity activity) {
// Check if we have write permission
int permission = ActivityCompat.checkSelfPermission(activity, Manifest.permission.WRITE_EXTERNAL_STORAGE);
if (permission != PackageManager.PERMISSION_GRANTED) {
// We don't have permission so prompt the user
ActivityCompat.requestPermissions(
activity,
PERMISSIONS_STORAGE,
REQUEST_EXTERNAL_STORAGE
);
}
}
}

Can you please try to change to this
android:searchSuggestAuthority="com.chefme.chefme.RecipeIngredientTabs.SuggestionProvider
to
android:searchSuggestAuthority="#string/application_package_name"
android:searchSuggestSelection=" ?"
Also you are missing meta-data tag
<meta-data
android:name="android.app.default_searchable"
android:value="com.chefme.chefme.RecipeIngredientTabs.YOURSEARCHACTIVITY" >
</meta-data>
Refer this link
https://developer.android.com/guide/topics/search/search-dialog.html

Related

How to Implement Google Search in Android SearchView

What would be the proper way to Implement a Google Search with SearchView. For example, I press the Search button, and enter a query, and then after I hit enter button, it would do a google search in which I can get JSON data. All the examples I've seen are with lists or something similar. I'm trying figure out how to implement a Web search into SearchView
try using Google Custom Search api
I know this is old, but you should not put your SearchView searchView as a global variable, as that can lead to memory leaks. Instead, keep it as a local variable inside of onCreateOptionsMenu.
Figured it out! It was probably something to do with my Android Manifest or something:
AndroidManifest.xml:
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.alexoladele.testingshit">
<!-- Permissions's -->
<uses-permission android:name="android.permission.WRITE_INTERNAL_STORAGE" />
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" />
<application
android:allowBackup="true"
android:icon="#mipmap/ic_launcher"
android:label="#string/app_name"
android:roundIcon="#mipmap/ic_launcher_round"
android:supportsRtl="true"
android:theme="#style/Theme.AppCompat.Light.NoActionBar">
<meta-data
android:name="android.app.default_searchable"
android:value=".SearchActivity" />
<!-- Main Activity -->
<activity android:name=".MainActivity">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<!-- SearchActivity -->
<activity
android:name=".SearchActivity"
android:launchMode="singleTop">
<intent-filter>
<action android:name="android.intent.action.SEARCH" />
</intent-filter>
<meta-data
android:name="android.app.searchable"
android:resource="#xml/searchable" />
</activity>
</application>
</manifest>
SearchActivity.java:
package com.alexoladele.testingshit;
import android.app.ListActivity;
import android.app.SearchManager;
import android.content.Intent;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.util.Log;
import android.view.View;
import android.widget.ListView;
import com.google.api.services.customsearch.Customsearch;
public class SearchActivity extends ListActivity {
private static final String TAG = "SearchActivity";
private String qry;
private Customsearch customsearch;
#Override
protected void onCreate(#Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_search);
Log.i(TAG, "onCreate: ContentView was set to activity_search");
Intent intent = getIntent();
Log.i(TAG, "onCreate: Got Intent");
Log.i(TAG, "onCreate: Handling Intent!");
handleIntent(intent);
}
#Override
protected void onNewIntent(Intent intent) {
super.onNewIntent(intent);
setIntent(intent);
handleIntent(intent);
}
#Override
protected void onListItemClick(ListView l, View v, int position, long id) {
// Call detail activity for clicked entry
}
private void handleIntent(Intent intent) {
if (Intent.ACTION_SEARCH.equals(intent.getAction())) {
qry = intent.getStringExtra(SearchManager.QUERY);
Log.i(TAG, "handleIntent: QUERY: " + qry + "\n Starting the doSearch Method!");
doSearch(qry);
} else {
Log.i(TAG, "handleIntent: Intent WAS NOT search");
}
}
private void doSearch(String query) {
Log.i(TAG, "doSearch: In doSearch Method!");
}
}
MainActivity.java:
package com.alexoladele.testingshit;
import android.Manifest;
import android.app.SearchManager;
import android.content.ComponentName;
import android.content.Context;
import android.content.pm.PackageManager;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.v4.app.ActivityCompat;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentTransaction;
import android.support.v4.content.ContextCompat;
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.util.Log;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.widget.Toast;
import layout.WelcomeScreenFragment;
public class MainActivity extends AppCompatActivity {
private static final String TAG = "MainActivity";
SearchView searchView;
final static String[] NEEDED_PERMISSIONS = {Manifest.permission.WRITE_EXTERNAL_STORAGE,
Manifest.permission.INTERNET,
Manifest.permission.ACCESS_NETWORK_STATE};
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
// requestWindowFeature(Window.FEATURE_NO_TITLE);
// getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN, 0);
setContentView(R.layout.activity_main);
Toolbar toolbar = (Toolbar) findViewById(R.id.my_toolbar);
setSupportActionBar(toolbar);
if (ContextCompat.checkSelfPermission(getApplicationContext(), NEEDED_PERMISSIONS[0])
!= PackageManager.PERMISSION_GRANTED &&
ContextCompat.checkSelfPermission(getApplicationContext(), NEEDED_PERMISSIONS[1])
!= PackageManager.PERMISSION_GRANTED &&
ContextCompat.checkSelfPermission(getApplicationContext(), NEEDED_PERMISSIONS[2])
!= PackageManager.PERMISSION_GRANTED) {
ActivityCompat.requestPermissions(this, NEEDED_PERMISSIONS, 808);
Log.i(TAG, "onCreate: Requesting Permissions");
}
// Makes sure that the root_layout view is not null before doing anything
if (findViewById(R.id.root_layout) != null) {
// Makes sure that there's no saved instance before proceeding
if (savedInstanceState == null) {
FragmentManager fm = getSupportFragmentManager();
FragmentTransaction manager = fm.beginTransaction();
manager
.add(R.id.root_layout, WelcomeScreenFragment.newInstance(), "welcomeScreen")
.commit();
}
}
}
#Override
public void onRequestPermissionsResult(int requestCode, #NonNull String[] permissions, #NonNull int[] grantResults) {
switch (808) {
case 808:
if (grantResults[0] == PackageManager.PERMISSION_GRANTED) {
Toast.makeText(getApplicationContext(), "Permissions GRANTED", Toast.LENGTH_SHORT).show();
} else {
Toast.makeText(getApplicationContext(), "Permissions NOT GRANTED", Toast.LENGTH_SHORT).show();
}
}
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
MenuInflater inflater = getMenuInflater();
inflater.inflate(R.menu.options_menu, menu);
// VARIBLES TO USE
MenuItem searchItem = menu.findItem(R.id.search);
searchView = (SearchView) MenuItemCompat.getActionView(searchItem);
// Set Up the search Function
searchView.setOnQueryTextListener(new SearchView.OnQueryTextListener() {
#Override
public boolean onQueryTextSubmit(String query) {
return false;
}
#Override
public boolean onQueryTextChange(String newText) {
return false;
}
});
SearchManager searchManager = (SearchManager) getSystemService(Context.SEARCH_SERVICE);
ComponentName componentName = new ComponentName(getApplicationContext(), SearchActivity.class);
searchView.setSearchableInfo(searchManager.getSearchableInfo(componentName));
searchView.setIconifiedByDefault(false);
return true;
}
}

Activity doesn't start from NFC_TECH_DISCOVERED-intent filter

I am trying to read some information via NFC and created the intent-filter to do so, together with the xml that contains the required technologies. The intent-filter should start my ReadActivity, but it doesn't do so, when I put the card near my phone. NFC is activated, so this shouldn't be the problem. I really don't see the problem with my code, so it would be great if someone could take a look at it and maybe give me a hint in the right direction. Here is the code:
AndroidManifest.xml:
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.example.johan.nfcreaderforunicard">
<uses-permission android:name="android.permission.NFC" />
<uses-feature android:name="android.hardware.nfc" android:required="true"/>
<uses-sdk android:minSdkVersion="10"/>
<application
android:allowBackup="true"
android:icon="#mipmap/apple"
android:label="#string/app_name"
android:supportsRtl="true"
android:theme="#style/Theme.AppCompat.Light.NoActionBar">
<activity android:name=".MainActivity">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<activity android:name=".ReadActivity">
<intent-filter>
<action android:name="android.nfc.action.TECH_DISCOVERED"/>
<category android:name="android.intent.category.DEFAULT" />
</intent-filter>
<meta-data android:name="android.nfc.action.TECH_DISCOVERED"
android:resource="#xml/tech"/>
</activity>
</manifest>
ReadActivity:
import android.nfc.NfcAdapter;
import android.nfc.Tag;
import android.nfc.tech.IsoDep;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.widget.TextView;
import android.content.Intent;
import android.os.Bundle;
import java.io.IOException;
public class ReadActivity extends AppCompatActivity {
private final byte[] selectAid = {(byte)90, (byte)95, (byte)-124, (byte)21};
private final byte[] creditPayload = {(byte)108, (byte)1};
private byte[] resultOk;
private byte[] creditBytes;
#Override
public void onCreate(Bundle savedInstanceState){
super.onCreate(savedInstanceState);
setContentView(R.layout.read_view);
Toolbar myToolbar = (Toolbar) findViewById(R.id.my_toolbar);
setSupportActionBar(myToolbar);
if(NfcAdapter.ACTION_TECH_DISCOVERED.equals(getIntent().getAction())){
IsoDep isodep = IsoDep.get((Tag)getIntent().getParcelableExtra(NfcAdapter.EXTRA_TAG));
if(isodep != null){
try{
isodep.connect();
resultOk = isodep.transceive(selectAid);
if(resultOk[0] == 0){
creditBytes = isodep.transceive(creditPayload);
}
}catch (IOException e){
}
}
}
float credit = (float)formatCredit(creditBytes);
TextView label = (TextView)findViewById(R.id.read_text);
label.setText("Dein Guthaben: "+String.valueOf(credit)+"€");
}
private double formatCredit(byte[] array) {
double credit = (double)(((0xff & array[4]) << 24) + ((0xff & array[3]) << 16) + ((0xff & array[2]) << 8) + (0xff & array[1])) / 1000D;
return credit;
}
#Override
public boolean onCreateOptionsMenu(Menu menu){
MenuInflater inflater = getMenuInflater();
inflater.inflate(R.menu.menu, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem menuItem){
switch(menuItem.getItemId()){
case(R.id.action_settings):
Intent startSettings = new Intent(ReadActivity.this, SettingsActivity.class);
startActivity(startSettings);
return true;
case(R.id.about):
Intent startAbout = new Intent(ReadActivity.this, AboutActivity.class);
startActivity(startAbout);
return true;
default:
return super.onOptionsItemSelected(menuItem);
}
}
#Override
public void onBackPressed(){
Intent backToMain = new Intent(getApplicationContext(), MainActivity.class);
startActivity(backToMain);
finish();
}
}
MainActivity:
import android.content.Intent;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.support.v7.widget.Toolbar;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
public class MainActivity extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Toolbar myToolbar = (Toolbar) findViewById(R.id.my_toolbar);
setSupportActionBar(myToolbar);
}
#Override
public boolean onCreateOptionsMenu(Menu menu){
MenuInflater inflater = getMenuInflater();
inflater.inflate(R.menu.menu, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem menuItem){
switch(menuItem.getItemId()){
case(R.id.action_settings):
Intent startSettings = new Intent(MainActivity.this, SettingsActivity.class);
startActivity(startSettings);
return true;
case(R.id.about):
Intent startAbout = new Intent(MainActivity.this, AboutActivity.class);
startActivity(startAbout);
return true;
default:
return super.onOptionsItemSelected(menuItem);
}
}
#Override
public void onBackPressed(){
finish();
}
}
The AboutActivity and SettingsActivity don't contain anything yet, so I didn't include them in this post. I really don't know where the problem is though.
Restarting my phone and the NFC-setting solved the problem.

android search with suggestions

I want to make a search with suggestions.
after running the app and typing a string in my search box non of the following Logs Log.d("states","a onCreate"), Log.d("states",arg0.toString()), Log.d("states",query) or Log.d("states","searchactivity onCreate") execute.
What do I have to do do so the query() method in a.java or the onCreate() method in b.java are called?
Please dont send me to google developer documents its very confusing.
MainActivity.java
package com.example.searchapp;
import android.app.ActionBar;
import android.app.Activity;
import android.app.SearchManager;
import android.content.Context;
import android.os.Bundle;
import android.util.Log;
import android.view.Menu;
import android.view.MenuInflater;
import android.widget.SearchView;
public class MainActivity extends Activity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Log.d("states","MainActivity onCreate");
ActionBar actionBar = getActionBar();
//actionBar.setDisplayShowHomeEnabled(false);
actionBar.setDisplayShowTitleEnabled(false);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the options menu from XML
MenuInflater inflater = getMenuInflater();
inflater.inflate(R.menu.options_menu, menu);
// Get the SearchView and set the searchable configuration
SearchManager searchManager = (SearchManager) getSystemService(Context.SEARCH_SERVICE);
SearchView searchView = (SearchView) menu.findItem(R.id.action_search).getActionView();
// Assumes current activity is the searchable activity
searchView.setSearchableInfo(searchManager.getSearchableInfo(getComponentName()));
searchView.setIconifiedByDefault(false); // Do not iconify the widget; expand it by default
//searchView.setSubmitButtonEnabled(true);
searchView.setQueryRefinementEnabled(true);
return true;
}
}
a.java
package com.example.searchapp;
import android.content.ContentProvider;
import android.content.ContentValues;
import android.database.Cursor;
import android.net.Uri;
import android.util.Log;
public class a extends ContentProvider{
#Override
public int delete(Uri arg0, String arg1, String[] arg2) {
// TODO Auto-generated method stub
return 0;
}
#Override
public String getType(Uri arg0) {
// TODO Auto-generated method stub
return null;
}
#Override
public Uri insert(Uri arg0, ContentValues arg1) {
// TODO Auto-generated method stub
return null;
}
#Override
public boolean onCreate() {
// TODO Auto-generated method stub
Log.d("states","a onCreate");
return true;
}
#Override
public Cursor query(Uri arg0, String[] arg1, String arg2, String[] arg3,
String arg4) {
// TODO Auto-generated method stub
Log.d("states",arg0.toString());
String query = arg0.getLastPathSegment().toLowerCase();
Log.d("states",query);
return null;
}
#Override
public int update(Uri arg0, ContentValues arg1, String arg2, String[] arg3) {
// TODO Auto-generated method stub
return 0;
}
}
b.java
package com.example.searchapp;
import android.app.Activity;
import android.app.SearchManager;
import android.content.Intent;
import android.os.Bundle;
import android.util.Log;
public class b extends Activity {
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
Log.d("states","searchactivity onCreate");
Intent intent = getIntent();
if (Intent.ACTION_SEARCH.equals(intent.getAction())) {
String query = intent.getStringExtra(SearchManager.QUERY);
Log.d("states",query);
}
}
}
AndroidManifest.xml
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.example.searchapp"
android:versionCode="1"
android:versionName="1.0" >
<uses-sdk
android:minSdkVersion="14"
android:targetSdkVersion="20" />
<application
android:allowBackup="true"
android:icon="#drawable/ic_launcher"
android:label="#string/app_name"
android:theme="#style/AppTheme" >
<provider
android:name=".a"
android:authorities="com.example.searchapp.searchsuggestion">
</provider>
<activity
android:name=".MainActivity"
android:label="#string/app_name" >
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<activity android:name=".b">
<intent-filter>
<action android:name="android.intent.action.SEARCH" />
</intent-filter>
<meta-data android:name="android.app.searchable"
android:resource="#xml/searchable"/>
</activity>
</application>
</manifest>
searchable.xml
<?xml version="1.0" encoding="utf-8"?>
<searchable xmlns:android="http://schemas.android.com/apk/res/android"
android:label="app_label"
android:hint="Search in tags"
android:searchSuggestAuthority="com.example.searchapp.searchsuggestion"
android:searchSuggestIntentAction="android.intent.action.VIEW" >
</searchable>
I think in your a-class you have to implement the getType()-method:
private UriMatcher uriMatcher;
#Override
public boolean onCreate() {
final String authority = "com.example.searchapp.searchsuggestion";
uriMatcher = new UriMatcher(UriMatcher.NO_MATCH);
uriMatcher.addURI(authority, SearchManager.SUGGEST_URI_PATH_QUERY, SEARCH_SUGGEST);
uriMatcher.addURI(authority, SearchManager.SUGGEST_URI_PATH_QUERY + "/*", SEARCH_SUGGEST);
return true;
}
#Override
public String getType(Uri uri) {
switch (uriMatcher.match(uri)) {
case SEARCH_SUGGEST:
return SearchManager.SUGGEST_MIME_TYPE;
default:
throw new IllegalArgumentException("Unknown URL " + uri);
}
}

Force close null pointer error

When I launch a new activity I get this force close error:
03-01 22:44:32.752 2992-2992/com.example.mike.beerportfoliomaterial E/AndroidRuntime﹕ FATAL EXCEPTION: main
Process: com.example.mike.beerportfoliomaterial, PID: 2992
java.lang.RuntimeException: Unable to start activity ComponentInfo{com.example.mike.beerportfoliomaterial/com.example.mike.beerportfoliomaterial.MainDrawer2}: java.lang.NullPointerException
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2404)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2464)
at android.app.ActivityThread.access$900(ActivityThread.java:172)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1308)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:146)
at android.app.ActivityThread.main(ActivityThread.java:5653)
at java.lang.reflect.Method.invokeNative(Native Method)
at java.lang.reflect.Method.invoke(Method.java:515)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1291)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1107)
at dalvik.system.NativeStart.main(Native Method)
Caused by: java.lang.NullPointerException
at com.example.mike.beerportfoliomaterial.MainDrawer2.onCreate(MainDrawer2.java:72)
at android.app.Activity.performCreate(Activity.java:5539)
at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1093)
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2368)
            at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2464)
            at android.app.ActivityThread.access$900(ActivityThread.java:172)
            at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1308)
            at android.os.Handler.dispatchMessage(Handler.java:102)
            at android.os.Looper.loop(Looper.java:146)
            at android.app.ActivityThread.main(ActivityThread.java:5653)
            at java.lang.reflect.Method.invokeNative(Native Method)
            at java.lang.reflect.Method.invoke(Method.java:515)
            at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1291)
            at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1107)
            at dalvik.system.NativeStart.main(Native Method)
03-01 22:45:56.047 2992-2992/com.example.mike.beerportfoliomaterial I/Process﹕ Sending signal. PID: 2992 SIG: 9
My Android manifest looks like this:
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.example.mike.beerportfoliomaterial" >
<uses-feature
android:glEsVersion="0x00020000"
android:required="true"/>
<uses-permission android:name="android.permission.INTERNET"/>
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE"/>
<!-- Permission to write to external storage -->
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>
<uses-permission android:name="com.google.android.providers.gsf.permission.READ_GSERVICES"/>
<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION"/>
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION"/>
<uses-permission android:name="android.permission.CALL_PHONE" />
<application
android:allowBackup="true"
android:icon="#drawable/logo"
android:label="#string/app_name"
android:theme="#style/AppTheme" >
<activity android:label="#string/app_name" android:name="com.example.mike.beerportfoliomaterial.MainActivity">
<intent-filter>
<action android:name="android.intent.action.MAIN"/>
<category android:name="android.intent.category.LAUNCHER"/>
</intent-filter>
</activity>
<receiver android:name="com.example.mike.beerportfoliomaterial.HelloWidget" android:label="Beer of the Day">
<intent-filter> <action android:name="android.appwidget.action.APPWIDGET_UPDATE" />
<action android:name="android.appwidget.action.APPWIDGET_ENABLED" />
</intent-filter>
<meta-data android:name="android.appwidget.provider" android:resource="#xml/hello_widget_provider" />
</receiver>
<receiver android:name="com.example.mike.beerportfoliomaterial.SearchWidget" android:label="Search ">
<intent-filter>
<action android:name="android.appwidget.action.APPWIDGET_UPDATE" />
<action android:name="android.appwidget.action.APPWIDGET_ENABLED" />
</intent-filter>
<meta-data android:name="android.appwidget.provider" android:resource="#xml/search_widget" />
</receiver>
<activity android:label="#string/app_name" android:name="com.example.mike.beerportfoliomaterial.LogIn">
<intent-filter>
<category android:name="android.intent.category"/>
</intent-filter>
</activity>
<activity android:label="#string/app_name" android:name="com.example.mike.beerportfoliomaterial.Register" android:screenOrientation="portrait">
<intent-filter>
<category android:name="android.intent.category"/>
</intent-filter>
</activity>
<activity android:label="#string/app_name" android:name="com.example.mike.beerportfoliomaterial.MainDraw" android:screenOrientation="portrait">
<intent-filter>
<category android:name="android.intent.category"/>
</intent-filter>
</activity>
<activity android:label="#string/app_name" android:name="com.example.mike.beerportfoliomaterial.MainDrawer2" android:screenOrientation="portrait">
<intent-filter>
<category android:name="android.intent.category"/>
</intent-filter>
</activity>
<meta-data android:name="com.crashlytics.ApiKey" android:value="ffdabd920d55d93f21d643ae41d5f93fb21ed5c1"/>
<meta-data
android:name="com.google.android.maps.v2.API_KEY"
android:value="AIzaSyCCDcbrkc0SlZNCKCrGaYHXliLgB0BFB90"/>
</application>
</manifest>
My MainDrawer2 looks like this:
/////////////////////////////////////////////////
package com.example.mike.beerportfoliomaterial;
import android.IntentIntegrator;
import android.IntentResult;
import android.annotation.TargetApi;
import android.content.Context;
import android.content.Intent;
import android.content.res.Configuration;
import android.os.Build;
import android.os.Bundle;
import android.support.v4.app.ActionBarDrawerToggle;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentActivity;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentTransaction;
import android.support.v4.widget.DrawerLayout;
import android.support.v7.app.ActionBarActivity;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.AdapterView;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.Spinner;
import android.widget.Toast;
/**
* Created by Mike and Simon on 2/22/14.
*/
public class MainDrawer2 extends FragmentActivity
{
private static final String EXTRA_NAV_ITEM = "extraNavItem";
private static final String STATE_CURRENT_NAV = "stateCurrentNav";
private ActionBarDrawerToggle mDrawerToggle;
private DrawerLayout mDrawerLayout;
private NavDrawerListAdapter mDrawerAdapter;
private ListView mDrawerList;
private CharSequence mTitle;
private CharSequence mDrawerTitle;
private MainNavItem mCurrentNavItem;
public static Intent createLaunchFragmentIntent(Context context, MainNavItem navItem)
{
return new Intent(context, MainDrawer2.class)
.putExtra(EXTRA_NAV_ITEM, navItem.ordinal());
}
#Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.fragment_main);
//Crashlytics.start(this);
mTitle = mDrawerTitle = getTitle();
mDrawerLayout = (DrawerLayout)findViewById(R.id.drawer_layout);
mDrawerList = (ListView)findViewById(R.id.drawer);
getActionBar().setDisplayHomeAsUpEnabled(true);
enableHomeButtonIfRequired();
mDrawerAdapter = new NavDrawerListAdapter(getApplicationContext());
mDrawerList.setAdapter(mDrawerAdapter);
mDrawerList.setOnItemClickListener(new ListView.OnItemClickListener()
{
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id)
{
displayNavFragment((MainNavItem)parent.getItemAtPosition(position));
}
});
mDrawerToggle = new ActionBarDrawerToggle(this, mDrawerLayout,
R.drawable.ic_drawer, R.string.app_name, R.string.app_name)
{
public void onDrawerClosed(View view)
{
getActionBar().setTitle(mTitle);
invalidateOptionsMenu();
}
public void onDrawerOpened(View drawerView)
{
getActionBar().setTitle(mDrawerTitle);
invalidateOptionsMenu();
}
};
mDrawerLayout.setDrawerListener(mDrawerToggle);
if(getIntent().hasExtra(EXTRA_NAV_ITEM)){
MainNavItem navItem = MainNavItem.values()
[getIntent().getIntExtra(EXTRA_NAV_ITEM,
MainNavItem.STATISTICS.ordinal())];
displayNavFragment(navItem);
}
else if(savedInstanceState != null){
mCurrentNavItem = MainNavItem.values()
[savedInstanceState.getInt(STATE_CURRENT_NAV)];
setCurrentNavItem(mCurrentNavItem);
}
else{
displayNavFragment(MainNavItem.STATISTICS);
}
}
#TargetApi(Build.VERSION_CODES.ICE_CREAM_SANDWICH)
private void enableHomeButtonIfRequired()
{
if(Build.VERSION.SDK_INT >= Build.VERSION_CODES.ICE_CREAM_SANDWICH){
getActionBar().setHomeButtonEnabled(true);
}
}
public void setActionBarTitle(String title) {
getActionBar().setTitle(title);
}
#Override
public void setTitle(CharSequence title)
{
mTitle = title;
getActionBar().setTitle(mTitle);
}
#Override
protected void onPostCreate(Bundle savedInstanceState)
{
super.onPostCreate(savedInstanceState);
// Sync the toggle state after onRestoreInstanceState has occurred.
mDrawerToggle.syncState();
}
#Override
public void onConfigurationChanged(Configuration newConfig)
{
super.onConfigurationChanged(newConfig);
// Pass any configuration change to the drawer toggles
mDrawerToggle.onConfigurationChanged(newConfig);
}
#Override
protected void onSaveInstanceState(Bundle outState)
{
super.onSaveInstanceState(outState);
if (mCurrentNavItem == null){
}
else{
outState.putInt(STATE_CURRENT_NAV, mCurrentNavItem.ordinal());
}
}
#Override
public boolean onCreateOptionsMenu(Menu menu)
{
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
/*
#Override
public boolean onPrepareOptionsMenu(Menu menu)
{
// if nav drawer is opened, hide the action items
boolean drawerOpen = mDrawerLayout.isDrawerOpen(mDrawerList);
menu.findItem(R.id.action_settings).setVisible(!drawerOpen);
return super.onPrepareOptionsMenu(menu);
}
*/
private void displayNavFragment(MainNavItem navItem)
{
//if(navItem == mCurrentNavItem){
// return;
//}
Fragment fragment = Fragment.instantiate(this,
navItem.getFragClass().getName());
if(fragment != null){
getSupportFragmentManager().beginTransaction()
.replace(R.id.main, fragment)
.commit();
setCurrentNavItem(navItem);
}
}
private void setCurrentNavItem(MainNavItem navItem)
{
int position = navItem.ordinal();
// If navItem is in DrawerAdapter
if(position >= 0 && position < mDrawerAdapter.getCount()){
//mDrawerList.setItemChecked(position, true);
}
else{
// navItem not in DrawerAdapter, de-select current item
if(mCurrentNavItem != null){
//mDrawerList.setItemChecked(mCurrentNavItem.ordinal(), false);
}
}
//test to keep item not selected
int toClear=mDrawerList.getCheckedItemPosition();
if (toClear >= 0) {
mDrawerList.setItemChecked(toClear, false);
}
mDrawerLayout.closeDrawer(mDrawerList);
setTitle(navItem.getTitleResId());
mCurrentNavItem = navItem;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case android.R.id.home:
if(mDrawerLayout.isDrawerOpen(mDrawerList)) {
mDrawerLayout.closeDrawer(mDrawerList);
}
else {
mDrawerLayout.openDrawer(mDrawerList);
}
return true;
default:
return super.onOptionsItemSelected(item);
}
}
public void goToSearch(MenuItem item){
//go to search page
Fragment Fragment_one;
FragmentManager man= getSupportFragmentManager();
FragmentTransaction tran = man.beginTransaction();
Fragment_one = new Search();
tran.replace(R.id.main, Fragment_one);//tran.
tran.addToBackStack(null);
tran.commit();
}
public void scanBarcode(MenuItem item){
//open scanner
IntentIntegrator scanIntegrator = new IntentIntegrator(this);
scanIntegrator.initiateScan();
}
public void onActivityResult(int requestCode, int resultCode, Intent intent) {
//retrieve scan result
IntentResult scanningResult = IntentIntegrator.parseActivityResult(requestCode, resultCode, intent);
if (scanningResult != null) {
//we have a result
String scanContent = scanningResult.getContents();
//todo: set scan content into setting, load new fragment which calls async task below. New
//todo: fragment will have same ui as search. :-)
Fragment Fragment_one;
FragmentManager man= this.getSupportFragmentManager();
FragmentTransaction tran = man.beginTransaction();
BarcodeFrag fragmentNew = new BarcodeFrag();
Bundle bundle = new Bundle();
bundle.putString("scanContent", scanContent);
fragmentNew.setArguments(bundle);
tran.replace(R.id.main, fragmentNew);//tran.
tran.addToBackStack(null);
//tran.commit();
tran.commitAllowingStateLoss();
}
else{
Toast toast = Toast.makeText(getApplicationContext(),
"No scan data received!", Toast.LENGTH_SHORT);
toast.show();
}
}
}
public class MainDrawer2 extends ActionBarActivity
try extending ActionBarActivity.it extends to fragment activity itself.So you do not need to worry about fragment activity.
Hope it will help.
As i can see you have not pass the drawer item list to NavDrawerListAdapter.
so where are you setting your drawer items?

Nothing happens when pressing Enter while searching using Android Search widget

I am trying to implement the search widget in android but unsuccessful. It lets me type the query text in the seacrh textbox but nothing happens when I press Enter. I followed the tutorial very closely http://developer.android.com/training/search/setup.html. But I can't fix the problem. I've been trying everything for 6 hours now. Please help!
Here is my Android manifest file:
<uses-sdk
android:minSdkVersion="11"
android:targetSdkVersion="19" />
<application
android:allowBackup="true"
android:icon="#drawable/ic_launcher"
android:label="#string/app_name"
android:theme="#style/Theme.Sherlock">
<meta-data android:name="android.app.default_searchable"
android:value="com.example.pt_labguide.SearchableActivity" />
<activity
android:name="com.example.pt_labguide.MainActivity"
android:label="#string/app_name" >
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<activity android:name=".BasicMetabolicPanelActivity"
android:label="#string/basic_metab_panel" >
<intent-filter>
<action android:name="com.example.pt_labguide.BasicMetabolicPanelActivity"/>
<category android:name="android.intent.category.DEFAULT" />
</intent-filter>
</activity>
<activity android:name=".ArterialBloodGasActivity"
android:label="#string/arterial_blood_gases" >
<intent-filter>
<action android:name="com.example.pt_labguide.ArterialBloodGasActivity" />
<category android:name="android.intent.category.DEFAULT" />
</intent-filter>
</activity>
<activity android:name=".DisplayLabValueActivity">
<intent-filter>
<action android:name="com.example.pt_labguide.DisplayLabValueActivity" />
<category android:name="android.intent.category.DEFAULT" />
</intent-filter>
</activity>
<activity android:name=".SearchableActivity">
<intent-filter>
<action android:name="com.example.pt_labguide.SearchableActivity" />
<category android:name="android.intent.action.SEARCH" />
</intent-filter>
<meta-data android:name="android.app.searchable"
android:resource="#xml/searchable" />
</activity>
</application>
</manifest>
****Here is the Searchable activity:****
package com.example.pt_labguide;
import android.app.SearchManager;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.util.Log;
import com.actionbarsherlock.app.SherlockFragmentActivity;
import com.actionbarsherlock.view.Menu;
import com.actionbarsherlock.view.MenuInflater;
import com.actionbarsherlock.widget.SearchView;
public class SearchableActivity extends SherlockFragmentActivity {
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.about);
handleIntent(getIntent());
}
#Override
protected void onNewIntent(Intent intent) {
handleIntent(intent);
Log.d("SearchResultsActivity", "onNewIntent called");
}
private void handleIntent(Intent intent) {
if (Intent.ACTION_SEARCH.equals(intent.getAction())) {
String query = intent.getStringExtra(SearchManager.QUERY);
doMySearch(query);
Log.d("SearchResultsActivity", query);
}
}
private void doMySearch(String query){
Intent intent = new Intent("com.example.pt_labguide.DisplayLabValueActivity");
intent.putExtra("labValue", query);
startActivity(intent);
}
}
**Here is the Main activity:**
package com.example.pt_labguide;
import android.app.Fragment;
import android.app.SearchManager;
import android.content.Context;
import android.os.Bundle;
import android.support.v4.app.FragmentTransaction;
import android.widget.Button;
import com.actionbarsherlock.app.ActionBar;
import com.actionbarsherlock.app.ActionBar.Tab;
import com.actionbarsherlock.app.SherlockFragment;
import com.actionbarsherlock.app.SherlockFragmentActivity;
import com.actionbarsherlock.view.Menu;
import com.actionbarsherlock.view.MenuInflater;
import com.actionbarsherlock.widget.SearchView;
import android.view.View;
import android.content.Intent;
public class MainActivity extends SherlockFragmentActivity{
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
// Notice that setContentView() is not used, because we use the root
// android.R.id.content as the container for each fragment
// setup action bar for tabs
ActionBar actionBar = getSupportActionBar();
actionBar.setNavigationMode(ActionBar.NAVIGATION_MODE_TABS);
actionBar.setDisplayShowTitleEnabled(true);
Tab tab = actionBar.newTab()
.setText(R.string.list)
.setTabListener(new TabListener<ListFragment>(
this, "list", ListFragment.class));
actionBar.addTab(tab);
tab = actionBar.newTab()
.setText(R.string.categories)
.setTabListener(new TabListener<CategoryFragment>(
this, "category", CategoryFragment.class));
actionBar.addTab(tab);
tab = actionBar.newTab()
.setText(R.string.favorites)
.setTabListener(new TabListener<FavoriteFragment>(
this, "favorite", FavoriteFragment.class));
actionBar.addTab(tab);
tab = actionBar.newTab()
.setText(R.string.about)
.setTabListener(new TabListener<AboutFragment>(
this, "about", AboutFragment.class));
actionBar.addTab(tab);
}
static class TabListener<T extends SherlockFragment> implements ActionBar.TabListener {
private android.support.v4.app.Fragment mFragment;
private final SherlockFragmentActivity mActivity;
private final String mTag;
private final Class<T> mClass;
/** Constructor used each time a new tab is created.
* #param activity The host Activity, used to instantiate the fragment
* #param tag The identifier tag for the fragment
* #param clz The fragment's Class, used to instantiate the fragment
*/
public TabListener(SherlockFragmentActivity activity, String tag, Class<T> clz) {
mActivity = activity;
mTag = tag;
mClass = clz;
}
/* The following are each of the ActionBar.TabListener callbacks */
public void onTabSelected(Tab tab, FragmentTransaction ft) {
// Check if the fragment is already initialized
if (mFragment == null) {
// If not, instantiate and add it to the activity
mFragment = SherlockFragment.instantiate(mActivity, mClass.getName());
ft.add(android.R.id.content, mFragment, mTag);
} else {
// If it exists, simply attach it in order to show it
ft.attach(mFragment);
}
}
public void onTabUnselected(Tab tab, FragmentTransaction ft) {
if (mFragment != null) {
// Detach the fragment, because another one is being attached
ft.detach(mFragment);
}
}
public void onTabReselected(Tab tab, FragmentTransaction ft) {
// User selected the already selected tab. Usually do nothing.
}
}//end inner class
#Override
public boolean onSearchRequested() {
return super.onSearchRequested();
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
MenuInflater inflater = getSupportMenuInflater();
inflater.inflate(R.menu.search, menu);
// Associate searchable configuration with the SearchView
SearchManager searchManager =
(SearchManager) getSystemService(Context.SEARCH_SERVICE);
SearchView searchView =
(SearchView) menu.findItem(R.id.menu_search).getActionView();
searchView.setSearchableInfo(
searchManager.getSearchableInfo(getComponentName()));
searchView.setIconifiedByDefault(false);
return true;
}
public void display_BMP (View view) {
startActivity(new Intent("com.example.pt_labguide.BasicMetabolicPanelActivity"));
}
public void display_ABG (View view) {
startActivity(new Intent("com.example.pt_labguide.ArterialBloodGasActivity"));
}
public void display_LabValue (View view) {
String name = ((Button) view).getText().toString();
Intent intent = new Intent("com.example.pt_labguide.DisplayLabValueActivity");
intent.putExtra("labValue", name);
startActivity(intent);
}
}//end class TabDemo
**Here is the menu/search.xml:**
<?xml version="1.0" encoding="utf-8"?>
<menu xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:com.example.pt_labguide="http://schemas.android.com/apk/res-auto">
<item android:id="#+id/menu_search"
android:title="#string/search_hint"
android:icon="#drawable/ic_search_lens"
android:showAsAction="collapseActionView|ifRoom"
android:actionViewClass="com.actionbarsherlock.widget.SearchView" />
</menu>
**Here is the raw/xml/searchable.xml:**
<?xml version="1.0" encoding="utf-8"?>
<searchable xmlns:android="http://schemas.android.com/apk/res/android"
android:label="#string/app_name"
android:hint="#string/search_hint" >
</searchable>

Categories

Resources