I develop a navigation drawer activity , but when I m trying to click in a fragment it gives me an error and it stopped I'm confused , please could someone help me to figure out the problem, here is the error
Caused by: java.lang.ClassCastException: com.nextinnovation.pt.barcodescanner.activity.NavigationDrawerActivity#a5712f1 must implement retryConnectionListener
at com.nextinnovation.pt.barcodescanner.fragment.BarcodeFragment.onAttach(BarcodeFragment.java:66)
BarcodeFragment
public class BarcodeFragment extends Fragment implements View.OnClickListener {
private static final String TAG= "BarcodeFragment";
private Button btnScan ;
private ScanRequest scanRequest ;
public BarcodeFragment(){
}
#Override
public void onCreate(#Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
}
#Nullable
#Override
public View onCreateView(LayoutInflater inflater, #Nullable ViewGroup container, #Nullable Bundle savedInstanceState) {
return inflater.inflate(R.layout.fragment_barcode_scanner, container, false);
}
#Override
public void onViewCreated(View view, #Nullable Bundle savedInstanceState) {
super.onViewCreated(view, savedInstanceState);
btnScan = view.findViewById(R.id.btnScan);
btnScan.setOnClickListener(this);
loadAdd(view);
}
private void loadAdd(View view) {
AdView mAdView = view.findViewById(R.id.adView);
AdRequest adRequest = new AdRequest.Builder().build();
mAdView.loadAd(adRequest);
}
#Override
public void onAttach(Context context) {
super.onAttach(context);
try {
scanRequest = (ScanRequest) context;
}
catch (ClassCastException e) {
throw new ClassCastException(context.toString()
+ " must implement retryConnectionListener");
}
}
#Override
public void onClick(View v) {
switch (v.getId()){
case R.id.btnScan :
// Pass the click event to activity to start the scanner .
scanRequest.scanBarcode();
break ;
}
}
public interface ScanRequest{
void scanBarcode();
}
}
NavigationDrawer
public class NavigationDrawerActivity extends AppCompatActivity implements NavigationView.OnNavigationItemSelectedListener {
private DrawerLayout drawer;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_navigation_drawer);
Toolbar toolbar = findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
drawer = findViewById(R.id.drawer_layout);
NavigationView navigationView = findViewById(R.id.nav_view);
navigationView.setNavigationItemSelectedListener(this);
ActionBarDrawerToggle toggle = new ActionBarDrawerToggle(this, drawer, toolbar,
R.string.navigation_drawer_open, R.string.navigation_drawer_close);
drawer.addDrawerListener(toggle);
toggle.syncState();
if (savedInstanceState == null) {
getSupportFragmentManager().beginTransaction().replace(R.id.fragment_container,
new BarcodeFragment()).commit();
navigationView.setCheckedItem(R.id.nav_home);
}
}
#Override
public void onBackPressed() {
if (drawer.isDrawerOpen(GravityCompat.START)) {
drawer.closeDrawer(GravityCompat.START);
} else {
super.onBackPressed();
}
}
#Override
public boolean onNavigationItemSelected(#NonNull MenuItem item) {
switch (item.getItemId()) {
case R.id.nav_home:
getSupportFragmentManager().beginTransaction().replace(R.id.fragment_container,
new BarcodeFragment()).commit();
break;
case R.id.nav_search:
getSupportFragmentManager().beginTransaction().replace(R.id.fragment_container,
new SearchFragment()).commit();
break;
/*
case R.id.nav_profile:
getSupportFragmentManager().beginTransaction().replace(R.id.fragment_container,
new ProfileFragment()).commit();
break;
case R.id.nav_share:
Toast.makeText(this, "Share", Toast.LENGTH_SHORT).show();
break;
case R.id.nav_send:
Toast.makeText(this, "Send", Toast.LENGTH_SHORT).show();
break;
*/
}
drawer.closeDrawer(GravityCompat.START);
return true;
}
}
Related
I am using navigation drawer with fragments and in my Home page i am navigating like this==> maincategory===>subcategory===>subcategoryDetail
while moving from maincategory to subcategory it perfectly replaces the hamburger icon and shows back arrow icon and onback press is working perfectly
but while moving from subcategory to subcategoryDetail when i press the back arrow of subcategoryDetail onback press is working perfectly
but it replaces the back arrow of subcategory.java page with hamburger icon and i cannot go back to home page
MainActivity.java
public class MainActivity extends AppCompatActivity
implements NavigationView.OnNavigationItemSelectedListener {
Toolbar toolbar;
DrawerLayout drawer;
ActionBarDrawerToggle toggle;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
toolbar = findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
toggle = new ActionBarDrawerToggle(
this, drawer, toolbar, R.string.navigation_drawer_open, R.string.navigation_drawer_close);
drawer.addDrawerListener(toggle);
toggle.syncState();
displaySelectedScreen(R.id.nav_home);
}
public ActionBarDrawerToggle getToggle() {
return toggle;
}
#Override
public void onBackPressed() {
DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
if (drawer.isDrawerOpen(GravityCompat.START)) {
drawer.closeDrawer(GravityCompat.START);
} else {
int fragments = getSupportFragmentManager().getBackStackEntryCount();
if (fragments == 1) {
finish();
} else if (getFragmentManager().getBackStackEntryCount() > 1) {
getFragmentManager().popBackStack();
} else {
super.onBackPressed();
toggle.setDrawerIndicatorEnabled(true);
}
}
}
#SuppressWarnings("StatementWithEmptyBody")
#Override
public boolean onNavigationItemSelected(MenuItem item) {
displaySelectedScreen(item.getItemId());
return true;
}
private void displaySelectedScreen(int itemId) {
Bundle bundle = new Bundle();
//creating fragment object
Fragment fragment = null;
//initializing the fragment object which is selected
switch (itemId) {
case R.id.nav_home:
fragment = new HomeFragment();
break;
case R.id.nav_mens_clothing:
bundle.putString("MAINCATEGORYID", String.valueOf(1));
bundle.putString("MAINCATEGORYNAME","Carpentry");
fragment = new SubCategoryFragment();
fragment.setArguments(bundle);
break;
case R.id.nav_womens_clothing:
bundle.putString("MAINCATEGORYID", String.valueOf(2));
bundle.putString("MAINCATEGORYNAME","Electrical");
fragment = new SubCategoryFragment();
fragment.setArguments(bundle);
break;
case R.id.nav_boys_clothing:
fragment = new SubCategoryFragment();
break;
}
//replacing the fragment
if (fragment != null) {
FragmentTransaction ft = getSupportFragmentManager().beginTransaction();
ft.replace(R.id.content_frame, fragment);
ft.addToBackStack(null);
ft.commit();
}
DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
drawer.closeDrawer(GravityCompat.START);
}
}
SubCategoryFragment.java
public class SubCategoryFragment extends Fragment {
protected Toolbar toolbar;
protected ActionBarDrawerToggle toggle;
View view;
public SubCategoryFragment() {
// Required empty public constructor
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
if (view == null) {
view = inflater.inflate(R.layout.fragment_sub_category, container, false);
toolbar = ((MainActivity) getActivity()).findViewById(R.id.toolbar);
toggle = ((MainActivity) getActivity()).getToggle();
shimmerContainer = view.findViewById(R.id.shimmer_view_container);
recyclerView_subcategory = view.findViewById(R.id.recycler_view_category);
toggle.setDrawerIndicatorEnabled(false);
toggle.setHomeAsUpIndicator(R.drawable.back);
toggle.setToolbarNavigationClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
getActivity().onBackPressed();
}
});
}
return view;
}
#Override
public void onPause() {
super.onPause();
toolbar.setTitle("Cooper");
toggle.setDrawerIndicatorEnabled(true);
}
SubCategoryDetailFragment.java
public class SubCategoryDetailFragment extends Fragment {
protected Toolbar toolbar;
protected ActionBarDrawerToggle toggle;
View view;
public SubCategoryDetailFragment() {
// Required empty public constructor
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
if (view == null) {
view = inflater.inflate(R.layout.fragment_sub_category_detail, container, false);
toolbar = ((MainActivity) getActivity()).findViewById(R.id.toolbar);
toggle = ((MainActivity) getActivity()).getToggle();
toggle.setDrawerIndicatorEnabled(false);
toggle.setHomeAsUpIndicator(R.drawable.back);
toggle.setToolbarNavigationClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
getActivity().onBackPressed();
}
});
}
return view;
}
#Override
public void onPause() {
super.onPause();
toolbar.setTitle("zzz");
toggle.setDrawerIndicatorEnabled(true);
}}
}
Design two different toolbars in XML and set their visibility according to fragment and activity. When Activity load set Toolbar with Navigation drawer, but when fragment load in that activity hide the current toolbar and replace with another toolbar XML with the back icon.
Do not forget to add toolbar code in onResume() method of the fragment.
Please add these two lines in onresume it will work.
toggle.setDrawerIndicatorEnabled(false);
toggle.setHomeAsUpIndicator(R.drawable.back);
Hey I'm new in android development and i'm trying to develop an app with navigation drawer. So i created fragments with navigation drawer menus, and from one of those fragments I have given an intent to a new activity. But i dont know how to go back from that activity to previous fragment.
MainActivity.java
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);
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.addDrawerListener(toggle);
toggle.syncState();
NavigationView navigationView = (NavigationView) findViewById(R.id.nav_view);
navigationView.setNavigationItemSelectedListener(this);
displaySelectedScreen(R.id.nav_bus);
}
#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) {
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
int id = item.getItemId();
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
private void displaySelectedScreen(int itemId) {
Fragment fragment = null;
switch (itemId) {
case R.id.nav_bus:
fragment = new BusFragment();
break;
case R.id.nav_hotel:
fragment = new HotelFragment();
break;
}
if (fragment != null) {
FragmentTransaction ft = getSupportFragmentManager().beginTransaction();
ft.replace(R.id.content_frame, fragment);
ft.commit();
}
DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
drawer.closeDrawer(GravityCompat.START);
}
#SuppressWarnings("StatementWithEmptyBody")
#Override
public boolean onNavigationItemSelected(MenuItem item) {
displaySelectedScreen(item.getItemId());
return true;
}
}
From this fragment i have given intent to city.java activity
HotelFragment.java
public class HotelFragment extends Fragment {
public View onCreateView(LayoutInflater inflater, #Nullable ViewGroup container, #Nullable Bundle savedInstanceState) {
View rootView= inflater.inflate(R.layout.fragment_hotel, container, false);
Button button = (Button) rootView.findViewById(R.id.button);
button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
updateDetail();
} });
return rootView;
}
public void updateDetail() {
Intent intent = new Intent(getActivity(), City.class);
startActivity(intent);
}
#Override
public void onViewCreated(View view, #Nullable Bundle savedInstanceState) {
super.onViewCreated(view, savedInstanceState);
getActivity().setTitle("Hotel");
}
}
City.java
public class City extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_city_list);
} }
In manifest file i have added this
<activity android:name=".City_List"
android:parentActivityName = "MainActivity"
>
<meta-data
android:name = "android.support.PARENT_ACTIVITY"
android:value = "MainActivity" />
</activity>
</application>
to be able to go back to the previous fragment should include the .addToBackStack()
if (fragment != null) {
FragmentTransaction ft = getSupportFragmentManager().beginTransaction();
ft.replace(R.id.content_frame, fragment);
ft.addToBackstack(null)
ft.commit();
}
and when you click on back button in the toolbar programmatically go back to the previous fragment using following code.
if ( getFragmentManager().getBackStackEntryCount() > 0)
{
getFragmentManager().popBackStack();
return;
}
super.onBackPressed();
Add this line inside back pressed method
if(getFragmentManager().getBackStackEntryCount() > 0) {
getFragmentManager().popBackStack();
}
else {
super.onBackPressed();
}
I am creating an application in which I use navigation menu. When I click on menu, navigation drawer open, and I click on an item and open a fragment. I want that, when fragment open navigation menu change into back arrow.
Here is my code of Activity:
public class Container_Activity extends AppCompatActivity implements NavigationView.OnNavigationItemSelectedListener {
FrameLayout frameLayout;
private Boolean exit = false;
FloatingActionButton floatingActionButton;
static Container_Activity activity;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_container_);
if (android.os.Build.VERSION.SDK_INT >= 21) {
Window window = this.getWindow();
window.addFlags(WindowManager.LayoutParams.FLAG_DRAWS_SYSTEM_BAR_BACKGROUNDS);
window.clearFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS);
window.setStatusBarColor(this.getResources().getColor(R.color.statusbarcolor));
}
activity = this;
if (savedInstanceState == null) {
Container_Activity.showFragment(new Home_fragment(), "");
}
frameLayout = (FrameLayout) findViewById(R.id.container_frame);
floatingActionButton = (FloatingActionButton) findViewById(R.id.fab);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
toolbar.setNavigationIcon(getResources().getDrawable(R.drawable.ic_arrow_back));
if (getSupportActionBar() != null) {
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
getSupportActionBar().setDisplayShowHomeEnabled(true);
}
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);
floatingActionButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Container_Activity.showFragment(new ConctactUs_fragment(), "");
}
});
}
public void showFloatingActionButton() {
floatingActionButton.show();
}
;
public void hideFloatingActionButton() {
floatingActionButton.hide();
}
;
#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 onNavigationItemSelected(#NonNull MenuItem item) {
DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
drawer.closeDrawer(GravityCompat.START);
switch (item.getItemId()) {
case R.id.home_item:
showFragment(new Home_fragment(), "Home");
break;
case R.id.services:
showFragment(new Services_fragment(), "Services");
break;
case R.id.portfolio_item:
showFragment(new Portfolio_fragment(), "Portfolio");
break;
case R.id.training_item:
showFragment(new Training_fragment(), "Training");
break;
case R.id.gallery_item:
showFragment(new Gallery_Fragment(), "Gallery");
break;
case R.id.share_item:
shareurl();
break;
case R.id.reach_us:
showFragment(new ConctactUs_fragment(), "Contact");
break;
}
return false;
}
private void shareurl() {
Intent sendIntent = new Intent();
sendIntent.setAction(Intent.ACTION_SEND);
sendIntent.putExtra(Intent.EXTRA_TEXT,
"Hey check out my app at: https://play.google.com/store/apps/details?id=com.techenrage");
sendIntent.setType("text/plain");
startActivity(sendIntent);
}
public static void showFragment(Fragment fragment, String Tag) {
FragmentManager manager = activity.getSupportFragmentManager();
FragmentTransaction transcation = manager.beginTransaction();
transcation.replace(R.id.container_frame, fragment, Tag);
transcation.addToBackStack(Tag);
transcation.commit();
}
#Override
public boolean dispatchTouchEvent(MotionEvent ev) {
if (ev.getAction() == MotionEvent.ACTION_DOWN) {
View v = getCurrentFocus();
if (v instanceof EditText) {
Rect outRect = new Rect();
v.getGlobalVisibleRect(outRect);
if (!outRect.contains((int) ev.getRawX(), (int) ev.getRawY())) {
v.clearFocus();
InputMethodManager imm = (InputMethodManager) getSystemService(activity.INPUT_METHOD_SERVICE);
imm.hideSoftInputFromWindow(v.getWindowToken(), 0);
}
}
}
return super.dispatchTouchEvent(ev);
}
}
Fragment Class:
public class Portfolio_fragment extends Fragment {
TabLayout tabLayout;
ViewPager viewPager;
#Nullable
#Override
public View onCreateView(LayoutInflater inflater, #Nullable ViewGroup container, #Nullable Bundle savedInstanceState) {
final View view = inflater.inflate(R.layout.portfolio_fragment, container, false);
((AppCompatActivity) getActivity()).getSupportActionBar().setTitle("Portfolio");
tabLayout = (TabLayout) view.findViewById(R.id.tabLayout);
tabLayout.setupWithViewPager(viewPager);
tabLayout.addTab(tabLayout.newTab().setText("Websites"));
tabLayout.addTab(tabLayout.newTab().setText("Mobile Application"));
tabLayout.addTab(tabLayout.newTab().setText("Graphics"));
tabLayout.setTabGravity(TabLayout.GRAVITY_FILL);
viewPager = (ViewPager) view.findViewById(R.id.portfolio_pager);
Portfolio_Adapter adapter = new Portfolio_Adapter(getChildFragmentManager(), tabLayout.getTabCount());
viewPager.setAdapter(adapter);
tabLayout.setOnTabSelectedListener(new TabLayout.OnTabSelectedListener() {
#Override
public void onTabSelected(TabLayout.Tab tab) {
viewPager.setCurrentItem(tab.getPosition());
}
#Override
public void onTabUnselected(TabLayout.Tab tab) {
}
#Override
public void onTabReselected(TabLayout.Tab tab) {
}
});
viewPager.addOnPageChangeListener(new TabLayout.TabLayoutOnPageChangeListener(tabLayout));
return view;
}
}
try this
#Override
protected void onCreateView(Bundle savedInstanceState) {
((AppCompatActivity) getActivity()).getSupportActionBar().setHomeAsUpIndicator(R.drawable.back_button);
((AppCompatActivity) getActivity()).getSupportActionBar().setDisplayHomeAsUpEnabled(true);
}
I have a main activity with navigation drawer and a button to load fragment.
When the main ativity is launched I load the MainFragment.
In this moment all works well. The hamburger icon is showing and my Main fragment was loaded.
Next, I click a button and load a secondFragment. After I load the second fragment, I can use the backbutton and homebutton to come back to main activity without problems.
When I am with second fragment loaded and I make a rotation screen, the back button continues to work well, but the home button disappears and hamburger icon appears.
What am i doing wrong?
public class MainActivity extends AppCompatActivity {
private ActionBarDrawerToggle actionBarDrawerToggle;
private DrawerLayout drawerLayout;
private Toolbar toolbar;
private CharSequence mDrawerTitle;
private CharSequence mTitle;
private String mSubTitle;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
initNavigationDrawer();
if (savedInstanceState != null) {
return;
}
MainActivityFragment mainFragment = new MainActivityFragment();
firstFragment.setArguments(getIntent().getExtras());
// Add the fragment to the 'fragment_container' FrameLayout
FragmentTransaction transaction = getSupportFragmentManager().beginTransaction();
//transaction.replace(R.id.fragment_container, firstFragment);
transaction.replace(R.id.fragment_container, mainFragment, "princ");
transaction.commit();
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// Only handle with DrawerToggle if the drawer indicator is enabled.
if (actionBarDrawerToggle.isDrawerIndicatorEnabled() &&
actionBarDrawerToggle.onOptionsItemSelected(item)) {
return true;
}
// Handle your other action bar items...
return super.onOptionsItemSelected(item);
}
}
public Fragment getCurrentFragment(){
FragmentManager frgmgr = getSupportFragmentManager();
return frgmgr.findFragmentById(R.id.fragment_container);
}
#Override
public void onBackPressed() {
if (drawerLayout != null) {
if (drawerLayout.isDrawerOpen(GravityCompat.START)) {
drawerLayout.closeDrawer(GravityCompat.START);
return;
}
}
if ((getCurrentFragment() instanceof MainFragment)) {
finish();
} else if (getSupportFragmentManager().getBackStackEntryCount() > 0) {
getSupportFragmentManager().popBackStack();
} else super.onBackPressed();
}
public void initNavigationDrawer() {
NavigationView navigationView = (NavigationView) findViewById(R.id.navigation_view);
navigationView.setNavigationItemSelectedListener(new NavigationView.OnNavigationItemSelectedListener() {
#Override
public boolean onNavigationItemSelected(MenuItem menuItem) {
FragmentManager frgmgr = getSupportFragmentManager();
FragmentTransaction transaction = frgmgr.beginTransaction();
Fragment cur_frag;
// Handle navigation view item clicks here.
int id = menuItem.getItemId();
switch (id) {
case R.id.home:
cur_frag = frgmgr.findFragmentById(R.id.fragment_container);
if (!(cur_frag instanceof MainActivityFragment)) {
MainActivityFragment frag = new MainActivityFragment();
transaction.setCustomAnimations(R.anim.enter_from_left, R.anim.exit_to_right, R.anim.enter_from_right, R.anim.exit_to_left);
transaction.replace(R.id.fragment_container, frag);
transaction.commit();
break;
}
drawerLayout.closeDrawers();
break;
case R.id.logout_drw:
finish();
}
drawerLayout.closeDrawer(GravityCompat.START);
return true;
}
});
View header = navigationView.getHeaderView(0);
TextView tv_email = (TextView) header.findViewById(R.id.tv_email);
tv_email.setText("Agendamento");
drawerLayout = (DrawerLayout) findViewById(R.id.drawer);
mTitle = mDrawerTitle = getTitle();
actionBarDrawerToggle = new ActionBarDrawerToggle(this, drawerLayout, toolbar, R.string.drawer_open, R.string.drawer_close) {
#Override
public void onDrawerClosed(View v) {
super.onDrawerClosed(v);
}
#Override
public void onDrawerOpened(View v) {
super.onDrawerOpened(v);
}
};
drawerLayout.addDrawerListener(actionBarDrawerToggle);
actionBarDrawerToggle.syncState();
if (toolbar != null) {
getSupportFragmentManager().addOnBackStackChangedListener(new FragmentManager.OnBackStackChangedListener() {
#Override
public void onBackStackChanged() {
int i=getSupportFragmentManager().getBackStackEntryCount();
if ((i > 0) || (!(getCurrentFragment() instanceof MainActivityFragment))) {
getSupportActionBar().setDisplayHomeAsUpEnabled(true); // show back button
toolbar.setNavigationOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
onBackPressed();
}
});
} else {
getSupportActionBar().setDisplayHomeAsUpEnabled(false);
actionBarDrawerToggle.syncState();
toolbar.setNavigationOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
drawerLayout.openDrawer(GravityCompat.START);
}
});
}
}
});
}
}
}
Main Fragment:
public class MainFragment extends Fragment {
public MainFragment() {
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View view=inflater.inflate(R.layout.fragment_main, container, false);
Button butCons= (Button) view.findViewById(R.id.butcons);
butCons.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
SecundaryFrag frag = new SecundaryFragFrag();
// Add the fragment to the 'fragment_container' FrameLayout
FragmentTransaction transaction=getFragmentManager().beginTransaction();
transaction.setCustomAnimations(R.anim.enter_from_left, R.anim.exit_to_right, R.anim.enter_from_right, R.anim.exit_to_left);
transaction.replace(R.id.fragment_container, frag);
transaction.addToBackStack(null);
transaction.commit();
}
});
return view;
}
}
Secondary Fragment:
public class SecundaryFrag extends Fragment{
public SecundaryFrag() {
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
}
#Nullable
#Override
public View onCreateView(LayoutInflater inflater, #Nullable ViewGroup container, #Nullable Bundle savedInstanceState) {
View view=inflater.inflate(R.layout.fragment_consulta_ag, container, false);
return view;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case android.R.id.home:
((MainActivity)getActivity()).onBackPressed();
return true;
default:
return super.onOptionsItemSelected(item);
}
}
}
After Rotation:
Main activty with main fragment:
Before Rotation:
I believe it is related to the fact that the view is recreated after the orientation change. I would take a closer look to the onCreate() from the MainActivity in particular when the
if (savedInstanceState != null) {
return;
}
is triggered.
One option is to retain the fragments and restoring them onCreate. Also you could turn off the recreation by catching the orientation and handle it yourself in the application, you can see here both options explained developer.android.com/guide/topics/resources/
I'm writing an app for school and everything works fine when I run the app in the emulator.
The problem is when I connect my phone through usb and run the app on the phone.
Whenever I do something which requires the mListener (in any fragment in the whole app), I get a nullpointerexception on my mListener.
I have searched but have not found a solution or similar problem.
I have the problem in all of my fragments, but I will just show 1 fragment here:
Code of a fragment:
public class QuizFragment extends Fragment {
private OnFragmentQuizInteractionListener mListener;
List<Vraag> quesList;
int qid=0;
Vraag currentQ;
TextView txtQuestion;
RadioButton rda, rdb, rdc;
Button butNext;
TextView txtResult;
Button btnToonAntwoord;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
getActivity().setTitle("Quiz");
final View view = inflater.inflate(R.layout.quiz_layout, container, false);
//btnStart = (Button) getActivity().findViewById(R.id.btnStart);
//btnStart.setOnClickListener(new View.OnClickListener() {
// #Override
// public void onClick(View v) {
// mListener.initQuiz();
// }
//});
//reset the score to 0
mListener.resetScore();
qid=0;
QuizDbHelper db=new QuizDbHelper(view.getContext());
quesList=db.getAllQuestions();
currentQ=quesList.get(qid);
txtQuestion=(TextView) view.findViewById(R.id.textView1);
rda=(RadioButton)view.findViewById(R.id.radio0);
rdb=(RadioButton)view.findViewById(R.id.radio1);
rdc=(RadioButton)view.findViewById(R.id.radio2);
//zet de radiobuttons klaar om geklikt te worden.
rda.setEnabled(true);
rdb.setEnabled(true);
rdc.setEnabled(true);
butNext=(Button)view.findViewById(R.id.btnNext);
btnToonAntwoord=(Button)view.findViewById(R.id.btnToonAntwoord);
txtResult = (TextView) view.findViewById(R.id.resultTextview);
setQuestionView(view);
setOnClickListeners(view);
return view;
}
private void setOnClickListeners(View v){
final View thisView = v;
butNext.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if(qid<8){
//zet de radiobuttons klaar om geklikt te worden.
rda.setEnabled(true);
rdb.setEnabled(true);
rdc.setEnabled(true);
//zet het resultaat terug op niets
txtResult.setText("");
//Wanneer het goed is, voeg 1 bij de score bij
RadioGroup grp = (RadioGroup) thisView.findViewById(R.id.radioGroup1);
RadioButton answer = (RadioButton) thisView.findViewById(grp.getCheckedRadioButtonId());
if (currentQ.getANSWER().equals(checkChecked(answer.getId()))) {
mListener.incrementScore();
}
currentQ=quesList.get(qid);
setQuestionView(thisView);
}else{
//ga naar het eindscherm met het resultaat.
mListener.navigeerEindscore();
}
}
});
btnToonAntwoord.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
RadioGroup grp = (RadioGroup) thisView.findViewById(R.id.radioGroup1);
RadioButton answer = (RadioButton) thisView.findViewById(grp.getCheckedRadioButtonId());
//toon de juiste boodschap aan de hand van het antwoord die gegeven is.
if (currentQ.getANSWER().equals(checkChecked(answer.getId()))) {
txtResult.setText(currentQ.getGoedeFeedback());
}else{
txtResult.setText(currentQ.getSlechteFeedback());
}
//zet de radiobuttons klaar om geklikt te worden.
rda.setEnabled(false);
rdb.setEnabled(false);
rdc.setEnabled(false);
}
});
}
private String checkChecked(int id) {
if(id == R.id.radio0){
return "A";
}else if(id == R.id.radio1){
return "B";
}else{
return "C";
}
}
private void setQuestionView(View v)
{
txtQuestion.setText(currentQ.getQUESTION());
rda.setText(currentQ.getOPTA());
rdb.setText(currentQ.getOPTB());
rdc.setText(currentQ.getOPTC());
qid++;
}
#Override
public void onAttach(Context context) {
super.onAttach(context);
if (context instanceof OnFragmentQuizInteractionListener) {
mListener = (OnFragmentQuizInteractionListener) context;
} else {
throw new RuntimeException(context.toString()
+ " must implement OnResultFragmentInteractionListener");
}
}
public interface OnFragmentQuizInteractionListener {
void incrementScore();
void resetScore();
void navigeerEindscore();
}
#Override
public void onDetach() {
super.onDetach();
mListener = null;
}
mainActivity:
{
public class MainActivity extends AppCompatActivity
implements NavigationView.OnNavigationItemSelectedListener,DashboardFragment.OnFragmentLoginInteractionListener,LoginFragment.OnFragmentLoginInteractionListener, RegistratieFragment.OnFragmentRegistratieInteractionListener,QuizFragment.OnFragmentQuizInteractionListener, ResultFragment.OnResultFragmentInteractionListener{
private FragmentManager fragmentManager;
public int quizScore;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
Utils.onActivityCreateSetTheme(this);
setContentView(R.layout.activity_main);
quizScore = 0;
SharedPreferences pref = PreferenceManager
.getDefaultSharedPreferences(this);
String themeName = pref.getString("Theme1", "Blauw");
//toolbar ophalen
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
Log.i("huidige preferences", themeName);
//toolbar instellen
setSupportActionBar(toolbar);
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.addDrawerListener(toggle);
toggle.syncState();
/**if (themeName.equals("Blauw")) {
setTheme(R.style.AppTheme_blauw);
Log.i("MyActivity", "in blauw");
} else if (themeName.equals("Groen")) {
this.setTheme(R.style.AppTheme_groen);
Log.i("MyActivity", "in groen");
} else if (themeName.equals("Roze")) {
this.setTheme(R.style.AppTheme_roze);
Log.i("MyActivity", "in roze");
}**/
fragmentManager = getFragmentManager();
NavigationView navigationView = (NavigationView) findViewById(R.id.nav_view);
navigationView.setNavigationItemSelectedListener(this);
fragmentManager.beginTransaction().replace(R.id.content_frame, new DashboardFragment()).commit();
}
//backknop werkt hoe hij moet werken
#Override
public void onBackPressed() {
DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
int count = getFragmentManager().getBackStackEntryCount();
if (drawer.isDrawerOpen(GravityCompat.START)) {
drawer.closeDrawer(GravityCompat.START);
} else {
if (count == 0) {
super.onBackPressed();
//additional code
} else {
getFragmentManager().popBackStack();
}
}
}
#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) {
// 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.
switch (item.getItemId()) {
case R.id.action_settings:
fragmentManager.beginTransaction().replace(R.id.content_frame, new InstellingenFragment()).commit();
return true;
}
return super.onOptionsItemSelected(item);
}
//region dashboard
public void MijnProfielClicked() {
getFragmentManager().beginTransaction().replace(R.id.content_frame, new MijnProfielFragment())
.addToBackStack("MijnProfiel")
.commit();
}
public void AlarmClicked() {
getFragmentManager().beginTransaction().replace(R.id.content_frame, new PilAlarmFragment())
.addToBackStack("Pilalarm")
.commit();
}
public void KalenderClicked() {
getFragmentManager().beginTransaction().replace(R.id.content_frame, new MenstruatieFragment())
.addToBackStack("Kalender")
.commit();
}
//endregion
//Navigatiemethodes LOGIN
public void Login() {
getFragmentManager().beginTransaction().replace(R.id.content_frame, new DashboardFragment())
.addToBackStack("Login")
.commit();
}
//Navigatiemethodes REGISTREREN
public void Registreer() {
getFragmentManager().beginTransaction().replace(R.id.content_frame, new DashboardFragment())
.addToBackStack("Registreer")
.commit();
}
public void Annuleren() {
getFragmentManager().beginTransaction().replace(R.id.content_frame, new LoginFragment())
.addToBackStack("Registreer")
.commit();
}
#SuppressWarnings("StatementWithEmptyBody")
#Override
public boolean onNavigationItemSelected(MenuItem item) {
// Handle navigation view item clicks here.
switch (item.getItemId()) {
case R.id.nav_dashboard_layout:
fragmentManager.beginTransaction().replace(R.id.content_frame, new DashboardFragment()).addToBackStack("dashboard").commit();
break;
case R.id.nav_mijnprofiel_layout:
fragmentManager.beginTransaction().replace(R.id.content_frame, new MijnProfielFragment()).addToBackStack("mijnprofiel").commit();
break;
case R.id.nav_categorieen_layout:
fragmentManager.beginTransaction().replace(R.id.content_frame, new CategorieenFragment()).addToBackStack("categorieen").commit();
break;
case R.id.nav_pilalarm_layout:
fragmentManager.beginTransaction().replace(R.id.content_frame, new PilAlarmFragment()).addToBackStack("pilalarm").commit();
break;
case R.id.nav_menstruatie_layout:
fragmentManager.beginTransaction().replace(R.id.content_frame, new MenstruatieFragment()).addToBackStack("menstruatie").commit();
break;
case R.id.nav_quiz_layout:
fragmentManager.beginTransaction().replace(R.id.content_frame, new QuizFragment()).addToBackStack("quiz").commit();
break;
case R.id.nav_instellingen_layout:
fragmentManager.beginTransaction().replace(R.id.content_frame, new InstellingenFragment()).addToBackStack("instellingen").commit();
break;
case R.id.nav_partners_layout:
fragmentManager.beginTransaction().replace(R.id.content_frame, new PartnersFragment()).addToBackStack("partners").commit();
break;
}
DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
drawer.closeDrawer(GravityCompat.START);
return true;
}
//region Partner onclick listeners
public void onVivesPartner_clicked(View view) {
// Perform action on click
goToUrl("http://www.vives.be/");
}
public void onSensoaPartner_clicked(View view) {
// Perform action on click
goToUrl("http://www.sensoa.be/");
}
public void onUgentPartner_clicked(View view) {
// Perform action on click
goToUrl("http://www.ugent.be/");
}
public void onUCCVPartner_clicked(View view) {
// Perform action on click
goToUrl("http://www.ucvvgent.be/nl/");
}
public void onOnePartner_clicked(View view) {
// Perform action on click
goToUrl("http://www.one.be//");
}
private void goToUrl(String url) {
Uri uriUrl = Uri.parse(url);
Intent launchBrowser = new Intent(Intent.ACTION_VIEW, uriUrl);
startActivity(launchBrowser);
}
//endregion
//region quizfragment
#Override
public void incrementScore() {
quizScore++;
}
#Override
public void resetScore() {
quizScore = 0;
}
#Override
public void navigeerEindscore() {
fragmentManager.beginTransaction().replace(R.id.content_frame, new ResultFragment()).commit();
}
#Override
public int getScore() {
return quizScore;
}
//endregion
The error I'm getting (doesn't matter what fragment, it's always nullpointerexception on the mlistener)
java.lang.NullPointerException: Attempt to invoke interface method 'void be.vives.pwo_kinderwens.Quiz.QuizFragment$OnFragmentQuizInteractionListener.resetScore()' on a null object reference
at be.vives.pwo_kinderwens.Quiz.QuizFragment.onCreateView(QuizFragment.java:55)
at android.app.Fragment.performCreateView(Fragment.java:2053)
at android.app.FragmentManagerImpl.moveToState(FragmentManager.java:894)
at android.app.FragmentManagerImpl.moveToState(FragmentManager.java:1067)
at android.app.BackStackRecord.run(BackStackRecord.java:834)
at android.app.FragmentManagerImpl.execPendingActions(FragmentManager.java:1452)
at android.app.FragmentManagerImpl$1.run(FragmentManager.java:447)
at android.os.Handler.handleCallback(Handler.java:739)
at android.os.Handler.dispatchMessage(Handler.java:95)
at android.os.Looper.loop(Looper.java:135)
at android.app.ActivityThread.main(ActivityThread.java:5294)
at java.lang.reflect.Method.invoke(Native Method)
at java.lang.reflect.Method.invoke(Method.java:372)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:904)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:699)
The problem is that your mListener is not implemented.
I would try the following:
I would add a method to QuizFragment like :
public void setFragmentQuizInteractionListener(OnFragmentQuizInteractionListener mListener)
{
this.mListener = mListener;
}
And then
case R.id.nav_quiz_layout:
QuizFragment quizFragment = new QuizFragment();
quizFragment.setFragmentQuizInteractionListener(this);
fragmentManager.beginTransaction().replace(R.id.content_frame, quizFragment ).addToBackStack("quiz").commit();
break;
And drop the onAttach() method.
Probably not the nicest way but worth a try.
You need to override
public void onAttach (Activity activity)
instead of
public void onAttach (Context context)
The latter was included in API level 23, so previous versions of Android will not call it.
See onAttach (Activity activity)
Use onAttach method in Fragment. Check Fragment Lifecycle
Context context;
#Override
public void onAttach(Context context) {
super.onAttach(context);
this.context=context;
}