Method invocation 'setDisplayHomeAsUpEnabled' may produce 'java.lang.NullPointerException - android

Why this line produce NullPointerException?
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
I have imported android.support.v7.app.AppCompatActivity
in build.grade I am using com.android.support.design:25.0.1
public class PhotosActivity extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.photos_activity);
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
int id = item.getItemId();
if (id == android.R.id.home) {
// finish the activity
onBackPressed();
return true;
}
return super.onOptionsItemSelected(item);
}
}
Errors: http://pastebin.com/aCQ4Hvpi

This conditional will fix that warning:
if (getSupportActionBar() != null) {
This is how I have my SupportActionBar set up, maybe this will help!
Toolbar myToolbar = (Toolbar) findViewById(R.id.toolbar_top);
setSupportActionBar(myToolbar);
if (getSupportActionBar() != null) {
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
getSupportActionBar().setLogo(R.mipmap.ic_launcher);
getSupportActionBar().setDisplayUseLogoEnabled(true);
}

Related

how to display downloaded images(history) in one of options called "view downloads" in navigation drawer menu

in my project my image are getting downloaded perfectly now I only wanted to know how should I display that downloaded images in "view downloads" activity which is present in navigation drawer...please anybody how can I display
download function in my activity:
downloadimage.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
DownloadManager.Request request = new DownloadManager.Request(
Uri.parse(imgUrl));
request.allowScanningByMediaScanner();
request.setNotificationVisibility(DownloadManager.
Request.VISIBILITY_VISIBLE_NOTIFY_COMPLETED);
request.setDestinationInExternalPublicDir(Environment.DIRECTORY_DOWNLOADS, "/my_file.JPEG");
DownloadManager dm = (DownloadManager) getSystemService(DOWNLOAD_SERVICE);
dm.enqueue(request);
Toast.makeText(getApplicationContext(), "Downloading File",
Toast.LENGTH_LONG).show();
}
});
view downloads activity(I haven't done here anything)edit please:
public class NextActivity extends AppCompatActivity {
ImageView myImage;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_next);
myImage = (ImageView) findViewById(R.id.down);
//getActionBar().setDisplayHomeAsUpEnabled(true);
// getActionBar().setHomeButtonEnabled(true);
//Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
//setSupportActionBar(toolbar);
// this.getSupportActionBar().setDisplayHomeAsUpEnabled(false);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
File imgFile = new File( Environment.DIRECTORY_DOWNLOADS, "/my_file.JPEG");
if(!(imgFile==null)){
Bitmap myBitmap = BitmapFactory.decodeFile(imgFile.getPath());
myImage.setImageBitmap(myBitmap);
Log.d("ashwiniiii","ashwiniii");
}
else {
myImage.setImageResource(R.drawable.ic_launcher_background);
}
NavigationView navigationView = (NavigationView) findViewById(R.id.nav_view);
assert navigationView != null;
//navigationView.setNavigationItemSelectedListener((NavigationView.OnNavigationItemSelectedListener) this);
if (getSupportActionBar() != null){
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
getSupportActionBar().setDisplayShowHomeEnabled(true);
}
// getSupportActionBar().setDisplayHomeAsUpEnabled(true);
//getSupportActionBar().setHomeButtonEnabled(true);
}
#Override
public boolean onOptionsItemSelected(#NonNull MenuItem item) {
if (item.getItemId() == android.R.id.home) {
finish(); // close this activity and return to preview activity (if there is any)
}
return super.onOptionsItemSelected(item);
}
#Override
public void onBackPressed() {
super.onBackPressed();
}}
if you are looking for showing images that you have downloaded to your device, the below code should work,
public class NextActivity extends AppCompatActivity {
ImageView img;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_next);
img=findViewById(R.id.down);
//getActionBar().setDisplayHomeAsUpEnabled(true);
// getActionBar().setHomeButtonEnabled(true);
//Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
//setSupportActionBar(toolbar);
// this.getSupportActionBar().setDisplayHomeAsUpEnabled(false);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
NavigationView navigationView = (NavigationView) findViewById(R.id.nav_view);
assert navigationView != null;
//update code
img.setImageBitmap(getImage());
//navigationView.setNavigationItemSelectedListener((NavigationView.OnNavigationItemSelectedListener) this);
if (getSupportActionBar() != null){
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
getSupportActionBar().setDisplayShowHomeEnabled(true);
}
// getSupportActionBar().setDisplayHomeAsUpEnabled(true);
//getSupportActionBar().setHomeButtonEnabled(true);
}
#Override
public boolean onOptionsItemSelected(#NonNull MenuItem item) {
if (item.getItemId() == android.R.id.home) {
finish(); // close this activity and return to preview activity (if there is any)
}
return super.onOptionsItemSelected(item);
}
public Image getImage(){
File imgFile = new File("/image_location");
//code to get image from path
if(imgFile.exists())
{
Bitmap myBitmap = BitmapFactory.decodeFile(imgFile.getAbsolutePath());
}
return myBitmap;
//returns image to specified imageview
}
#Override
public void onBackPressed() {
super.onBackPressed();
}}
}

How to implement android Toolbar Back button

I am using a custom toolbar. I need to add back button to it. Now I am using this code to add the back button.
Toolbar toolbar = (Toolbar) getActivity().findViewById(R.id.toolbar);
toolbar.setBackgroundColor(getResources().getColor(R.color.white));
toolbar.setNavigationIcon(getResources().getDrawable(R.drawable.back_arrow));
toolbar.setNavigationOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
onBackPressed();
}
});
This works fine. I can see the back button added. But consider the case where I am in Fragment1 which has no back button. Now I move to Fragment2 and I add in Back Button. From Fragment 2 I open Fragment 3 and I add the back button again.
Now when I press back button from fragment3 to go back to fragment2 i have to check the Fragment Stack to see whether the back button is required in fragment 2 or not.
Is there any other way to handle back button automatically as we push fragments to stack?
Just add two new line of code. Something like this
Toolbar toolbar = (Toolbar) getActivity().findViewById(R.id.toolbar);
toolbar.setBackgroundColor(getResources().getColor(R.color.white));
toolbar.setNavigationIcon(getResources().getDrawable(R.drawable.back_arrow));
setSupportActionBar(toolbar);
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
toolbar.setNavigationOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
onBackPressed();
}
});
This assumes you are using an AppCompatActivity
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
toolbar = (Toolbar) findViewById(R.id.tool_bar); // Attaching the layout to the toolbar object
setSupportActionBar(toolbar);
// enabling action bar app icon and behaving it as toggle button
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
getSupportActionBar().setHomeButtonEnabled(true);
}
Then in the onOptionsItemSelected you can override the home button as follows:
#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;
}
else if(id == android.R.id.home){
Intent i= new Intent(this, MainActivity.class);
i.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TASK | Intent.FLAG_ACTIVITY_NEW_TASK);
startActivity(i);
finish();
return true;
}
return super.onOptionsItemSelected(item);
}
You can handle back icon very easily. If all of your fragment are in single Activity I really recommend to handle this with following way :
first crate a abstract BaseFragment class which implement FragmentManager .OnBackStackChangedListener then put following method inside that :
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
mainActivity = (MainActivity) getActivity();
getFragmentManager().addOnBackStackChangedListener(this);
shouldDisplayHomeUp();
}
#Override
public void onBackStackChanged() {
shouldDisplayHomeUp();
}
public boolean shouldDisplayHomeUp() {
//Enable Up button only if there are entries in the back stack
boolean canBack = false;
try {
canBack = getFragmentManager().getBackStackEntryCount() > 0;
} catch (Exception ex) {
// Log.e(getClass().getCanonicalName(), ex.getMessage());getMessage
}
if (canBack) {
mainActivity.drawerDisable();
} else {
mainActivity.drawerEnable();
}
return canBack;
}
By this way disableDrawer & enableDrawer function handle your Icon and OnBackPressed method handle your BackStack Now in your activity when you press back-icon display if needed. your onBackPressed should be something like this :
int backStackCount = getSupportFragmentManager().getBackStackEntryCount();
if (backStackCount == 0) {
//nothing exist in backStack OS handle it
super.onBackPressed();
} else {
getSupportFragmentManager().popBackStack();
}
See full implementation here.
use Method in Class your Activity
private void setupToolbar(){
Toolbar toolbar=(Toolbar)findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
ActionBar actionBar=getSupportActionBar();
actionBar.setDisplayHomeAsUpEnabled(true);
actionBar.setDisplayShowHomeEnabled(true);
toolbar.setNavigationOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
finish();
}
});
}
It's works on back pressed function to toolbar
private setUpToolBar() {
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
getSupportActionBar().setDisplayShowHomeEnabled(true);
toolbar.setNavigationOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
onBackPressed();
}
});
}
i have Main activity and Four fragments.
In MainActivity i write this code
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
toolbar.setNavigationOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
onBackPressed();
}
});
this is working fine and if you have fragments then create a onBackPressed() method
#Override
public void onBackPressed() {
int position = mViewPager.getCurrentItem();
if(position == 2) { // go back to search / result tab from info detail tab
mViewPager.setCurrentItem(2);
} else if(position == 0) { // switch from result to search tab or go back to home tab
SectionsPagerAdapter sectionsPagerAdapter = (SectionsPagerAdapter) mViewPager.getAdapter();
Fragment fragment = sectionsPagerAdapter.getItem(position);
if(fragment instanceof ResultFragment) {
Bundle bundle = ((ResultFragment) fragment).getArguments();
if(bundle != null) {
sectionsPagerAdapter.replaceFragment(SearchFragment.newInstance(bundle.getString(GlobalInfo.TAG_ID), bundle.getString(GlobalInfo.PART_NO), bundle.getString(GlobalInfo.SERIAL_NO), bundle.getString(GlobalInfo.PART_NAME)), getString(R.string.search), 0);
}
} else {
mViewPager.setCurrentItem(1);
}
}
else if(position == 3){
SectionsPagerAdapter sectionsPagerAdapter = (SectionsPagerAdapter) mViewPager.getAdapter();
Fragment fragment = new ToolMgtFragment();
sectionsPagerAdapter.replaceFragment(fragment,"Tool Mgt", 3);
}
else {
super.onBackPressed();
}
}

Back Button isn't showing

I've just followed answers from this site and but they doesn't work for me. I am gonna have few activities and I want to have a back button on the action bar but it doesn't seems to appear. I am using API 16 for minimum sdk and I've set the parent Activity to the secondary activity.
Here's my code.
public class MainActivity extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
getSupportActionBar().setDefaultDisplayHomeAsUpEnabled(true);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.menu_main, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
int id = item.getItemId();
switch (item.getItemId()) {
case android.R.id.home:
NavUtils.navigateUpFromSameTask(this);
return true;
}
if (id == R.id.action_options) {
Intent i = new Intent(this, Settings.class);
startActivity(i);
return true;
}
return super.onOptionsItemSelected(item);
}
}
You probably meant setDisplayHomeAsUpEnabled, not setDefaultDisplayHomeAsUpEnabled. Not sure what the latter is anyway.
You missed setting setDisplayShowHomeEnabled(true). setDisplayHomeAsUpEnabled(true) is not enough.
final ActionBar actionBar = getSupportActionBar();
if (actionBar != null) {
actionBar.setDisplayShowHomeEnabled(true);
actionBar.setDisplayHomeAsUpEnabled(true);
}

android.R.id.home can not find symbol

I used Toolbar component in AppCompat library instead of Default Actionbar.
Compile time: I get compile-error that cannot find symbol android.R.id.home
public void setupActionBar() {
// Set a Toolbar to replace the ActionBar.
toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
getSupportActionBar().setHomeButtonEnabled(true);
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
int id = item.getItemId();
if(id == R.id.action_help) {
showHelp();
return true;
}else if(id == android.R.id.home){
Log.d(TAG, "Back Button clicked!");
this.finish();
return true;
}
return super.onOptionsItemSelected(item);
}
android.R.id.home was introduced in API level 11.
here is more detail:
https://stackoverflow.com/a/18719090/2178694
add this to your activity.
#Override
public void onBackPressed() {
// your code.
this.finish();
}

Android Back Arrow icon on ActionBar not working

For some reason this activity has the back arrow in the actionbar, but when it is clicked it has no reaction, doesn't even seen to recognize the click. I have other activities that are similar that work fine though. Here is the code with some stuff removed:
public class LanguageActivity extends ActionBarActivity {
private static final String TAG = "LanguageActivity";
#InjectView(R.id.listView)
RecyclerView mRecyclerView;
#State
String selectedLang;
LangViewHolder selectedHolder = null;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
Icepick.restoreInstanceState(this, savedInstanceState);
setContentView(R.layout.recyclerview);
ButterKnife.inject(this);
Toolbar toolbar = (Toolbar)findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
setTitle(R.string.ad_title_settings_lang);
selectedLang = PreferencesFacade.getInstance().getCurrentLang();
mRecyclerView.setLayoutManager(new TrueWrapContentLinearLayoutManager(this));
List<Pair<String, String>> langList = new LinkedList<>();
langList.add(Constants.Languages.US);
langList.add(Constants.Languages.LATIN_AMERICA_SPANISH);
mRecyclerView.setAdapter(new RecycleViewMappedArrayAdapter(R.layout.view_language_item, new LangViewHolder(mRecyclerView), langList));
}
#Override
protected void onSaveInstanceState(Bundle outState) {
Icepick.saveInstanceState(this, outState);
super.onSaveInstanceState(outState);
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()){
case android.R.id.home:
onBackPressed();
return true;
}
return super.onOptionsItemSelected(item);
}
#Override
public void finish() {
super.finish();
PreferencesFacade.getInstance().setCurrentLang(selectedLang);
Log.v(TAG, "Finishing?");
}
public class LangViewHolder extends RecycleViewMappedArrayAdapter.ViewHolder<Pair<String, String>>{
...
}
}
Manifest snippet:
<activity android:name=".activities.LanguageActivity"
android:parentActivityName=".activities.MainActivity">
<meta-data
android:name="android.support.PARENT_ACTIVITY"
android:value=".activities.MainActivity"/>
</activity>
This seems to be working for me:
Toolbar tBar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(tBar); // sets the Toolbar as the actionbar
tBar.setNavigationIcon(getResources().getDrawable(R.drawable.ic_arrow_back_white_24dp));
tBar.setNavigationOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
onBackPressed(); // calls the System onBackPressed method
}
});
Update:
getDrawable(int id) is depreciated so you should change this line of code:
int currentapiVersion = android.os.Build.VERSION.SDK_INT;
if (currentapiVersion >= Build.VERSION_CODES.LOLLIPOP){
tBar.setNavigationIcon(getResources().getDrawable(R.drawable.ic_arrow_back_white_24dp, getApplicationContext().getTheme()));
} else {
tBar.setNavigationIcon(getResources().getDrawable(R.drawable.ic_arrow_back_white_24dp));
}
why don't You extend AppCompatActivity(i think actionbaractivity is deprecated...)
?
and
Toolbar toolbar = (Toolbar) findViewById(R.id.the_id);
setSupportActionBar(toolbar);
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
//try this instead
toolbar.setNavigationOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
onBackPressed();
}
});

Categories

Resources