onOptionsItemSelected item shows method dont work? - android

As a topic:
With the current state of my work, I can show items on settings tab and action bar.
But the methods included don't work like expected. I'm not sure what's the problem.
Can you take a look at the following code to help me understand my errors?
public class Automat extends Activity {
DataBase dataBase;
ArrayList<Resource> res;
ViewPager myPager;
boolean move;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_automat);
// Show the Up button in the action bar.
setupActionBar();
move=true;
dataBase = new DataBase(this);
dataBase.open();
res = dataBase.getList();
ViewPagerAdapter2 adapter = new ViewPagerAdapter2(this, res, dataBase);
System.out.println("ADAPTER" + adapter);
myPager = (ViewPager) findViewById(R.id.myPager2);
//myPager.setOffscreenPageLimit(0);
myPager.setAdapter(adapter);
adapter.notifyDataSetChanged();
adapter.startUpdate(myPager);
dataBase.close();
class MyTimerTask extends TimerTask {
public void run() {
runOnUiThread(new Runnable() {
public void run() {
if (move){
myPager.setCurrentItem(myPager.getCurrentItem() + 1);
}else {}
}
});
System.out.println("");
}
}
MyTimerTask myTask = new MyTimerTask();
Timer myTimer = new Timer();
myTimer.schedule(myTask, 15000, 15000);
}
/**
* Set up the {#link android.app.ActionBar}, if the API is available.
*/
#TargetApi(Build.VERSION_CODES.HONEYCOMB)
private void setupActionBar() {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB) {
getActionBar().setDisplayHomeAsUpEnabled(true);
}
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.automat, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case android.R.id.home:
switchPause();
// This ID represents the Home or Up button. In the case of this
// activity, the Up button is shown. Use NavUtils to allow users
// to navigate up one level in the application structure. For
// more details, see the Navigation pattern on Android Design:
//
// http://developer.android.com/design/patterns/navigation.html#up-vs-back
//
NavUtils.navigateUpFromSameTask(this);
return true;
}
return super.onOptionsItemSelected(item);
}
private void switchPause(){
if(move){
System.out.println("MOVE = FALSE");
move=false;
}else {
System.out.println("MOVE = true");
move=true;
}
}
}

In method onOptionsItemSelected use code like following
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle item selection
switch (item.getItemId()) {
case android.R.id.home:
newGame();
return true;
case R.id.help:
showHelp();
return true;
default:
return super.onOptionsItemSelected(item);
}
}

Related

BaseActivity with common toolbar and menuItems activities can not catch onMenuItemClick

I've the base activity where all toolbar initializations and options menu are done, the activities extending the base can not fire onitemclick
In the base i have
public class BaseActivity extends AppCompatActivity {
private MenuItem refresh;
public Toolbar getToolbar() {
return toolbar;
}
public MenuItem getRefresh() {
return refresh;
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.menu_main, menu);
refresh = menu.findItem(R.id.action_refresh);
refresh.setActionView(R.layout.menu_item_view);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case android.R.id.home:
onBackPressed();
break;
}
return false;
}
#Override
public boolean onPrepareOptionsMenu(Menu menu) {
switch (mState) {
case Const.STATE_IDLE:
refresh.setVisible(true);
break;
case STATE_WORKING:
refresh.setVisible(false);
break;
default:
refresh.setVisible(true);
break;
}
return super.onPrepareOptionsMenu(menu);
}
}
In one of the activites I handle it like
public class CommentsActivity extends BaseToolbarActivity
{
#Override
public boolean onCreateOptionsMenu(Menu menu) {
super.onCreateOptionsMenu(menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
super.onOptionsItemSelected(item);
if(item.getItemId() == R.id.action_refresh){
setState(Const.STATE_WORKING);
showMsg(contentRoot,"oops");
return true;
}
return super.onOptionsItemSelected(item);
}
}
but the click items won't fire
After a while I came to realize that since I was setting a custom layout for my items (useful for animations) an option menu with a custom view that is either set in the xml or dynamically using
item.setActionView(R.layout.menu_lay);
Just like my problem above the menu item can never be invoked by the normal onOptionsItemSelected listener so the way to make it work is to implement onClickListener on the item's custom View so in my case the way to make it invoke is by
#Override
public boolean onCreateOptionsMenu(Menu menu) {
getRefresh.getActionView().setOnClickListener(new OnClickListener(){
#Override
public void onClick(View v) {
//refresh some data
}
});
return true;
}

saving items in Parse query adapter in main activity to favorites adapter by click

I want to be able to touch the items in the main activity and once touch the item will save to the favorites class. I'm assuming I need to implement and OnItemClickListener but I am having trouble implementing it correctly. please help
Also do I need to add another intent code and place the onclicklistener inside of there? If more information is needed please let me know, I have been stuck on this issue for awhile now. Thank you
This is my main activity code
import com.parse.ParseQueryAdapter;
public class WingmanListActivity extends ListActivity {
private ParseQueryAdapter<Tip> mainAdapter;
private FavoriteTipAdapter favoritesAdapter;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
getListView().setClickable(true);
mainAdapter = new ParseQueryAdapter<Tip>(this, Tip.class);
mainAdapter.setTextKey("title");
mainAdapter.setImageKey("photo");
//Subclass ParseQueryAdapter
favoritesAdapter = new FavoriteTipAdapter(this);
//Default view is all wingman tips
setListAdapter(mainAdapter);
/* String url = "http://twitter.com/";
WebView view = (WebView) this.findViewById(R.id.webView);
view.getSettings().setJavaScriptEnabled(true);
view.loadUrl(url); */
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.menu_wingman_list, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case R.id.action_refresh: {
updateTipList();
break;
}
case R.id.action_favorites: {
showFavorites();
break;
}
case R.id.action_new: {
newTip();
break;
}
case R.id.twitter: {
twitter();
break;
}
}
return super.onOptionsItemSelected(item);
}
private void twitter() {
Intent a = new Intent(this, Twitter.class);
startActivityForResult(a, 0);
}
private void updateTipList() {
mainAdapter.loadObjects();
setListAdapter(mainAdapter);
}
private void showFavorites() {
favoritesAdapter.loadObjects();
setListAdapter(favoritesAdapter);
}
private void newTip() {
Intent i = new Intent(this, NewTipActivity.class);
startActivityForResult(i, 0);

Getting error: Unable to Instantiate Activity

I have been following this tutorial: http://developer.android.com/guide/topics/ui/menus.html#CAB. However, when I run the application, I get an error:
java.lang.RuntimeException:
Unable to instantiate activity
ComponentInfo{com.example.ayushi.chaseyourdream/com.example.ayushi.chaseyourdream.MainActivity}:
java.lang.InstantiationException: can't instantiate class
com.example.ayushi.chaseyourdream.MainActivity
Here's my MainActivity. My application was working completely fine before I added code between label 1 and `label 2'.
public abstract class MainActivity extends ActionBarActivity implements AbsListView.MultiChoiceModeListener{
DbHelper db;
ListView myList;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
db = new DbHelper(this);
myList = (ListView) findViewById(R.id.newList);
loadData();
// LABEL 1
myList.setChoiceMode(ListView.CHOICE_MODE_MULTIPLE_MODAL);
myList.setMultiChoiceModeListener(new AbsListView.MultiChoiceModeListener() {
#Override
public void onItemCheckedStateChanged(ActionMode mode, int position,
long id, boolean checked) {
// Here you can do something when items are selected/de-selected,
// such as update the title in the CAB
}
#Override
public boolean onActionItemClicked(ActionMode mode, MenuItem item) {
// Respond to clicks on the actions in the CAB
switch (item.getItemId()) {
case R.id.menu_delete:
// deleteSelectedItems();
mode.finish(); // Action picked, so close the CAB
return true;
default:
return false;
}
}
#Override
public boolean onCreateActionMode(ActionMode mode, Menu menu) {
// Inflate the menu for the CAB
MenuInflater inflater = mode.getMenuInflater();
inflater.inflate(R.menu.context_main, menu);
return true;
}
public void onDestroyActionMode(ActionMode mode) {
// Here you can make any necessary updates to the activity when
// the CAB is removed. By default, selected items are deselected/unchecked.
}
public boolean onPrepareActionMode(ActionMode mode, Menu menu) {
// Here you can perform updates to the CAB due to
// an invalidate() request
return false;
}
});
// LABEL 2
}
public void onResume()
{
super.onResume();
loadData();
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.menu_main, 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();
//noinspection SimplifiableIfStatement
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
public void loadData()
{
Cursor cursor = null;
try {
cursor = db.fetchData();
}
catch(NullPointerException e)
{
e.printStackTrace();
}
ListAdapter myAdapter = new SimpleCursorAdapter(this, R.layout.tasks,
cursor,
new String[]{db._ID, db.COLUMN_1, db.COLUMN_2},
new int[]{R.id.idnum, R.id.c1, R.id.c2}, 0);
myList.setAdapter(myAdapter);
}
public void addNew(View v)
{
Intent intent = new Intent(this,AddActivity.class);
startActivity(intent);
}
}
EDIT 1: this line
public class MainActivity extends ActionBarActivity implements AbsListView.MultiChoiceModeListener{
showed me an error in Android Studio, and when I clicked Alt + Enter, it showed me two options: Make the class abstract, or implement its methods.
The first option gave me the initial problem, so now I went for option 2. Here are the additional methods implemented :
#Override
public void onItemCheckedStateChanged(ActionMode mode, int position, long id, boolean checked) {
}
#Override
public boolean onCreateActionMode(ActionMode mode, Menu menu) {
return false;
}
#Override
public boolean onPrepareActionMode(ActionMode mode, Menu menu) {
return false;
}
#Override
public boolean onActionItemClicked(ActionMode mode, MenuItem item) {
return false;
}
#Override
public void onDestroyActionMode(ActionMode mode) {
}
Now, my doubt is: these are exactly the same methods in between LABEL 1 and LABEL 2, and erasing any one set will lead to errors. What should I do?
You are getting this error: Unable to instantiate activity because you made your activity abstract. Remove that and implement the methods of AbsListView.MultiChoiceModeListenerinterface.
When you're implementing an Interface so you have to implement all the methods you have listed. If you don't know what to do with method you don't use just leave them as they are.
Now, my doubt is: these are exactly the same methods in between LABEL 1 and LABEL 2, and erasing any one set will lead to errors. What should I do?
You shouldn't have two of the same. Try using #Override annotation on the methods you implemented.

Programatically fire action bar menu item in Android

I have actionbar with menu item on the bar. When I click on the refresh icon I have method that shows up the progress bar.
I would like to do the on loading of this activity. Hence, I tried calling the refresh icon item click programatically:
onOptionsItemSelected(menu.findItem(R.id.action_Refresh));
I am calling the above after creating the menu.
But this gives null pointer exception on load my data. If I click on refresh button it is working fine, but if I call it programmatically I get an error.
Here is what I have:
#Override
public boolean onCreateOptionsMenu(Menu menu)
{
this.optionsMenu = menu;
getMenuInflater().inflate(R.menu.main, menu);
onOptionsItemSelected(menu.findItem(R.id.action_Refresh));
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item)
{
switch (item.getItemId())
{
case R.id.action_about:
aboutapp();
return true;
case R.id.action_Refresh:
Log.e("REfressh","Clicked");
Mapsthree.refreshValue = 0;
timer = new Timer();
timerMethod();
setRefreshActionButtonState(true);
displayView(1);
return true;
default:
return super.onOptionsItemSelected(item);
}
}
private void timerMethod()
{
timer.scheduleAtFixedRate(new TimerTask()
{
#Override
public void run()
{
updateProgressBar();
}
}, 0, 800);
}
private void updateProgressBar()
{
runOnUiThread(new Runnable()
{
public void run()
{
if (Maps.refreshValue == 1)
{
setRefreshActionButtonState(false);
timer.purge();
timer.cancel();
}
}
});
}
public void setRefreshActionButtonState(final boolean refreshing)
{
if (optionsMenu != null)
{
final MenuItem refreshItem = optionsMenu.findItem(R.id.action_Refresh);
if (refreshItem != null)
{
if (refreshing)
{
refreshItem.setActionView(R.layout.actionbar_indeterminate_progress);
}
else
{
refreshItem.setActionView(null);
}
}
}
}
Is it possible to call a menu item programmatically? if so how?
Thanks!
Just do findViewById(R.id.action_Refresh).callOnClick();
or
findViewById(R.id.action_Refresh).performClick();
Why are you calling it from onCreateOptionsMenu?
You can write the code for loading in onCreate or onResume method depending on the requirement:
#Override
protected void onCreate(Bundle arg0) {
super.onCreate(arg0);
//whatever you are doing
//now code for refresh
Log.e("REfressh","First time");
Mapsthree.refreshValue = 0;
timer = new Timer();
timerMethod();
setRefreshActionButtonState(true);
displayView(1);
}
You can try this :
get the reference of the Menu class opMenu inside your Activity here:
Menu opMenu;
#Override
public boolean onCreateOptionsMenu(Menu menu)
{
opMenu= menu;
getMenuInflater().inflate(R.menu.main, menu);
onOptionsItemSelected(opMenu.findItem(R.id.action_Refresh));
return super.onCreateOptionsMenu(menu);;
}
Use opMenu.findItem() to trigger click
// check is assignable to menu item implementation
if(menuItem !=null
&& MenuItemImpl.class.isAssignableFrom(menuItem.getClass())){
// if so cast
MenuItemImpl impl = (MenuItemImpl)menuItem;
// invoke listener
impl.invoke();
}
which is equal to implementation;
public boolean invoke() {
if (mClickListener != null && mClickListener.onMenuItemClick(this)) {
return true;
}
if (mIntent != null) {
mContext.startActivity(mIntent);
return true;
}
return false;
}
you can always use reflections :)

Android webview fire custom CAB during longClick and Selection mode

I use this code to override webview Context Action Bar but during longclick the CAB appears but no text selection how can i only fire CAB when text selection mode?
public class MainActivity extends Activity {
ActionMode.Callback mCallback;
ActionMode mMode;
WebView webview;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
webview=webview = (WebView) findViewById(R.id.webView1);
webview.loadUrl("http://www.google.com");
webview.setOnLongClickListener(new OnLongClickListener() {
#TargetApi(Build.VERSION_CODES.HONEYCOMB)
#SuppressLint("NewApi")
#Override
public boolean onLongClick(View v) {
// TODO Auto-generated method stub
if (mMode != null)
return false;
else
mMode = startActionMode(mCallback);
return true;
}
});
mCallback = new ActionMode.Callback() {
#Override
public boolean onPrepareActionMode(ActionMode mode, Menu menu) {
return false;
}
#Override
public void onDestroyActionMode(ActionMode mode) {
mMode = null;
}
#SuppressLint("NewApi")
#Override
public boolean onCreateActionMode(ActionMode mode, Menu menu) {
mode.setTitle("1 selected");
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
#SuppressLint("NewApi")
#Override
public boolean onActionItemClicked(ActionMode mode, MenuItem item) {
switch (item.getItemId()) {
case R.id.action_settings:
Toast.makeText(getBaseContext(), "Selected Action1 ",
Toast.LENGTH_LONG).show();
mode.finish();
break;
}
return false;
}
};
}
}
during long press my custom CAB appear without text selection
how to make it appear only in the case of text selection?
many thanks
don't do this,it is not necessary to overwrite longClick, you should make your custom webview and do some thing that below link display:
Look At This Answer

Categories

Resources