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>
Related
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;
}
}
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
I create search Interface in the toolbar , every thing is good and when i press the back button in toolbar , it work's good and get back to main activity , but when i press the hardware back button , i have to press several times until get back to the main activity :
this is my MainActivity :
import android.app.SearchManager;
import android.content.Context;
import android.os.Bundle;
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.MenuItem;
import app.bahaltarinha.com.R;
public class MainActivity extends AppCompatActivity {
//===================================================== onCreateMethod()
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
//setupToolbar
setUpToolbar();
}
//===================================================== setupToolbar Method()
private void setUpToolbar() {
Toolbar mainToolbar = (Toolbar)findViewById(R.id.xmlToolbarMain);
setSupportActionBar(mainToolbar);
getSupportActionBar().setDisplayShowTitleEnabled(false);
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
getSupportActionBar().setHomeAsUpIndicator(R.mipmap.ic_menu);
}
//===================================================== onCreateOptionsMenu Method()
#Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.menu_main , menu);
SearchManager searchManager = (SearchManager) getSystemService(Context.SEARCH_SERVICE);
MenuItem searchItem = menu.findItem(R.id.action_search_toolbar);
SearchView searchView = (SearchView) MenuItemCompat.getActionView(searchItem);
searchView.setSearchableInfo(searchManager.getSearchableInfo(getComponentName()));
searchView.setIconifiedByDefault(true);
return true;
}
//===================================================== onOptionsItemSelected Method()
#Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()){
case R.id.action_search_toolbar:
return true;
default:
return super.onOptionsItemSelected(item);
}
}
}
and this is the SearchResultActivity:
import android.app.SearchManager;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
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.MenuItem;
import android.widget.TextView;
import app.bahaltarinha.com.R;
/**
* Created by majid on 1/8/2016.
*/
public class SearchResultsActivity extends AppCompatActivity {
private TextView txtSearchQuery;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_result);
setUpToolbar();
txtSearchQuery = (TextView)findViewById(R.id.txtSearchQuery);
handleIntent(getIntent());
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.menu_main, menu);
SearchManager searchManager = (SearchManager) getSystemService(Context.SEARCH_SERVICE);
MenuItem searchItem = menu.findItem(R.id.action_search_toolbar);
SearchView searchView = (SearchView) MenuItemCompat.getActionView(searchItem);
searchView.setSearchableInfo(searchManager.getSearchableInfo(getComponentName()));
searchView.setIconifiedByDefault(true);
return true;
}
private void setUpToolbar() {
Toolbar mainToolbar = (Toolbar)findViewById(R.id.xmlToolbarSearchActivity);
setSupportActionBar(mainToolbar);
getSupportActionBar().setDisplayShowTitleEnabled(false);
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
}
#Override
protected void onNewIntent(Intent intent) {
handleIntent(intent);
}
private void handleIntent(Intent intent) {
if(Intent.ACTION_SEARCH.equals(intent.getAction())){
String query = intent.getStringExtra(SearchManager.QUERY);
doSearchQuery(query);
}
}
private void doSearchQuery(String query) {
txtSearchQuery.setText(query);
}
#Override
public void onBackPressed() {
super.onBackPressed();
this.finish();
}
}
and this is androidManifest:
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="app.bahaltarinha.com">
<application
android:allowBackup="true"
android:icon="#mipmap/ic_launcher"
android:label="#string/app_name"
android:supportsRtl="true"
android:theme="#style/AppTheme">
<!-- MainActivity -->
<activity android:name=".activities.MainActivity">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
<meta-data
android:name="android.app.default_searchable"
android:value=".activities.SearchResultsActivity"/>
</activity>
<!-- Search Results Activity -->
<activity
android:name=".activities.SearchResultsActivity"
android:label="#string/app_name"
android:parentActivityName=".activities.MainActivity">
<intent-filter>
<action android:name="android.intent.action.SEARCH"/>
<category android:name="android.intent.category.DEFAULT"/>
</intent-filter>
<meta-data
android:name="android.app.searchable"
android:resource="#xml/searchable"/>
</activity>
</application>
</manifest>
Try removing the below code from your SearchResultsActivity.JAVA. You no need to define it. By default System will automatically finish the current activity when you press back.
#Override
public void onBackPressed() {
super.onBackPressed();
this.finish();
}
and there is not need of intent filter in the Manifest for this activity. Kindly remove them too.
<intent-filter>
<action android:name="android.intent.action.SEARCH"/>
<category android:name="android.intent.category.DEFAULT"/>
</intent-filter>
Hope this will help you..!!
Ok , i find the solution and we should use intent for that :
we should write in onBackPressed() in SearchResultActivity:
#Override
public void onBackPressed() {
startActivity(new Intent(SearchResultsActivity.this , MainActivity.class));
}
I am trying to learn android, I create, deploy app using ant based CLI.
My manifest file is as follows
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.example.frag"
android:versionCode="1"
android:versionName="1.0">
<uses-sdk
android:minSdkVersion="14"
android:targetSdkVersion="21" />
<application android:label="#string/app_name" android:icon="#drawable/ic_launcher" android:theme="#android:style/Theme.Holo">
<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>
</application>
</manifest>
I added a menu xml file in by creating res\menu\items.xml
<?xml version="1.0" encoding="utf-8"?>
<menu xmlns:android="http://schemas.android.com/apk/res/android">
<item
android:id="#+id/action_share"
android:title="Share it"
>
</item>
</menu>
If I now compile using ant debug, then run the app, the app crashes. Any ideas?
Following is the activity code, it does not uses Menu as of now.
package com.example.frag;
import android.app.Activity;
import android.app.ActionBar;
import android.os.Bundle;
import android.app.ActionBar.Tab;
import android.app.FragmentTransaction;
import android.support.v4.app.FragmentActivity;
import android.support.v4.view.ViewPager;
//import android.support.v4.view.Menu;
//import android.support.v4.view.MenuInflater;
public class MainActivity extends FragmentActivity implements ActionBar.TabListener
{
private ActionBar actionBar;
private ViewPager viewPager;
private TabPagerAdapter tabPagerAdapter;
private String[] tabs = { "Mouse", "Keyboard"};
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
viewPager = (ViewPager) findViewById (R.id.pager);
tabPagerAdapter = new TabPagerAdapter (getSupportFragmentManager());
viewPager.setAdapter (tabPagerAdapter);
actionBar = getActionBar();
//actionBar.setHasOptionsMenu (true);
actionBar.setNavigationMode(ActionBar.NAVIGATION_MODE_TABS);
for (String tab_name : tabs) {
actionBar.addTab(actionBar.newTab().setText(tab_name).setTabListener(this));
}
viewPager.setOnPageChangeListener(new ViewPager.OnPageChangeListener() {
/**
* on swipe select the respective tab
* */
#Override
public void onPageSelected(int position) {
actionBar.setSelectedNavigationItem(position);
}
#Override
public void onPageScrolled(int arg0, float arg1, int arg2) { }
#Override
public void onPageScrollStateChanged(int arg0) { }
});
}
#Override
public void onTabReselected(Tab tab, FragmentTransaction ft) { }
#Override
public void onTabSelected(Tab tab, FragmentTransaction ft) {
viewPager.setCurrentItem(tab.getPosition());
}
#Override
public void onTabUnselected(Tab tab, FragmentTransaction ft) {}
/*#Override
public boolean onCreateOptionsMenu(Menu menu)
{
MenuInflater inflater = getMenuInflater();
inflater.inflate (R.menu.items, menu);
return super.onCreateOptionsMenu (menu);
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
super.onOptionsItemSelected(item);
return true;
}*/
}
UPDATE
I removed menu resources, then tried adding styles.xml in values/, recompiled, launched and it crashed again.
My Main Activity class is as follows
package com.example.barnight2;
import java.text.SimpleDateFormat;
import java.util.Date;
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.TextView;
public class MainActivity extends Activity {
private TextView date;
private Button taxiButton;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
addListenerOnButton();
dateAndTime();
}
public void addListenerOnButton() {
taxiButton = (Button) findViewById(R.id.btnTaxi);
taxiButton.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
Intent taxiIntent = new Intent(MainActivity.this, TaxiActivity.class);
startActivity(taxiIntent);
}
});
}
public void dateAndTime() {
date = (TextView) findViewById(R.id.lblDate);
SimpleDateFormat sdf = new SimpleDateFormat("EEEE");
Date day = new Date();
String dayOfTheWeek = sdf.format(day);
date.setText(dayOfTheWeek);
}
}
then i have my second activity called the Taxi Activity
package com.example.barnight2;
import android.os.Bundle;
import android.app.Activity;
import android.view.Menu;
public class TaxiActivity extends Activity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_taxi);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.taxi, menu);
return true;
}
}
Here is my Manifest.xml i thought i had done everything perfectly but it seems to always crash upon start up of the app
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.example.barnight2"
android:versionCode="1"
android:versionName="1.0" >
<uses-sdk
android:minSdkVersion="8"
android:targetSdkVersion="19" />
<application
android:allowBackup="true"
android:icon="#drawable/ic_launcher"
android:label="#string/app_name"
android:theme="#style/AppTheme" >
<activity
android:name="com.example.barnight2.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="com.example.barnight2.TaxiActivity" >
<intent-filter>
<action android:name="android.intent.action.MAIN" />
</intent-filter>
</activity>
</application>
</manifest>
![image]http://i62.tinypic.com/16rma8.png
ClassCastException
you're casting an object that it's not the same type you're trying to cast, so that's why it throw a RunTimeException with ClassCastException.
It should be:
taxiButton = (ImageButton) findViewById(R.id.btnTaxi);
Since you declared it as ImageButton in xml.
Please remove :
<intent-filter>
<action android:name="android.intent.action.MAIN" />
</intent-filter>
from your activity com.example.barnight2.TaxiActivity in the AndroidManifest.xml