android: ClassCastException when working with context menu? - android

In my apps class ProjectFragActivtiy encountered exception like
java.lang.ClassCastException: com.actionbarsherlock.internal.view.menu.MenuBuilder
at com.oj.bs.ProjectFragActivity.onCreateOptionsMenu
(ProjectFragActivity.java:49).
in apps menu button is used for logout operation but encountered exception. Is there another way to implement the menu in actionbarsherlock.
Does anyone have a solution to this? Thanks in advance.
following is the ProjectFragActivtiy class
package com.oj.bs;
import android.os.Bundle;
import android.view.View;
import android.widget.Toast;
import com.actionbarsherlock.app.ActionBar;
import com.actionbarsherlock.app.ActionBar.Tab;
import com.actionbarsherlock.app.SherlockFragmentActivity;
import com.actionbarsherlock.view.Menu;
public class ProjectFragActivity extends SherlockFragmentActivity {
SessionManager sessionMngr ;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
sessionMngr = new SessionManager(getApplicationContext());
Toast.makeText(getApplicationContext(), "User Login Status: " + sessionMngr .isLoggedIn(),
Toast.LENGTH_LONG).show();
sessionMngr.checkLogin();
ActionBar actionBar = getSupportActionBar();
actionBar.setNavigationMode(ActionBar.NAVIGATION_MODE_TABS);
actionBar.setDisplayShowTitleEnabled(true);
Tab tab = actionBar.newTab().
setText("Residential").
setTabListener(new ResidentialFragActivity()).
setIcon(R.drawable.residential);
actionBar.addTab(tab);
tab = actionBar.newTab().
setText("Commercial").
setTabListener(new CommercialFragActivity()).
setIcon(R.drawable.commercial);
actionBar.addTab(tab);
}
public void Logout(View v) {
sessionMngr.logoutUser();
}
#Override
public boolean onCreateOptionsMenu(Menu m) {
getMenuInflater().inflate(R.menu.menu_logout, (android.view.Menu) m);
return true;
}
}

Change the onCreateOptionsMenu() as follows
#Override
public boolean onCreateOptionsMenu(Menu menu) {
com.actionbarsherlock.view.MenuInflater inflater = getSupportMenuInflater();
inflater.inflate(R.menu.menu_logout, (com.actionbarsherlock.view.Menu) menu);
return true;
}
NOTE :
In order to inflate your menu from XML you should call getSupportMenuInflater() in your activities. The fragment callbacks will already have an instance of the inflater as an argument.

Related

How to inflate two different menus for a Toolbar and a BottomAppBar

The following causes a post-install crash in emulator. No debug info shown.
package com.example.myapplication;
import android.os.Bundle;
import com.google.android.material.bottomappbar.BottomAppBar;
import com.google.android.material.tabs.TabLayout;
import androidx.appcompat.widget.Toolbar;
import androidx.viewpager.widget.ViewPager;
import androidx.appcompat.app.AppCompatActivity;
import android.view.Menu;
import android.view.MotionEvent;
import android.view.View;
import android.widget.ImageButton;
import android.widget.ListView;
import com.example.myapplication.ui.main.SectionsPagerAdapter;
public class MainActivity extends AppCompatActivity {
#Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.top_bar, menu);
return true;
}
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Toolbar top_toolbar = findViewById(R.id.top_toolbar);
setSupportActionBar(top_toolbar);
getSupportActionBar().setDisplayShowTitleEnabled(false);
BottomAppBar bottom_toolbar = findViewById(R.id.bottom_toolbar);
bottom_toolbar.replaceMenu(R.menu.bottom_bar);
SectionsPagerAdapter sectionsPagerAdapter = new SectionsPagerAdapter(this, getSupportFragmentManager());
ViewPager viewPager = findViewById(R.id.view_pager);
viewPager.setAdapter(sectionsPagerAdapter);
TabLayout tabs = findViewById(R.id.tabs);
tabs.setupWithViewPager(viewPager);
ImageButton my_posts_button = findViewById(R.id.my_posts_button);
ImageButton chats_button = findViewById(R.id.chats_button);
ImageButton post_button = findViewById(R.id.post_button);
ImageButton settings_button = findViewById(R.id.settings_button);
ImageButton profile_button = findViewById(R.id.profile_button);
ImageButton sort_button = findViewById(R.id.search_button);
ImageButton search_button = findViewById(R.id.sort_button);
}
}
It looks like the website thinks my post is mostly code.It looks like the website thinks my post is mostly code.It looks like the website thinks my post is mostly code.
You are using both a Toolbar and a BottomBar. You can use the onCreateOptionsMenu only for the bar used in the setSupportActionBar.
For example:
Toolbar toolbar = findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
and onCreateOptionsMenu for the Toolbar menu:
#Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.toolbar_menu, menu);
return true;
}
Then for the BottomBar you can use the app:menu in the layout or the replaceMenu method:
BottomAppBar bottomAppBar = findViewById(R.id.bottomappbar);
bottomAppBar.replaceMenu(R.menu.bottom_bar);
bottomAppBar.setOnMenuItemClickListener(new Toolbar.OnMenuItemClickListener() {
#Override
public boolean onMenuItemClick(MenuItem item) {
if (item == R.id...){
//....
return true;
}
return false;
}
});

Menu in a custom toolbar not showing in a fragment

So I have had asked this multiple times but I can't get a decent answer to my question.
Can someone please tell me why my menu is not showing in my custom toolbar?
PurchaseItemList.java
package com.example.devcash.Fragments;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.support.v7.widget.Toolbar;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.SearchView;
import android.widget.Spinner;
import android.widget.Toast;
import com.example.devcash.R;
/**
* A simple {#link Fragment} subclass.
*/
public class PurchaseItemListFragment extends Fragment implements SearchView.OnQueryTextListener, MenuItem.OnActionExpandListener {
Toolbar itemListToolbar;
Spinner itemListSpinner;
public PurchaseItemListFragment() {
// Required empty public constructor
}
#Override
public void onCreate(#Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
//inflate the menu
setHasOptionsMenu(true);
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
View view = inflater.inflate(R.layout.fragment_purchase_item_list, container, false);
itemListToolbar = (Toolbar) view.findViewById(R.id.toolbar_purchaseitemlist);
itemListSpinner = (Spinner) view.findViewById(R.id.spinner_allcategories);
///
ArrayAdapter<String> myAdapter = new ArrayAdapter<String>(getActivity(),
R.layout.custom_spinner_item,
getResources().getStringArray(R.array.dropdownitempurchase));
myAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
itemListSpinner.setAdapter(myAdapter);
itemListSpinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
#Override
public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
Toast.makeText(getActivity(),
itemListSpinner.getSelectedItem().toString(),
Toast.LENGTH_SHORT).show();
}
#Override
public void onNothingSelected(AdapterView<?> parent) {
}
});
return view;
}
//handles the search menu
#Override
public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {
inflater.inflate(R.menu.searchmenu, menu);
MenuItem searchItem = menu.findItem(R.id.action_search);
SearchView searchView = (SearchView) searchItem.getActionView();
searchView.setOnQueryTextListener(this);
searchView.setQueryHint("Search..");
super.onCreateOptionsMenu(menu, inflater);
}
#Override
public boolean onQueryTextSubmit(String query) {
return false;
}
#Override
public boolean onQueryTextChange(String newText) {
return false;
}
#Override
public boolean onMenuItemActionExpand(MenuItem item) {
return true;
}
#Override
public boolean onMenuItemActionCollapse(MenuItem item) {
return true;
}
}
and this is a snippet of my custom toolbar in my fragment_purchase_item_list.xml
<android.support.v7.widget.Toolbar
android:id="#+id/toolbar_purchaseitemlist"
android:layout_width="match_parent"
android:layout_height="wrap_content"
app:theme="#style/ThemeOverlay.AppCompat.Dark.ActionBar"
style="#style/PrimaryHeaderBar"
android:elevation="4dp">
<Spinner
android:id="#+id/spinner_allcategories"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:popupTheme="#style/ThemeOverlay.AppCompat.Light"/>
</android.support.v7.widget.Toolbar>
I have tried checking all the related posts from the internet and can't find a decent tutorial on YT. Can someone tell me what is going on here?
Add following line in onCreateView() method
setHasOptionsMenu(true)
Also add below line in onViewCreated() method
(activity as AppCompatActivity?)!!.setSupportActionBar(customToolbar as Toolbar?)
Where customToolBar is the id of the toolbar added in xml file
Add this in your onCreateView method
setHasOptionsMenu(true);

Search Bar for a seperate fragment

I have made different fragments inside one Activity (Home.java) on which toolbar and navigation drawer is there.
Right now I thought to put searchview inside fragment.We usually write all code related to searchview inside oncreateoption menu. I have done the same thing but oncreateoption is made inside fragment.
I'm not getting any error but searchbar is not be shown over the toolbar.
package com.example.foody;
import android.database.Cursor;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.support.v7.widget.SearchView;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import java.util.ArrayList;
public class fitem extends Fragment implements SearchView.OnQueryTextListener
{
RecyclerView rv1;
fitemAdapter adapter;
ArrayList<All_Data> item;
Cursor cr;
Storage sob;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState)
{
View v=inflater.inflate(R.layout.fragment_fitem, container, false);
sob=new Storage(getContext());
Bundle bundle = this.getArguments();
if (bundle == null)
cr=sob.allData(); //if called from home page
else
cr=sob.categorisedData(bundle.getString("category")); // if called from category page
inData();
rv1=v.findViewById(R.id.rv1);
rv1.setHasFixedSize(true);
rv1.setLayoutManager(new LinearLayoutManager(getContext()));
adapter=new fitemAdapter(getContext(),item);
rv1.setAdapter(adapter);
return v;
}
void inData()
{
item=new ArrayList<>();
while(cr.moveToNext())
{
item.add(new All_Data(cr.getString(0),cr.getString(2),cr.getString(3)));
}
}
public void onCreateOptionsMenu(Menu menu, MenuInflater inflater)
{
super.onCreateOptionsMenu(menu, inflater);
inflater.inflate(R.menu.tool_menu, menu);
MenuItem searchItem = menu.findItem(R.id.search1);
SearchView searchView = (SearchView) searchItem.getActionView();
searchView.setOnQueryTextListener(fitem.this);
searchView.setQueryHint("Search");
}
#Override
public boolean onQueryTextChange(String s)
{
String userInput=s.toLowerCase();
ArrayList<All_Data> filterlist=new ArrayList<>();
for(int i=0;i<item.size();i++)
{
String st=item.get(i).getName().toLowerCase();
if(st.contains(userInput))
filterlist.add(item.get(i));
}
adapter=new fitemAdapter(getContext(),filterlist);
rv1.setAdapter(adapter);
return true;
}
#Override
public boolean onQueryTextSubmit(String s) {
return false;
}
}
Inside your fragment's onCreate()/onCreateView() call setHasOptionsMenu(true);
This will allow your fragment to show the menu items you inflate inside the fragment's onCreateOptionsMenu(); otherwise it uses the host Activity's menu.

getSupportMenuInflater() is undefined for the type MainActivity with SlidingMenu + ABS

I am using Sliding Menu + ActionBarSherlock and for some "strange" reason I am getting this error. I get similar errors for "onCreateOptionsMenu" and "onOptionsItemSelected". I thought that importing Menu, MenuInflater and MenuItem from ABS would have solved the issues, but still I can't find the solution.
There shouldn't be any problem related to the dependencies between my project, ABS and SlidingMenu. Further I have extended all the classes correctly. Do you guys have any advice? Thanks.
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import com.actionbarsherlock.view.Menu;
import com.actionbarsherlock.view.MenuInflater;
import com.actionbarsherlock.view.MenuItem;
import com.jeremyfeinstein.slidingmenu.lib.SlidingMenu;
import com.jeremyfeinstein.slidingmenu.lib.app.SlidingFragmentActivity;
public class MainActivity extends SlidingFragmentActivity {
private Fragment mMapFragment;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
setBehindContentView(R.layout.menu_frame);
getSlidingMenu().setMode(SlidingMenu.LEFT_RIGHT);
getSlidingMenu().setTouchModeAbove(SlidingMenu.TOUCHMODE_NONE);
FragmentManager fm = getSupportFragmentManager();
mMapFragment = fm.findFragmentById(R.id.container);
if (savedInstanceState == null) {
mMapFragment = new RunMapFragment();
fm.beginTransaction()
.add(R.id.container, mMapFragment)
.commit();
}
getSlidingMenu().setSecondaryMenu(R.layout.menu_frame_two);
getSlidingMenu().setBehindOffsetRes(R.dimen.slidingmenu_offset);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu items for use in the action bar
MenuInflater inflater = getSupportMenuInflater();
inflater.inflate(R.menu.main_activity_actions, menu);
return super.onCreateOptionsMenu(menu);
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle presses on the action bar items
switch (item.getItemId()) {
case R.id.button1:
getSlidingMenu().showMenu();
return true;
case R.id.button2:
getSlidingMenu().showSecondaryMenu();;
return true;
default:
return super.onOptionsItemSelected(item);
}
}
}
SlidingMenuActivity appears to inherit from FragmentActivity, not SherlockFragmentActivity, and so you do not have ActionBarSherlock support, such as getSupportMenuInflater().
You may have to clone SlidingMenuActivity and create SherlockSlidingMenuActivity, changing it to inherit from SherlockFragmentActivity, then use your SherlockSlidingMenuActivity as the base class for your MainActivity.

How to add & link a second activity in actionbar compat in android 2.3.3

I am using actionbar compat in my application first time. I want to add another activity to the application. When i press a SETTINGS from actionbar, i like to start the second activity.
How is possible ?
codes for my application as follows
MainActivity.java
import android.os.Bundle;
import android.support.v7.app.ActionBarActivity;
import android.view.Menu;
import android.view.MenuItem;
import android.widget.Toast;
public class MainActivity extends ActionBarActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
#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);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
super.onOptionsItemSelected(item);
switch(item.getItemId()){
case R.id.action_settings:
Toast.makeText(getBaseContext(), "You selected Settings", Toast.LENGTH_SHORT).show();
startActivity( new Intent().setClass(this, SecondActivity.class));
break;
}
return true;
}
}
mainactivity image
Secondactivity.java
package com.example.test;
import android.app.Activity;
import android.os.Bundle;
public class SecondActivity extends Activity {
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.secondactivity);
// TODO Auto-generated method stub
}
}
secondactivity image
thanks in advance
Just use a
Intent intent = new Intent(this, YourActivityToStart.class);
startActivity(intent);
on the position where you pop up a Toast.
Using 'app' instead of 'android' namespace prefix for 'actionLayout' attribute fixed it for me.
So, basically, use
app:actionLayout="#layout/yourLayout"
instead of
android:actionLayout="#layout/yourLayout"
I am assuming you are using app_compat library to get the theming engine.

Categories

Resources