Back arrow - error: cannot find symbol class MenuItem - android

I was trying to intent The getSupportActionBar() to the previous page.
While creating a back arrow to toolbar , I am getting an error for the second method says error: cannot find symbol class MenuItem
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_start);
getSupportActionBar().setHomeButtonEnabled(true);
}
#Override // This method creates the error
public boolean onOptionsItemSelected(MenuItem item) {
startActivity(new Intent(StartActivity.this, MainActivity.class));
}

Try This to get click event of back arraow
#Override
public boolean onOptionsItemSelected(MenuItem item) {
if (item.getItemId() == android.R.id.home) {
// perform Your action here
return true;
}
return false;
}
and in your manifest file add parent activity to your activity like this
<activity
android:name=".yourActivity"
android:parentActivityName=".ParentActivityname"/>

You can try this
MainActivity.java
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_start);
}
#Override // This method creates the error
public boolean onOptionsItemSelected(MenuItem item) {
switch(item.getItemId()) {
case android.R.id.home:
startActivity(new Intent(StartActivity.this, MainActivity.class));
return true;
}
return false;
}
Add the meta-data tag in your AndroidManifest.xml inside tag like this
<activity
android:name=".StartActivity"
android:parentActivityName="your package name.MainActivity">
<meta-data
android:name="android.support.PARENT_ACTIVITY"
android:value="your package name.MainActivity" />
</activity>
Note: Change "your package name" to your project package name

Ratilal Chopda already posted the right answer, here is only the solution in pretty code
public class ServicesViewActivity extends Activity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
// etc...
getActionBar().setDisplayHomeAsUpEnabled(true);
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case android.R.id.home:
NavUtils.navigateUpFromSameTask(this);
return true;
default:
return super.onOptionsItemSelected(item);
}
}
}
The function NavUtils.navigateUpFromSameTask(this) requires you to define the parent activity in the AndroidManifest.xml file
<activity android:name="com.example.ServicesViewActivity" >
<meta-data
android:name="android.support.PARENT_ACTIVITY"
android:value="com.example.ParentActivity" />
</activity>
http://developer.android.com/design/patterns/navigation.html#up-vs-back

You could also check if menu item was imported properly
that was my own experience the class wasn't imported hence it couldn't find the MenuItem

Related

Open new activity from public static class in android studio( menu > settings > preferences> activity)?

Friends,
I want to open a new activity from static method. But I am not able to access the xml file. I want to write code to call this contact.xml in xml folder of resources that contains.
<Preference
android:id="#+id/about_call"
android:title="Contact The Developer"
android:icon="#android:drawable/ic_menu_call"
android:onClick="Activity_call"
android:key="contact"
/>
Now I am struck at the java code of preferences in settings.java that contains the contact.xml access.
#TargetApi(Build.VERSION_CODES.HONEYCOMB)
public static class AboutFragment extends PreferenceFragment {
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
addPreferencesFromResource(R.xml.contact);
setHasOptionsMenu(true);
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
int id = item.getItemId();
if (id == android.R.id.home) {
startActivity(new Intent(getActivity(), settings.class));
return true;
}
return super.onOptionsItemSelected(item);
}
}
At this stage the xml file shows the listview of action_call. Please help me here to write code that if i click the xml id:action_call, it should do something either call or open an activity.
maybe u can try this
#Override
public boolean onOptionsItemSelected(MenuItem item) {
switch(item.getItemId)){
case R.id.about_call:
startActivity(new Intent(getActivity(), settings.class));
return true;
}
return super.onOptionsItemSelected(item);
}

Back button stopped to work in only one Activity

Back button stopped to work in only one Activity. I have three activities which have the same parent. But one of them stopped to back (CurrentMovieActivity). I can't figure out why. Manifest seems to be correct.
What's a possible reason for it?
My Manifest:
<application
android:allowBackup="true"
android:icon="#mipmap/ic_movie_white_24dp"
android:label="#string/app_name"
android:roundIcon="#mipmap/ic_movie_white_24dp"
android:supportsRtl="true"
android:theme="#style/AppTheme">
<activity android:name=".activity.MovieActivity">
<meta-data
android:name="android.app.searchable"
android:resource="#xml/searchable" />
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<action android:name="android.intent.action.SEARCH" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<activity
android:label="#string/settings_title"
android:name=".activity.SettingsActivity"
android:parentActivityName=".activity.MovieActivity" />
<activity
android:label="#string/current_title"
android:name=".activity.CurrentMovieActivity"
android:parentActivityName=".activity.MovieActivity" />
<activity
android:label="#string/favourites"
android:name=".activity.FavouritesActivity"
android:parentActivityName=".activity.MovieActivity" />
<provider
android:authorities="com.globallogic.v_holodynskyi.imdbclient"
android:exported="false"
android:name=".database.MovieProvider" />
I also tried to change launch mode and to override onBackPress. It looks like this, but I can't see any logs:
#Override
public void onBackPressed() {
Log.i(LOG_TAG, "back pressed1");
super.onBackPressed();
Log.i(LOG_TAG, "back pressed2");
}
My "broken" activity:
public class CurrentMovieActivity extends AppCompatActivity {
private static final String LOG_TAG = CurrentMovieActivity.class.getSimpleName();
private ImageView mPoster;
private TextView mMovieTitle;
private TextView mMovieDescription;
private FloatingActionButton mFloatingButton;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_current_movie);
initializeVariables();
}
#Override
public void onBackPressed() {
Log.i(LOG_TAG, "back pressed1");
super.onBackPressed();
Log.i(LOG_TAG, "back pressed2");
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
MenuInflater menuInflater = getMenuInflater();
menuInflater.inflate(R.menu.current_menu, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case R.id.action_favourite:
Intent openFavourite = new Intent(this, FavouritesActivity.class);
startActivity(openFavourite);
break;
default:
break;
}
return true;
}
private void initializeVariables() {
Intent intent = getIntent();
final String title = intent.getExtras().getString(Intent.EXTRA_TEXT + TITLE);
final String overview = intent.getExtras().getString(Intent.EXTRA_TEXT + DESCRIPTION);
final String posterLocation = intent.getExtras().getString(Intent.EXTRA_TEXT + LOCATION);
mPoster = findViewById(R.id.iv_movie_poster_current);
downloadImage(posterLocation, mPoster);
mMovieTitle = findViewById(R.id.tv_movie_title);
mMovieTitle.setText(title);
mMovieDescription = findViewById(R.id.tv_movie_description_current);
mMovieDescription.setText(overview);
mFloatingButton = findViewById(R.id.fb_add_to_favourites);
mFloatingButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
saveMovie(CurrentMovieActivity.this, title, overview, posterLocation, CONTENT_URI);
}
});
}
}
This is probably because of using android:parentActivityName. When you using the attribute, it makes your code checking for android.R.id.home in onOptionsItemSelected method.
You need to check for android.R.id.home and don't use a default case in the switch like this:
#Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
...
case android.R.id.home:
finish(); // call finish and don't use default case.
break;
}
return true;
}
Here is related documentation: Providing Up Navigation
check for override onBackPress() code as either you have deleted the code inside it. add finish() inside the onBackPress(),.

OnBackBressed not called

I have activity ActivityProfile, have getSupportActionBar().setDisplayHomeAsUpEnabled(true); implemented, onBackPressed() as well, search all over the internet and still no help.
#Override
public void onBackPressed() {
Toast.makeText(this, "OnBackpressed fired", Toast.LENGTH_SHORT).show();
super.onBackPressed();
}
#Override
public boolean onKeyDown(int keyCode, KeyEvent event)
{
//replaces the default 'Back' button action
if(keyCode== KeyEvent.KEYCODE_BACK) {
// something here
onBackPressed();
}
return true;
}
using the device's back button works, but not on the app...
To implement Up navigation, declare a parent of that particular activity in manifest and setDisplayHomeAsUpEnabled as true.
<activity
android:name="com.example.myfirstapp.DisplayMessageActivity"
android:label="#string/title_activity_display_message"
android:parentActivityName="com.example.myfirstapp.MainActivity" >
<!-- Parent activity meta-data to support 4.0 and lower -->
<meta-data
android:name="android.support.PARENT_ACTIVITY"
android:value="com.example.myfirstapp.MainActivity" />
</activity>
Read More https://developer.android.com/training/implementing-navigation/ancestral.html
you should use onOptionItemSelected to handle click on the bottom on action bar :
#Override
public boolean onOptionsItemSelected(MenuItem item)
{
switch (item.getItemId())
{
case android.R.id.home:
finish();
return true;
default:
return super.onOptionsItemSelected(item);
}
}
Try this
setSupportActionBar(toolbar);
toolbar.setNavigationOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
onBackPressed();
}
});
This should work
#Override
public boolean onOptionsItemSelected(MenuItem item) {
int id = item.getItemId();
if (id == android.R.id.home) {
onBackPressed();
}
return super.onOptionsItemSelected(item);
}
hi add this code in your activity. when you press back button in toolbar following code execute.
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.your_view);
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
getSupportActionBar().setHomeButtonEnabled(true);
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()){
case android.R.id.home:
finish();
break;
default:
return super.onOptionsItemSelected(item);
}
return super.onOptionsItemSelected(item);
}

Action bar Back button not working

with the help of these Android Docs.I am trying to do a action bar Back button.I get an Action Bar Back Button like these below image:
Output:
But My problem is After watching the Gallery images I press the action bar back button.
Then it is not working.But it have to go back to previous page.
Listed below are the codings.
GalleryActivity.java:
import android.app.ActionBar;
import android.os.Bundle;
import android.support.v4.app.FragmentActivity;
import android.support.v4.app.NavUtils;
import android.view.MenuItem;
import com.fth.android.R;
public class GalleryActivity extends FragmentActivity {
private int position;
private static String id;
private static String name;
private DemoCollectionPagerAdapter mDemoCollectionPagerAdapter;
private ViewPager mViewPager;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_gallery);
position = getIntent().getExtras().getInt("position");
id = getIntent().getExtras().getString("id");
name = getIntent().getExtras().getString("name");
mDemoCollectionPagerAdapter = new DemoCollectionPagerAdapter(getSupportFragmentManager());
// Set up action bar.
final ActionBar actionBar = getActionBar();
actionBar.setDisplayHomeAsUpEnabled(true);
// getActionBar().setDisplayOptions(ActionBar.DISPLAY_SHOW_HOME|ActionBar.DISPLAY_USE_LOGO|ActionBar.DISPLAY_HOME_AS_UP);
// Set up the ViewPager, attaching the adapter.
mViewPager = (ViewPager) findViewById(R.id.pager);
mViewPager.setAdapter(mDemoCollectionPagerAdapter);
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case android.R.id.home:
Intent upIntent = new Intent(this, HomeActivity.class);
upIntent.putExtra("position", position);
if (NavUtils.shouldUpRecreateTask(this, upIntent)) {
TaskStackBuilder.from(this)
.addNextIntent(upIntent)
.startActivities();
finish();
} else {
NavUtils.navigateUpTo(this, upIntent);
}
return true;
}
return super.onOptionsItemSelected(item);
}
}
GalleryDetailFragment.java:
import com.sit.fth.model.GalleryDetail;
import com.sit.fth.util.APIServiceHandler;
import com.sit.fth.util.AppConstants;
import com.sit.fth.util.AppPromoPager;
public class GalleryDetailFragment extends BaseFragment implements
PromoPagerListener {
private TextView countView;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
this.setHasOptionsMenu(true);
id = getArguments().getString("id");
name = getArguments().getString("name");
View view = inflater.inflate(R.layout.app_pager, null);
return view;
}
}
Anybody can help me if you know how to solve these.Thank You.
I solved these problem by adding the below coding in GalleryActivity.
ActionBar actionBar;
actionBar=getActionBar();
actionBar.setDisplayHomeAsUpEnabled(true);
#Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case android.R.id.home:
onBackPressed();
return true;
}
return super.onOptionsItemSelected(item);
}
In MainActivity:
Previously,
public class HomeActivity extends BaseActivity
Then I change into
public class HomeActivity extends FragmentActivity
In GalleryFragment:
I use Intent to pass it to the GalleryActivity.
#Override
public void onItemClick(AdapterView<?> arg0, View arg1, int arg2, long arg3) {
Gallery gallery = (Gallery) arg0.getAdapter().getItem(arg2);
Intent intent = new Intent(getActivity(), GalleryActivity.class);
intent.putExtra("position", position);
intent.putExtra("id", gallery.getGalId());
intent.putExtra("name", gallery.getAlbumTitle());
startActivity(intent);
// mCallback.OnGalItemSelected(gallery.getGalId(),gallery.getAlbumTitle());
}
Please read this
you should have something like this:
<activity
android:name="com.sit.fth.activity.HomeActivity"
android:screenOrientation="portrait">
</activity>
<activity
android:name="com.sit.fth.activity.GalleryActivity"
android:screenOrientation="portrait"
android:parentActivityName="com.sit.fth.activity.HomeActivity">
<meta-data
android:name="android.support.PARENT_ACTIVITY"
android:value="com.sit.fth.activity.HomeActivity"/>
</activity>
then calling NavUtils.navigateUpFromSameTask(this) will cause navigating to parent activity (HomeActivity).
You need to call setDisplayHomeAsUpEnabled(true) method in the onCreate method and override onSupportNavigateUp() and call onBackPressed() in it as below. That's it. done :)
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_help);
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
}
#Override
public boolean onSupportNavigateUp() {
onBackPressed();
return true;
}
You have just to add the following line to the activity in the manifest.xml. The parent activity is the activity to which you want to go back.
android:parentActivityName=".activities.MainActivity"
Try like
First of all you need to use addToBackStack() before commit() for Fragments
#Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
// Respond to the action bar's Up/Home button
case android.R.id.home:
if(getSupportFragmentManager().getBackStackEntryCount()>0)
getSupportFragmentManager().popBackStack();
return true;
}
return super.onOptionsItemSelected(item);
}
Best and easy answer is add the parent activity name in Manifest file, so Actionbar back button will work.
For that under that Activity tag of Manifest File use
android:parentActivityName=".MyCustomParentActivity"
if the home button is shown. you should add an action to the home button through onOptionItemSelected fun (arrow in your case) by default there's no action. so it's totally normal that it's not working. Please add this fun to your activity :
override fun onOptionsItemSelected(item: MenuItem): Boolean {
return when {
item.itemId == android.R.id.home -> {
finish()
true
}
else -> super.onOptionsItemSelected(item)
}
}
None of the answers provided here worked for me. I had to put the switch inside the onMenuItemSelected method. I'm aware this is not what is stated in the Android documentation, but still, it worked, so I just thought I'd leave this here for people who run into the same issue. My problem involved an Activity instead of a Fragment though, but that should be pretty much the same.
class FooActivity extends Activity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
// ...
getActionBar().setHomeButtonEnabled(true);
getActionBar().setDisplayHomeAsUpEnabled(true);
}
#Override
public boolean onMenuItemSelected(int featureId, MenuItem item) {
switch (item.getItemId()) {
case android.R.id.home:
NavUtils.navigateUpFromSameTask(this);
return true;
}
return false;
}
}
To me, I had to set mDrawerToggle.setToolbarNavigationClickListener(...) to a listener that triggers the back action. Otherwise it does nothing. This is what the source code of ActionBarDrawerToggle looks like:
toolbar.setNavigationOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (mDrawerIndicatorEnabled) {
toggle();
} else if (mToolbarNavigationClickListener != null) {
mToolbarNavigationClickListener.onClick(v);
}
}
});
So the default behaviour is actually to call our listener, and not do any magic on its own.
Use on SupportNavigateUp() method and call onBackPressed in this method.
onCreate
{
...
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
resetActionBar();
...
}
public void resetActionBar()
{
getSupportActionBar().setDisplayShowHomeEnabled(true);
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
getSupportActionBar().setHomeButtonEnabled(true);
}
#Override
public void onBackPressed() {
FragmentManager fm = getSupportFragmentManager();
int count = fm.getBackStackEntryCount();
if(count == 0) {
// Do you want to close app?
showDialog();
}else{
super.onBackPressed();
}
}
#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();
Log.i("coming", "comming");
//noinspection SimplifiableIfStatement
if(id==android.R.id.home){
if (getSupportFragmentManager().getBackStackEntryCount() > 0)
onBackPressed();
else
drawerLayout.openDrawer(navigationView);
return true;
}
return super.onOptionsItemSelected(item);
}
Here is one more thing to check for in case the other answers here (or here or here or here) don't work.
I had copied some code from another activity that disabled the menu. Deleting this method (and applying the solutions given in the others answers) allowed the up button to work.
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// hide the menu
return false;
}
In my case I had overridden the onCreateOptionsMenu method and I forgot to call super at the end.
Tool bar enable back button for Kotlin binding
setSupportActionBar(binding.toolbar)
supportActionBar?.setDisplayHomeAsUpEnabled(true)
supportActionBar?.setHomeAsUpIndicator(R.drawable.ic_times_ic)

Adding settings to android app

This is definitely a noob question. I've followed the instructions here http://developer.android.com/guide/topics/ui/settings.html#Activity and when I click on settings, nothing happens.
Here's what I have in MainActivity.java:
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
PreferenceManager.setDefaultValues(this, R.xml.preferences, false);
}
Then I have a new java file called PrefsActivity.java
public class PrefsActivity extends PreferenceActivity {
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
addPreferencesFromResource(R.xml.preferences);
} }
Then I have res/xml/preferences.xml
<?xml version="1.0" encoding="utf-8"?>
<PreferenceScreen xmlns:android="http://schemas.android.com/apk/res/android">
<CheckBoxPreference
android:key="face_up"
android:title="#string/face_up"
android:summary="#string/face_up_desc"
android:defaultValue="false" />
</PreferenceScreen>
I am trying to make it compatible with minsdk 7 if possible. What am I missing?
You need to open your activity when you click on your settings button. If your using an action bar, use something like this:
#Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case R.id.menu_settings:
Intent intent = new Intent(this, SettingsActivity.class);
startActivity(intent);
return true;
}
return super.onOptionsItemSelected(item);
}
In your main Activity
// Ensure the right menu is setup
#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;
}
// Start your settings activity when a menu item is selected
#Override
public boolean onOptionsItemSelected(MenuItem item) {
if (item.getItemId() == R.id.action_settings) {
Intent settingsIntent = new Intent(this, PrefsActivity.class);
startActivity(settingsIntent);
}
return super.onOptionsItemSelected(item);
}

Categories

Resources