How to Implement Google Search in Android SearchView - android

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

Related

Cannot start Activity from action bar menu even though i have added the activity element in manifest file

I am starting the activity after clicking on menu item in the action bar menu.
I have added the activity in manifest file also . I cannot find why there is ActivityNotFoundException. I have used intent to start new Activity. FragmentActivity extends Activity.
MANIFEST FILE:
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.example.android.myapplication">
<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">
<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="com.example.android.myapplication.FragmentActivity"
android:label="#string/app_name"></activity>
</application>
</manifest>
MAIN ACTIVITY FILE:
package com.example.android.myapplication;
import android.app.Activity;
import android.content.ActivityNotFoundException;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v4.app.FragmentActivity;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.app.AppCompatCallback;
import android.support.v7.app.AppCompatDelegate;
import android.support.v7.view.ActionMode;
import android.support.v7.widget.Toolbar;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.widget.EditText;
import android.widget.Toast;
public class MainActivity extends Activity implements AppCompatCallback{
private SharedPreferences mSharedPreferences;
private SharedPreferences.Editor mEditor;
private EditText mEditTextName;
private EditText mEditTextEmail;
private EditText mEditTextPhone;
private Context context;
Toast mToast;
Intent mIntent;
// private String mPreferenceFileName = getString(R.string.preference_file_key);
// private String mNameKey = this.getString(R.string.name_key);
// private String mPhoneKey = this.getString(R.string.phone_key);
//private String mEmailKey = this.getString(R.string.email_key);
#Override
public void onSupportActionModeStarted(ActionMode mode) {}
#Override
public void onSupportActionModeFinished(ActionMode mode) {}
#Nullable
#Override
public ActionMode onWindowStartingSupportActionMode(ActionMode.Callback callback) {
return null;
}
private AppCompatDelegate delegate;
#Override
protected void onCreate(Bundle savedInstanceState) {
delegate = AppCompatDelegate.create(this, this);
delegate.installViewFactory();
super.onCreate(savedInstanceState);
delegate.onCreate(savedInstanceState);
delegate.setContentView(R.layout.activity_main);
Toolbar toolbar=(Toolbar) findViewById(R.id.app_bar);
delegate.setSupportActionBar(toolbar);
mSharedPreferences = this.getSharedPreferences("myFile" , Context.MODE_PRIVATE);
mEditor = mSharedPreferences.edit();
mEditTextName = (EditText)findViewById(R.id.name);
mEditTextPhone = (EditText)findViewById(R.id.phone);
mEditTextEmail= (EditText)findViewById(R.id.email);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.menu, menu);
return super.onCreateOptionsMenu(menu);
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
switch(item.getItemId()){
case R.id.save:
mEditor.putString( "mNameKey",mEditTextName.getText().toString());
mEditor.putString( "mEmailKey",mEditTextPhone.getText().toString());
mEditor.putString( "mPhoneKey",mEditTextEmail.getText().toString());
mEditor.apply();
mToast = Toast.makeText(this,"saved",Toast.LENGTH_LONG);
mToast.show();
break;
case R.id.Clear:
mEditTextName.setText("");
mEditTextEmail.setText("");
mEditTextPhone.setText("");
mToast = Toast.makeText(this,"Cleared",Toast.LENGTH_LONG);
mToast.show();
break;
case R.id.retrieve:
if(mSharedPreferences.contains("mNameKey")){
mEditTextName.setText(mSharedPreferences.getString("mNameKey",""));
}
if(mSharedPreferences.contains("mEmailKey")){
mEditTextEmail.setText(mSharedPreferences.getString("mEmailKey",""));
}
if(mSharedPreferences.contains("mPhoneKey")){
mEditTextPhone.setText(mSharedPreferences.getString("mPhoneKey",""));
}
mToast = Toast.makeText(this,"Retrieved",Toast.LENGTH_LONG);
mToast.show();
break;
case R.id.FragementActivity:
// HERE I CALL THE NEW ACTIVITY
try {
mIntent = new Intent(MainActivity.this, FragmentActivity.class);
this.startActivity(mIntent);
}catch(ActivityNotFoundException e){
e.printStackTrace();
Log.i("tag","exception");
}
}
return super.onOptionsItemSelected(item);
}
}
When i click on the FragmentActivity menu item I cannot start the new activity. Is it not possible to start new activity this way? Is there some alternative?
as #Mike M. already mentioned, you are trying to open FragmentActivity from the support package instead of your package, hence the issue
Solution :
You have to remove this import
import android.support.v4.app.FragmentActivity;
and import your activity carefully.
you can use setAction as
mIntent = new Intent();
intent.setAction("com.example.android.myapplication.FragmentActivity");
this.startActivity(mIntent);
Note : For second solution , To avoid the user to select app to complete the action, you need to add DEFAULT as category along with intent-filter for FragmentActivity
No need of changing the class name or no need of removing this :-
import android.support.v4.app.FragmentActivity;
Instead write your full qualified class ( yourPackagename.FragmentActivity )name like
(MainActivity.this,com.example.android.myapplication.FragmentActivity.class );
in the explicit intent call !!

Can't display my custom suggestion using SearchView

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

PermissionUtils cannot be resolved

I'm working on an app that will allow users to report potholes and other roadside issues easily. My specific issue is in the map I included; in the report activity that will allow users to pinpoint where the problem is by using google maps and some markers. To do this I'm basically copying code word for word from the google maps api and my problem is that the permission utils object isn't being inherited from google play services. I had put this code down for a while (out of frustration) so i dont exactly remember what the other issues were but i remember getting the code around permission utils to not give me an error was kind of a bitch. Anyway so please help ;_;. I apologize for how i space my code, it is just visually easier for me, the first block is the message activity, the second is my manifest. please let me know if I should post anything else.
package com.example.fixmytown;
import java.util.List;
import com.google.android.gms.common.api.GoogleApiClient;
import com.google.android.gms.location.LocationServices;
import com.google.android.gms.maps.GoogleMap;
import com.google.android.gms.maps.GoogleMap.OnMyLocationButtonClickListener;
import com.google.android.gms.maps.MapFragment;
import com.google.android.gms.maps.OnMapReadyCallback;
import com.google.android.gms.maps.model.LatLng;
import com.google.android.gms.maps.model.MarkerOptions;
import android.Manifest;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.os.Bundle;
import android.support.v4.app.FragmentActivity;
import android.support.v4.content.ContextCompat;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.EditText;
import android.widget.Toast;
import com.google.android.gms.maps.SupportMapFragment;
import android.support.annotation.NonNull;
import android.support.v4.app.ActivityCompat;
import android.support.v7.app.AppCompatActivity;
public class Message extends FragmentActivity implements OnMyLocationButtonClickListener,
OnMapReadyCallback,
ActivityCompat.OnRequestPermissionsResultCallback {
private static final int LOCATION_PERMISSION_REQUEST_CODE = 1;
private boolean mPermissionDenied = false;
private GoogleMap mMap;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.maps_frag);
MapFragment mapFragment = (MapFragment) getFragmentManager()
.findFragmentById(R.id.map);
mapFragment.getMapAsync(this);
//----------------------------[Don't Mess with the above]------------------------------------------------------------
android.app.ActionBar actionBar = getActionBar();
//-------------------------------------------------------------------------------------------------------------------
//you were trying to figure out why the action bar isnt changing title. beinga bitch
String subject = " ";
if (Black.activityType == 1){
subject = "Pothole";
}
else if (Black.activityType == 2){
subject = "Roadkill";
}
else if (Black.activityType == 3){
subject = "Pollution";
}
else if(Black.activityType == 4){
// getActionBar().setTitle("Email Public Servant ");
}
}
//-------------------------------------------------------------------------------------------------------------------
#Override
public void onMapReady(GoogleMap map) {
mMap = map;
mMap.setOnMyLocationButtonClickListener(this);
enableMyLocation();
}
private void enableMyLocation() {
if (ContextCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION)
!= PackageManager.PERMISSION_GRANTED) {
// Permission to access the location is missing.
PermissionUtils.requestPermission(this, LOCATION_PERMISSION_REQUEST_CODE,
Manifest.permission.ACCESS_FINE_LOCATION, true);
} else if (mMap != null) {
// Access to the location has been granted to the app.
mMap.setMyLocationEnabled(true);
}
}
//-------------------------------------------------------------------------------------------------------------------
public void sendMessage(View view) {
EditText text = (EditText)findViewById(R.id.MessageText);
String Description = text.getText().toString();
String subject = "";
if (Black.activityType == 1){
subject = "Pothole";
}
else if (Black.activityType == 2){
subject = "Roadkill";
}
else if (Black.activityType == 3){
subject = "Pollution";
}
else if(Black.activityType == 4){
// getActionBar().setTitle("Email Public Servant ");
}
//-------------------------------------------------------------------------------------------------------------------
//email ability
Intent i = new Intent(Intent.ACTION_SEND);
i.setType("message/rfc822");
i.putExtra(Intent.EXTRA_EMAIL , new String[]{"mckippy#gmail.com"});
i.putExtra(Intent.EXTRA_SUBJECT, subject);
i.putExtra(Intent.EXTRA_TEXT , Description);
try {
startActivity(Intent.createChooser(i, "Send mail..."));
} catch (android.content.ActivityNotFoundException ex) {
Toast.makeText(Message.this, "There are no email clients installed.", Toast.LENGTH_SHORT).show();
}
}
//-------------------------------------------------------------------------------------------------------------------
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.message, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
#Override
public boolean onMyLocationButtonClick() {
// TODO Auto-generated method stub
return false;
}
}
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.example.fixmytown"
android:versionCode="1"
android:versionName="1.0" >
<uses-permission android:name="com.google.android.providers.gsf.permisson.READ_GSERVICES"/>
<uses-permission
android:name="android.permission.ACCESS_NETWORK_STATE" />
<uses-permission
android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION"/>
<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION"/>
<uses-sdk
android:minSdkVersion="11"
android:targetSdkVersion="21" />
<application
android:allowBackup="true"
android:icon="#drawable/ic_launcher"
android:label="#string/app_name"
android:theme="#style/AppTheme" >
<activity
android:screenOrientation="portrait"
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:screenOrientation="portrait"
android:name=".Black"
android:label="#string/title_activity_black" >
</activity>
<activity
android:screenOrientation="portrait"
android:name=".Green"
android:configChanges="orientation|keyboardHidden|screenSize"
android:label="#string/title_activity_green"
android:theme="#style/FullscreenTheme" >
</activity>
<activity
android:screenOrientation="portrait"
android:name=".Message"
android:label="#string/title_activity_message" >
</activity>
<meta-data
android:name="com.google.android.gms.version"
android:value="#integer/google_play_services_version" />
<meta-data
android:name="com.google.android.geo.API_KEY"
android:value="AIzaSyA0e26vc4-YGqmvOQSA6lQfnZyt3dmmbek"/>
</application>
</manifest>

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.

back button don't close the search result activity and i have to press several times to get back to mainActivity

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

Categories

Resources