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?
Related
Synposis: I have 3 activity (LoginActivity, MainActivity and EditProfileActivity). After Facebook login in my LoginActivity I srart the MainActivity. (Till this point the app is working perfectly correct with no error). I have a NavigationDrawer for my navigations, When I click on Edit Profile link from the NavigationDrawer it starts the EditProfileActivity.
Problem: When I click on the LeftArrow in the Top blue bar, the app crashes.
Please see the images:
MainActivity
Navigation Drawer
EditProfileActivity
App Crash on clicking the top left arrow
Here is my Manifest.xml
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.example.example">
<uses-permission android:name="android.permission.INTERNET" />
<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/AppTheme">
<meta-data
android:name="com.facebook.sdk.ApplicationId"
android:value="#string/facebook_app_id" />
<activity
android:name="com.facebook.FacebookActivity"
android:configChanges="keyboard|keyboardHidden|screenLayout|screenSize|orientation"
android:label="#string/app_name" />
<activity
android:name="com.facebook.CustomTabActivity"
android:exported="true">
<intent-filter>
<action android:name="android.intent.action.VIEW" />
<category android:name="android.intent.category.DEFAULT" />
<category android:name="android.intent.category.BROWSABLE" />
<data android:scheme="#string/fb_login_protocol_scheme" />
</intent-filter>
</activity>
<activity android:name=".LoginActivity">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<provider
android:name="com.facebook.FacebookContentProvider"
android:authorities="com.facebook.app.FacebookContentProvider"
android:exported="true" />
<activity
android:name=".MainActivity"
android:label="#string/title_activity_main"
android:theme="#style/AppTheme.NoActionBar">
</activity>
<activity android:name=".EditProfileActivity"
android:parentActivityName=".MainActivity" >
<!-- The meta-data tag is required if you support API level 15 and lower -->
<meta-data
android:name="android.support.PARENT_ACTIVITY"
android:value=".MainActivity" />
</activity>
</application>
</manifest>
Here is my MainActivity.java
package com.example.example;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.AsyncTask;
import android.os.Bundle;
import android.support.design.widget.FloatingActionButton;
import android.support.design.widget.Snackbar;
import android.util.Log;
import android.view.View;
import android.support.design.widget.NavigationView;
import android.support.v4.view.GravityCompat;
import android.support.v4.widget.DrawerLayout;
import android.support.v7.app.ActionBarDrawerToggle;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.view.Menu;
import android.view.MenuItem;
import android.widget.ImageView;
import android.widget.TextView;
import java.io.InputStream;
public class MainActivity extends AppCompatActivity
implements NavigationView.OnNavigationItemSelectedListener {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
FloatingActionButton fab = (FloatingActionButton) findViewById(R.id.fab);
fab.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Snackbar.make(view, "Replace with your own action", Snackbar.LENGTH_LONG)
.setAction("Action", null).show();
}
});
DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
ActionBarDrawerToggle toggle = new ActionBarDrawerToggle(
this, drawer, toolbar, R.string.navigation_drawer_open, R.string.navigation_drawer_close);
drawer.setDrawerListener(toggle);
toggle.syncState();
NavigationView navigationView = (NavigationView) findViewById(R.id.nav_view);
navigationView.setNavigationItemSelectedListener(this);
}
#Override
public void onBackPressed() {
DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
if (drawer.isDrawerOpen(GravityCompat.START)) {
drawer.closeDrawer(GravityCompat.START);
} else {
super.onBackPressed();
}
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
Bundle inBundle = getIntent().getExtras();
String first_name = inBundle.get("first_name").toString();
String last_name = inBundle.get("last_name").toString();
String imageUrl = inBundle.get("imageUrl").toString();
TextView nameView = (TextView)findViewById(R.id.nameView);
nameView.setText("" + first_name + " " + last_name);
new DownloadImage((ImageView)findViewById(R.id.imageView)).execute(imageUrl);
return true;
}
public class DownloadImage extends AsyncTask<String, Void, Bitmap> {
ImageView bmImage;
public DownloadImage(ImageView bmImage) {
this.bmImage = bmImage;
}
protected Bitmap doInBackground(String... urls) {
String urldisplay = urls[0];
Bitmap mIcon11 = null;
try {
InputStream in = new java.net.URL(urldisplay).openStream();
mIcon11 = BitmapFactory.decodeStream(in);
} catch (Exception e) {
Log.e("Error", e.getMessage());
e.printStackTrace();
}
return mIcon11;
}
protected void onPostExecute(Bitmap result) {
bmImage.setImageBitmap(result);
}
}
#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();
//noinspection SimplifiableIfStatement
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
#SuppressWarnings("StatementWithEmptyBody")
#Override
public boolean onNavigationItemSelected(MenuItem item) {
// Handle navigation view item clicks here.
int id = item.getItemId();
if (id == R.id.nav_camera) {
// Handle the camera action
} else if (id == R.id.nav_gallery) {
} else if (id == R.id.nav_slideshow) {
} else if (id == R.id.nav_manage) {
} else if (id == R.id.nav_share) {
} else if (id == R.id.nav_send) {
} else if(id == R.id.nav_user_edit){
Intent intent = new Intent(this, EditProfileActivity.class);
startActivity(intent);
}
DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
drawer.closeDrawer(GravityCompat.START);
return true;
}
}
You have to define your activities parent in the manifest file like this
<meta-data
android:name="android.support.PARENT_ACTIVITY"
android:value="fully qualified activity name" />
Make sure that you keep this meta data of your activity containing back button. Other wise its just like you are not telling you back button where to go !!
You have to add these two lines in your MainActivity.java file:
getSupportActionBar().setHomeButtonEnabled(true);
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
Add this in your onOptionsItemSelected(MenuItem item) method:
if (id==android.R.id.home)
{
NavUtils.navigateUpFromSameTask(this);
}
In your toolbar.xml set an imageview. Do like this i your toolbar.xml
<ImageView
android:id="#+id/tv_header_title2"
android:layout_width="25dp"
android:layout_height="wrap_content"
android:layout_gravity="left"
android:src="#drawable/backbutton"
android:layout_marginLeft="15dp"/>
In MainActivity
ImageView img= (ImageView) findViewById(R.id.tv_header_title2);
and
img.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
finish();
}
});
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'm trying to start an activity from another package withing the same project. The problem is that I keep geet errors saying that it can't find the class and asks me if I declared it in my manifest file. Here is the Manifest file for the project, the code for the class and the log which states the exception given. The two source packeges are simply named "ingegneria" and "unisannioportal" or just consider them "package1" and "package2".
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.example"
android:versionCode="1"
android:versionName="1.0" >
<uses-sdk
android:minSdkVersion="14"
android:targetSdkVersion="19" />
<application
android:allowBackup="true"
android:icon="#drawable/ic_launcher"
android:label="#string/app_name"
android:theme="#style/AppTheme" >
<activity
android:name="unisannioportal.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="ingegneria.ElencoAvvisiActivity"
android:label="#string/title_activity_elenco_avvisi" >
</activity>
<activity
android:name="ingegneria.AvvisoActivity"
android:label="#string/title_activity_avviso" >
</activity>
</application>
</manifest>
here is the code for the main class:
package unisannioportal;
import com.example.R;
import android.app.Activity;
import android.app.Fragment;
import android.app.FragmentManager;
import android.content.Intent;
import android.content.res.Configuration;
import android.os.Bundle;
import android.support.v4.app.ActionBarDrawerToggle;
import android.support.v4.view.GravityCompat;
import android.support.v4.widget.DrawerLayout;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.ListView;
public class MainActivity extends Activity
{
private String titolo;
private String[] dipartimenti;
private DrawerLayout menuDrawerLayout;
private ListView elencoMenuListView;
private ActionBarDrawerToggle menuDrawerToggle;
#Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
titolo = this.getTitle().toString();
dipartimenti = getResources().getStringArray(R.array.departments_array);
menuDrawerLayout = (DrawerLayout) findViewById(R.id.drawer_layout);
elencoMenuListView = (ListView) findViewById(R.id.left_drawer);
elencoMenuListView.setAdapter(new ArrayAdapter<String>(this,
R.layout.drawer_list_item, dipartimenti));
// set up the drawer's list view with items and click listener
elencoMenuListView.setAdapter(new ArrayAdapter<String>(this,
R.layout.drawer_list_item, dipartimenti));
elencoMenuListView.setOnItemClickListener(new DrawerItemClickListener());
getActionBar().setDisplayHomeAsUpEnabled(true);
getActionBar().setHomeButtonEnabled(true);
// ActionBarDrawerToggle ties together the the proper interactions
// between the sliding drawer and the action bar app icon
menuDrawerToggle = new ActionBarDrawerToggle(
this, /* host Activity */
menuDrawerLayout, /* DrawerLayout object */
R.drawable.ic_drawer, /* nav drawer image to replace 'Up' caret */
R.string.drawer_open, /* "open drawer" description for accessibility */
R.string.drawer_close /* "close drawer" description for accessibility */
) {
public void onDrawerClosed(View view) {
getActionBar().setTitle(titolo);
invalidateOptionsMenu(); // creates call to onPrepareOptionsMenu()
}
public void onDrawerOpened(View drawerView) {
getActionBar().setTitle(titolo);
invalidateOptionsMenu(); // creates call to onPrepareOptionsMenu()
}
};
menuDrawerLayout.setDrawerListener(menuDrawerToggle);
if (savedInstanceState == null)
{
selectItem(0);
}
}
/*#Override*/
public boolean onCreateOptionsMenu(Menu menu)
{
MenuInflater inflater = getMenuInflater();
inflater.inflate(R.menu.main, menu);
return super.onCreateOptionsMenu(menu);
}
#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 (menuDrawerToggle.onOptionsItemSelected(item)) {
return true;
}
return super.onOptionsItemSelected(item);
}
/* The click listner for ListView in the navigation drawer */
private class DrawerItemClickListener implements ListView.OnItemClickListener
{
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id)
{
selectItem(position);
}
}
private void selectItem(int position)
{
if(position == 0)
{
Intent intent = new Intent(this, ingegneria.ElencoAvvisiActivity.class);
this.startActivity(intent);
}
/* // update the main content by replacing fragments
Fragment fragment = new PlanetFragment();
Bundle args = new Bundle();
args.putInt(PlanetFragment.ARG_PLANET_NUMBER, position);
fragment.setArguments(args);
FragmentManager fragmentManager = getFragmentManager();
fragmentManager.beginTransaction().replace(R.id.content_frame, fragment).commit();
// update selected item and title, then close the drawer
mDrawerList.setItemChecked(position, true);
setTitle(mPlanetTitles[position]);
mDrawerLayout.closeDrawer(mDrawerList);*/
}
You might want to try something like this:
Intent intent = new Intent(Intent.ACTION_MAIN);
PackageManager manager = getApplicationContext().getPackageManager();
intent = manager.getLaunchIntentForPackage(YourPackageName);
intent.addCategory(Intent.CATEGORY_LAUNCHER);
startActivity();
the package declaration has no error.
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.example"
android:versionCode="1"
android:versionName="1.0" >
But the error locates in the activity declaration.
<activity
android:name="ingegneria.ElencoAvvisiActivity"
android:label="#string/title_activity_elenco_avvisi" >
</activity>
because there is one dot missing before the activity name. should look like below:
<activity
android:name=".ingegneria.ElencoAvvisiActivity"
android:label="#string/title_activity_elenco_avvisi" >
</activity>
or
<activity
android:name="com.example.ingegneria.ElencoAvvisiActivity"
android:label="#string/title_activity_elenco_avvisi" >
</activity>
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>
I am having problems recovering my app after implementing the v7 AppCompat support library, and now the: "...MainActivity.onCreateOptionsMenu(MainActivity.java:185)" - always returns NULL, and my app crashes.
I have followed the latest API Guide, and repeated it twice already but I can't fix it and it almost take me a day so far...:(
As I add "yourapp:actionViewClass="android.support.v7.widget.SearchView" to my search widget menu item, my app wont run anymore, so I am stuck no metter how many times I read the google documentation again...:(
Please help me out, I run out of ideas.
vedtam
logcat:
03-28 00:59:00.195: W/dalvikvm(9375): threadid=1: thread exiting with uncaught exception (group=0x40a71930)
03-28 00:59:00.205: E/AndroidRuntime(9375): FATAL EXCEPTION: main
03-28 00:59:00.205: E/AndroidRuntime(9375): java.lang.NullPointerException
03-28 00:59:00.205: E/AndroidRuntime(9375): at com.exploreca.tourfinder.MainActivity.onCreateOptionsMenu(MainActivity.java:185)
03-28 00:59:00.205: E/AndroidRuntime(9375): at android.app.Activity.onCreatePanelMenu(Activity.java:2490)
03-28 00:59:00.205: E/AndroidRuntime(9375): at com.android.internal.policy.impl.PhoneWindow.preparePanel(PhoneWindow.java:407)
03-28 00:59:00.205: E/AndroidRuntime(9375): at com.android.internal.policy.impl.PhoneWindow.doInvalidatePanelMenu(PhoneWindow.java:769)
03-28 00:59:00.205: E/AndroidRuntime(9375): at com.android.internal.policy.impl.PhoneWindow$1.run(PhoneWindow.java:201)
03-28 00:59:00.205: E/AndroidRuntime(9375): at android.view.Choreographer$CallbackRecord.run(Choreographer.java:749)
03-28 00:59:00.205: E/AndroidRuntime(9375): at android.view.Choreographer.doCallbacks(Choreographer.java:562)
03-28 00:59:00.205: E/AndroidRuntime(9375): at android.view.Choreographer.doFrame(Choreographer.java:531)
03-28 00:59:00.205: E/AndroidRuntime(9375): at android.view.Choreographer$FrameDisplayEventReceiver.run(Choreographer.java:735)
03-28 00:59:00.205: E/AndroidRuntime(9375): at android.os.Handler.handleCallback(Handler.java:725)
03-28 00:59:00.205: E/AndroidRuntime(9375): at android.os.Handler.dispatchMessage(Handler.java:92)
03-28 00:59:00.205: E/AndroidRuntime(9375): at android.os.Looper.loop(Looper.java:137)
03-28 00:59:00.205: E/AndroidRuntime(9375): at android.app.ActivityThread.main(ActivityThread.java:5041)
03-28 00:59:00.205: E/AndroidRuntime(9375): at java.lang.reflect.Method.invokeNative(Native Method)
03-28 00:59:00.205: E/AndroidRuntime(9375): at java.lang.reflect.Method.invoke(Method.java:511)
03-28 00:59:00.205: E/AndroidRuntime(9375): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:793)
03-28 00:59:00.205: E/AndroidRuntime(9375): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:560)
03-28 00:59:00.205: E/AndroidRuntime(9375): at dalvik.system.NativeStart.main(Native Method)
03-28 01:04:00.395: I/Process(9375): Sending signal. PID: 9375 SIG: 9
main.xml:
<?xml version="1.0" encoding="utf-8"?>
<menu xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:yourapp="http://schemas.android.com/apk/res-auto" >
<!-- Search Widget -->
<item android:id="#+id/search"
android:icon="#drawable/ic_action_search"
android:title="#string/search_title"
android:showAsAction="always"
yourapp:actionViewClass="android.support.v7.widget.SearchView" />
</menu>
searchable.xml:
<?xml version="1.0" encoding="utf-8"?>
<searchable xmlns:android="http://schemas.android.com/apk/res/android"
android:hint="#string/search_hint"
android:label="#string/app_name" />
manifest:
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.exploreca.tourfinder"
android:versionCode="1"
android:versionName="1.0" >
<uses-permission android:name="android.permission.CALL_PHONE" />
<uses-sdk
android:minSdkVersion="14"
android:targetSdkVersion="18" />
<application
android:allowBackup="true"
android:icon="#drawable/ic_exploreca"
android:label="#string/app_name"
android:theme="#style/AppTheme" >
<activity
android:name="com.exploreca.tourfinder.MainActivity"
android:label="#string/app_name" >
<meta-data
android:name="android.app.default_searchable"
android:value=".SearchResultsActivity" />
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<activity
android:name=".SettingsActivity">
</activity>
<activity
android:name=".TourDetailActivity">
</activity>
<!-- Search results activity -->
<activity android:name=".SearchActivity"
android:parentActivityName="com.exploreca.tourfinder.MainActivity" >
<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.exploreca.tourfinder;
import android.app.ActionBar;
import android.app.Activity;
import android.app.SearchManager;
import android.content.Intent;
import android.os.Bundle;
import android.util.Log;
import android.widget.TextView;
public class SearchActivity extends Activity {
private TextView txtQuery;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_search_results);
// get the action bar
ActionBar actionBar = getActionBar();
// Enabling Back navigation on Action Bar icon
actionBar.setDisplayHomeAsUpEnabled(true);
txtQuery = (TextView) findViewById(R.id.txtQuery);
handleIntent(getIntent());
}
#Override
protected void onNewIntent(Intent intent) {
setIntent(intent);
handleIntent(intent);
}
/**
* Handling intent data
*/
private void handleIntent(Intent intent) {
if (Intent.ACTION_SEARCH.equals(intent.getAction())) {
String query = intent.getStringExtra(SearchManager.QUERY);
/**
* Use this query to display search results like
* 1. Getting the data from SQLite and showing in listview
* 2. Making webrequest and displaying the data
* For now we just display the query only
*/
txtQuery.setText("Search Query: " + query);
}
}
}
MainActivity:
package com.exploreca.tourfinder;
import java.util.List;
import android.app.ActionBar;
import android.app.ListActivity;
import android.app.SearchManager;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.SharedPreferences.OnSharedPreferenceChangeListener;
import android.content.res.Configuration;
import android.os.Bundle;
import android.preference.PreferenceManager;
import android.support.v4.app.ActionBarDrawerToggle;
import android.support.v4.widget.DrawerLayout;
import android.support.v7.widget.SearchView;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.ListView;
import android.widget.Spinner;
import android.widget.SpinnerAdapter;
public class MainActivity extends ListActivity {
public static final String LOGTAG = "EXPLORECA";
public static final String USERNAME="pref_username";
public static final String VIEWIMAGE="pref_viewimages";
private SharedPreferences settings;
private OnSharedPreferenceChangeListener listener;
private List<Tour> tours;
//declaring Tours datasource
ToursDataSource datasource;
private DrawerLayout mDrawerLayout;
private ListView mDrawerList;
private ActionBarDrawerToggle mDrawerToggle;
private CharSequence mDrawerTitle;
private CharSequence mTitle;
private String[] mPlanetTitles;
public String myArray[] = {"cluj", "satu", "etc"};
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
// Set up the action bar to show a dropdown list.
final ActionBar actionBar = getActionBar();
actionBar.setDisplayShowTitleEnabled(false);
actionBar.setNavigationMode(ActionBar.NAVIGATION_MODE_LIST);
// Create an ArrayAdapter using the string array and a default spinner layout
// Create an ArrayAdapter using the string array and a default spinner layout
SpinnerAdapter mSpinnerAdapter = ArrayAdapter.createFromResource( actionBar.getThemedContext(),
R.array.music_categs, android.R.layout.simple_spinner_dropdown_item);
Spinner spinner = new Spinner(this);
// Specify the layout to use when the list of choices appears
// mSpinnerAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
// Apply the adapter to the spinner
spinner.setAdapter(mSpinnerAdapter);
//Set the callback for the drop-down list with
actionBar.setListNavigationCallbacks(mSpinnerAdapter, null);
mTitle = mDrawerTitle = getTitle();
mPlanetTitles = getResources().getStringArray(R.array.planets_array);
mDrawerLayout = (DrawerLayout) findViewById(R.id.drawer_layout);
mDrawerList = (ListView) findViewById(R.id.left_drawer);
mDrawerToggle = new ActionBarDrawerToggle(
this, /* host Activity */
mDrawerLayout, /* DrawerLayout object */
R.drawable.ic_drawer, /* nav drawer icon to replace 'Up' caret */
R.string.drawer_open, /* "open drawer" description */
R.string.drawer_close /* "close drawer" description */
) {
/** Called when a drawer has settled in a completely closed state. */
public void onDrawerClosed(View view) {
super.onDrawerClosed(view);
getActionBar().setTitle(mTitle);
}
/** Called when a drawer has settled in a completely open state. */
public void onDrawerOpened(View drawerView) {
super.onDrawerOpened(drawerView);
getActionBar().setTitle("Menu");
}
};
// Set the adapter for the list view
mDrawerList.setAdapter(new ArrayAdapter<String>(this,
R.layout.drawer_list_item, mPlanetTitles));
// Set the list's click listener
mDrawerList.setOnItemClickListener(new DrawerItemClickListener());
// Set the drawer toggle as the DrawerListener
mDrawerLayout.setDrawerListener(mDrawerToggle);
getActionBar().setDisplayHomeAsUpEnabled(true);
getActionBar().setHomeButtonEnabled(true);
settings = PreferenceManager.getDefaultSharedPreferences(this);
listener = new OnSharedPreferenceChangeListener() {
#Override
public void onSharedPreferenceChanged(SharedPreferences sharedPreferences,
String key) {
MainActivity.this.refreshDisplay();
}
};
settings.registerOnSharedPreferenceChangeListener(listener);
//instantieting the datasouce
datasource = new ToursDataSource(this);
datasource.open();
tours = datasource.findAll();
if (tours.size() == 0){
createData();
tours = datasource.findAll();
}
refreshDisplay();
}
#Override
protected void onPostCreate(Bundle savedInstanceState) {
super.onPostCreate(savedInstanceState);
// Sync the toggle state after onRestoreInstanceState has occurred.
mDrawerToggle.syncState();
}
//uj config a "menu" png-nek
#Override
public void onConfigurationChanged(Configuration newConfig) {
super.onConfigurationChanged(newConfig);
mDrawerToggle.onConfigurationChanged(newConfig);
}
// click listener for the listview menu items
private class DrawerItemClickListener implements ListView.OnItemClickListener {
#Override
public void onItemClick(AdapterView parent, View view, int position, long id) {
selectItem(position);
}
}
// launching menus with the same position as in listview
private void selectItem(int position) {
if (position == 2){
Intent intent = new Intent(this, SettingsActivity.class);
startActivity(intent);
}
// Highlight the selected item, update the title, and close the drawer
mDrawerList.setItemChecked(position, true);
setTitle(mPlanetTitles[position]);
mDrawerLayout.closeDrawer(mDrawerList);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
MenuInflater inflater = getMenuInflater();
inflater.inflate(R.menu.main, menu);
// Associate searchable configuration with the SearchView
SearchManager searchManager = (SearchManager) getSystemService(Context.SEARCH_SERVICE);
SearchView searchView = (SearchView) menu.findItem(R.id.search).getActionView();
searchView.setSearchableInfo(searchManager
.getSearchableInfo(getComponentName()));
return super.onCreateOptionsMenu(menu);
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// Pass the event to ActionBarDrawerToggle, if it returns
// true, then it has handled the app icon touch event
if (mDrawerToggle.onOptionsItemSelected(item)) {
return true;
}
switch (item.getItemId()) {
case R.id.menu_all:
tours = datasource.findAll();
refreshDisplay();
break;
case R.id.menu_cheap:
tours = datasource.findFiltered("city=?", "Satu");
refreshDisplay();
break;
case R.id.menu_fancy:
//tours = datasource.findFiltered("price >= 1000", "city", "", "price DESC");
refreshDisplay();
break;
default:
break;
}
return super.onOptionsItemSelected(item);
}
/* Called whenever we call invalidateOptionsMenu() */
#Override
public boolean onPrepareOptionsMenu(Menu menu) {
// If the nav drawer is open, hide action items related to the content view
boolean drawerOpen = mDrawerLayout.isDrawerOpen(mDrawerList);
// menu.findItem(R.id.menu_all).setVisible(!drawerOpen);
return super.onPrepareOptionsMenu(menu);
}
protected void onResume(){
super.onResume();
datasource.open();
}
protected void onPause(){
super.onPause();
datasource.close();
}
private void createData() {
ToursPullParser parser = new ToursPullParser();
List<Tour> tours = parser.parseXML(this);
for(Tour tour : tours){
datasource.create(tour);
}
//inserting data into the table
/*
Tour tour = new Tour();
tour.setTitle("salton Sea, ohh");
tour.setDescription("Az ut a tohoz.");
tour.setPrice(990);
tour.setImage("salton_sea");
tour = datasource.create(tour);
Log.i(LOGTAG, "Tour created with id:" +tour.getId());
*/
}
public void refreshDisplay() {
ArrayAdapter <Tour> adapter = new TourListAdapter(this, tours);
setListAdapter(adapter);
}
#Override
protected void onListItemClick(ListView l, View v, int position, long id) {
super.onListItemClick(l, v, position, id);
Tour tour = tours.get(position);
Intent intent = new Intent(this, TourDetailActivity.class);
intent.putExtra(".Tour", tour);
startActivity(intent);
}
}