How to show activity (which cannot be converted to fragment) using BottomNavigationBar? - java

I have problem with showing my activity. I don't know how to implement methods from NoteActivity to HomeFragment. HomeFragment is carried out by BottomNavigationBar without executing a NoteActivity.
NoteActivity-
public class NoteActivity extends AppCompatActivity {
private FirebaseFirestore db = FirebaseFirestore.getInstance();
private CollectionReference notebookRef = db.collection("Notebook");
private NoteAdapter adapter;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.fragment_home);
setUpRecyclerView();
}
public void setUpRecyclerView() {
Query query = notebookRef.orderBy("title", Query.Direction.DESCENDING);
FirestoreRecyclerOptions<Note> options = new FirestoreRecyclerOptions.Builder<Note>()
.setQuery(query, Note.class)
.build();
adapter = new NoteAdapter(options);
RecyclerView recyclerView = findViewById(R.id.recycler_view);
recyclerView.setHasFixedSize(true);
recyclerView.setLayoutManager(new LinearLayoutManager(this));
recyclerView.setAdapter(adapter);
}
#Override
protected void onStart() {
super.onStart();
adapter.startListening();
}
#Override
protected void onStop() {
super.onStop();
adapter.stopListening();
}
}
Simple HomeFragment which should have content of NoteActivity-
public class HomeFragment extends Fragment {
#Nullable
public View onCreateView(LayoutInflater inflater, #Nullable ViewGroup container, #Nullable Bundle savedInstanceState) {
return inflater.inflate(R.layout.fragment_home, container, false);
}
}
BottomNavigationBar which is executing HomeFragment and 2 more activities -
public class BottomNavigationBar extends AppCompatActivity {
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_bottom);
BottomNavigationView bottomNav = findViewById(R.id.bottom_navigation);
bottomNav.setOnNavigationItemSelectedListener(navListener);
bottomNav.setSelectedItemId(R.id.nav_home);
}
private BottomNavigationView.OnNavigationItemSelectedListener navListener =
new BottomNavigationView.OnNavigationItemSelectedListener() {
#Override
public boolean onNavigationItemSelected(#NonNull MenuItem item) {
Fragment selectedFragment = null;
switch (item.getItemId()) {
case R.id.nav_home:
selectedFragment = new HomeFragment();
break;
case R.id.nav_game:
selectedFragment = new GameFragment();
break;
case R.id.nav_user:
selectedFragment = new UserFragment();
break;
}
getSupportFragmentManager()
.beginTransaction()
.replace(R.id.fragment_container,
selectedFragment)
.commit();
return true;
}
};
}
Please help, thanks.

Related

Saving State In Fragment With ViewPager Android Studio

Need a little help on how to approach saving state in my single activity application. I looked at a few resources but couldn't quite find one that fits the build. Essentially I have single activity with a Fragment container view that I'm using to swap out fragments as needed. My issue is that as my activity is destroyed when a lifecycle event occurs, the fragment with my view pager is restored but the individual fragments on the tabs are not loaded. I cannot figure out how to save the state properly. Below is my code:
Activity:
public class StartActivity extends AppCompatActivity {
FirebaseAuth mAuth;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_start);
mAuth = FirebaseAuth.getInstance();
if (savedInstanceState == null) {
LoginFragment fragment = new LoginFragment();
getSupportFragmentManager()
.beginTransaction()
.add(R.id.frameLayout, fragment)
.commit();
}
}
#Override
public void onStart() {
super.onStart();
FirebaseUser currentUser = mAuth.getCurrentUser();
if(currentUser != null){
MainActivity mainActivityFrag = new MainActivity();
getSupportFragmentManager()
.beginTransaction()
.add(R.id.frameLayout, mainActivityFrag)
.commit();
}
}
#Override
public void onSaveInstanceState(#NonNull Bundle outState, #NonNull PersistableBundle outPersistentState) {
super.onSaveInstanceState(outState, outPersistentState);
}
#Override
protected void onRestoreInstanceState(#NonNull Bundle savedInstanceState) {
super.onRestoreInstanceState(savedInstanceState);
}
}
Fragment With View Pager:
public class MainActivity extends Fragment {
private FirebaseAuth mAuth;
private SectionsPagerAdapter sectionsPagerAdapter;
private ViewPager viewPager;
private TabLayout tabs;
private Toolbar toolbar;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
mAuth = mAuth = FirebaseAuth.getInstance();
}
#Nullable
#Override
public View onCreateView(#NonNull LayoutInflater inflater, #Nullable ViewGroup container, #Nullable Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.activity_main, container, false);
sectionsPagerAdapter = new SectionsPagerAdapter(getContext(),((AppCompatActivity)getActivity()).getSupportFragmentManager());
viewPager = view.findViewById(R.id.view_pager);
viewPager.setAdapter(sectionsPagerAdapter);
tabs = view.findViewById(R.id.tabs);
tabs.setupWithViewPager(viewPager);
tabs.showContextMenu();
toolbar = view.findViewById(R.id.topAppBar);
((AppCompatActivity)getActivity()).setSupportActionBar(toolbar);
((AppCompatActivity)getActivity()).getSupportActionBar().setDisplayShowTitleEnabled(false);
setHasOptionsMenu(true);
tabs.getTabAt(0).setIcon(R.drawable.home_selector);
tabs.getTabAt(1).setIcon(R.drawable.destination);
tabs.getTabAt(2).setIcon(R.drawable.mail_outline_blk);
tabs.getTabAt(3).setIcon(R.drawable.notification_bell);
return view;
}
#Override
public void onCreateOptionsMenu(#NonNull Menu menu, #NonNull MenuInflater inflater) {
super.onCreateOptionsMenu(menu, inflater);
menu.clear();
inflater.inflate(R.menu.main_menu, menu);
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
super.onOptionsItemSelected(item);
switch (item.getItemId()){
case R.id.logout:
mAuth.signOut();
//navigate to home fragment
LoginFragment fragment = new LoginFragment();
((AppCompatActivity)getActivity()).getSupportFragmentManager()
.beginTransaction()
.replace(R.id.frameLayout, fragment)
.commit();
return true;
default:
return false;
}
}
#Override
public void onResume() {
super.onResume();
}
#Override
public void onSaveInstanceState(#NonNull Bundle outState) {
super.onSaveInstanceState(outState);
}
}
Adapter Code:
public class SectionsPagerAdapter extends FragmentPagerAdapter {
#StringRes
private static final int[] TAB_TITLES = new int[]{R.string.tab_text_1, R.string.tab_text_2, R.string.tab_text_3, R.string.tab_text_4};
private final Context mContext;
public SectionsPagerAdapter(Context context, FragmentManager fm) {
super(fm, BEHAVIOR_RESUME_ONLY_CURRENT_FRAGMENT);
mContext = context;
}
#Override
public Fragment getItem(int position) {
// getItem is called to instantiate the fragment for the given page.
// Return a PlaceholderFragment (defined as a static inner class below).
switch (position){
case 0:
PostFragment postFragment = new PostFragment();
return postFragment;
case 1:
TestFragment userFeedFragmentt = new TestFragment();
return userFeedFragmentt;
default:
TestFragment userFeedFragmenttt = new TestFragment();
return userFeedFragmenttt;
}
}
#Nullable
#Override
public CharSequence getPageTitle(int position) {
return mContext.getResources().getString(TAB_TITLES[position]);
}
#Override
public int getCount() {
// Show 2 total pages.
return 4;
}
}

How to close Unity without closing the entire app when changing fragments in Android Studio?

I have an app that the user can go through different fragments using BottomNavigationView and one of those fragments is a Unity3D application. So when i open the Unity fragment it works but when i open another fragment and open the Unity fragment back it crashes how do i fix this here is my code.
MainActivity.java
public class MainActivity extends AppCompatActivity {
BottomNavigationView mBottomNavigationView;
NavController mNavController;
NavDestination mDestination;
AppBarConfiguration appBarConfiguration;
String tab;
private boolean doubleBackToExitPressedOnce ;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
boolean b = this.requestWindowFeature(Window.FEATURE_NO_TITLE);
this.setContentView(R.layout.activity_main);
ActionBar mActionBar = getSupportActionBar();
mActionBar.setDisplayShowHomeEnabled(false);
mActionBar.setDisplayShowTitleEnabled(false);
LayoutInflater li = LayoutInflater.from(this);
View customView = li.inflate(R.layout.top_menu_custom, null);
mActionBar.setCustomView(customView);
mActionBar.setDisplayShowCustomEnabled(true);
mBottomNavigationView = (BottomNavigationView) findViewById(R.id.nav_view);
ImageButton profileButton = (ImageButton) customView.findViewById(R.id.profile_button);
ImageButton notificationButton = (ImageButton) customView.findViewById(R.id.noti_button);
profileButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
ProfileFragment profileFragment = new ProfileFragment();
getSupportFragmentManager().beginTransaction()
.replace(R.id.nav_host_fragment,profileFragment)
.addToBackStack(tab)
.setReorderingAllowed(true)
.commit();
mBottomNavigationView.setVisibility(View.GONE);
}
});
notificationButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
NotificationFragment notificationFragment = new NotificationFragment();
getSupportFragmentManager().beginTransaction()
.replace(R.id.nav_host_fragment,notificationFragment)
.addToBackStack(tab)
.setReorderingAllowed(true)
.commit();
mBottomNavigationView.setVisibility(View.GONE);
}
});
mBottomNavigationView.setItemIconTintList(null);
mBottomNavigationView.setItemTextColor(ColorStateList.valueOf(getColor(R.color.black)));
mNavController = Navigation.findNavController(this, R.id.nav_host_fragment);
// Passing each menu ID as a set of Ids because each
// menu should be considered as top level destinations.
appBarConfiguration = new AppBarConfiguration.Builder(
R.id.navigation_home, R.id.navigation_dashboard,R.id.navigation_map, R.id.navigation_card,R.id.navigation_deals)
.build();
NavigationUI.setupActionBarWithNavController(this, mNavController, appBarConfiguration);
NavigationUI.setupWithNavController(mBottomNavigationView, mNavController);
mNavController.addOnDestinationChangedListener(new NavController.OnDestinationChangedListener() {
#Override
public void onDestinationChanged(#NonNull NavController controller, #NonNull NavDestination destination, #Nullable Bundle arguments) {
Toast.makeText(getApplicationContext(),"hi",Toast.LENGTH_SHORT).show();
mDestination = mNavController.getCurrentDestination();
tab = mDestination.toString();
}
});
}
#Override
public void onBackPressed() {
//Toast.makeText(getApplicationContext(), mDestination.toString(),Toast.LENGTH_SHORT).show();
if (doubleBackToExitPressedOnce) {
getSupportFragmentManager().popBackStackImmediate();
mNavController.navigate(mDestination.getId());
mBottomNavigationView.setVisibility(View.VISIBLE);
super.onBackPressed();
return;
}
this.doubleBackToExitPressedOnce = true;
Toast.makeText(this, "Please click BACK again to exit", Toast.LENGTH_SHORT).show();
new Handler().postDelayed(new Runnable() {
#Override
public void run() {
doubleBackToExitPressedOnce=false;
}
}, 2000);
}
UnityMapFragment
public class MapFragment extends Fragment{
protected UnityPlayer mUnityPlayer;
FrameLayout frameLayoutForUnity;
public MapFragment() {
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
mUnityPlayer = new UnityPlayer(getActivity());
View view = inflater.inflate(R.layout.fragment_map, container, false);
this.frameLayoutForUnity = (FrameLayout) view.findViewById(R.id.frameLayoutForUnity);
this.frameLayoutForUnity.addView(mUnityPlayer.getView(),
FrameLayout.LayoutParams.MATCH_PARENT, FrameLayout.LayoutParams.MATCH_PARENT);
mUnityPlayer.requestFocus();
mUnityPlayer.windowFocusChanged(true);
return view;
}
#Override
public void onPause() {
super.onPause();
mUnityPlayer.pause();
}
#Override
public void onResume() {
super.onResume();
mUnityPlayer.resume();
}
// Quit Unity
#Override
public void onDestroy ()
{
mUnityPlayer.quit();
super.onDestroy();
}
So I managed to make a solution for this problem don't know if its good to make it this way or not but what i did was I instantiate the UnityPlayer in my MainActivity and in my fragment i call upon the UnityPlayer that was instatiated in my Main Activity.
MainActivity.java
public class MainActivity extends AppCompatActivity {
public BottomNavigationView mBottomNavigationView;
public NavController mNavController;
public NavDestination mDestination;
AppBarConfiguration appBarConfiguration;
String tab;
int onBackTimes = 0;
public UnityPlayer mUnityPlayer; <----Call unity player
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
mUnityPlayer = new UnityPlayer(this); <----UNITY PLAYER HERE
boolean b = this.requestWindowFeature(Window.FEATURE_NO_TITLE);
this.setContentView(R.layout.activity_main);
ActionBar mActionBar = getSupportActionBar();
mActionBar.setDisplayShowHomeEnabled(false);
mActionBar.setDisplayShowTitleEnabled(false);
LayoutInflater li = LayoutInflater.from(this);
View customView = li.inflate(R.layout.top_menu_custom, null);
mActionBar.setCustomView(customView);
mActionBar.setDisplayShowCustomEnabled(true);
mBottomNavigationView = (BottomNavigationView) findViewById(R.id.nav_view);
ImageButton profileButton = (ImageButton) customView.findViewById(R.id.profile_button);
ImageButton notificationButton = (ImageButton) customView.findViewById(R.id.noti_button);
profileButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
ProfileFragment profileFragment = new ProfileFragment();
getSupportFragmentManager().beginTransaction()
.replace(R.id.nav_host_fragment,profileFragment)
.addToBackStack(tab)
.setReorderingAllowed(true)
.commit();
mBottomNavigationView.setVisibility(View.GONE);
}
});
notificationButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
NotificationFragment notificationFragment = new NotificationFragment();
getSupportFragmentManager().beginTransaction()
.replace(R.id.nav_host_fragment,notificationFragment)
.addToBackStack(tab)
.setReorderingAllowed(true)
.commit();
mBottomNavigationView.setVisibility(View.GONE);
}
});
mBottomNavigationView.setItemIconTintList(null);
mBottomNavigationView.setItemTextColor(ColorStateList.valueOf(getColor(R.color.black)));
mNavController = Navigation.findNavController(this, R.id.nav_host_fragment);
// Passing each menu ID as a set of Ids because each
// menu should be considered as top level destinations.
appBarConfiguration = new AppBarConfiguration.Builder(
R.id.navigation_home, R.id.navigation_dashboard,R.id.navigation_map, R.id.navigation_card,R.id.navigation_deals)
.build();
NavigationUI.setupActionBarWithNavController(this, mNavController, appBarConfiguration);
NavigationUI.setupWithNavController(mBottomNavigationView, mNavController);
mNavController.addOnDestinationChangedListener(new NavController.OnDestinationChangedListener() {
#Override
public void onDestinationChanged(#NonNull NavController controller, #NonNull NavDestination destination, #Nullable Bundle arguments) {
mDestination = mNavController.getCurrentDestination();
tab = mDestination.toString();
}
});
}
#Override
public void onBackPressed() {
Toast.makeText(this, "Please click BACK again to exit", Toast.LENGTH_SHORT).show();
onBackTimes +=1;
if(onBackTimes>1){
LoginActivity.close.finish();
finish();
}
else{
getSupportFragmentManager().popBackStackImmediate();
mBottomNavigationView.setVisibility(View.VISIBLE);
super.onBackPressed();
mNavController.navigate(mDestination.getId());
}
new Handler().postDelayed(new Runnable() {
#Override
public void run() {
onBackTimes=0;
}
}, 2000);
}
#Override
protected void onStop() {
super.onStop();
}
//UNITY STUFF OVER HERE
#Override
protected void onPause() {
super.onPause();
mUnityPlayer.pause();
}
#Override protected void onResume()
{
super.onResume();
mUnityPlayer.resume();
}
#Override
protected void onDestroy(){
super.onDestroy();
}
}
UnityMapFragment
public class MapFragment extends Fragment{
private MainActivity mUnityMainActivity;
private UnityPlayer mUnityPlayer;
public MapFragment() {
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
//this code calls the UNITYPLAYER from MainActivity and return it here
mUnityMainActivity = (MainActivity) getActivity();
View unityPlayViewer = mUnityMainActivity.mUnityPlayer.getView();
mUnityMainActivity.mUnityPlayer.requestFocus();
mUnityMainActivity.mUnityPlayer.windowFocusChanged(true);
return unityPlayViewer;
}
/** FOR UNITY **/
#Override
public void onPause() {
super.onPause();
mUnityMainActivity.mUnityPlayer.pause();
}
// Resume Unity
#Override public void onResume()
{
super.onResume();
mUnityMainActivity.mUnityPlayer.resume();
}
I don't know why i have to include the OnPause, OnResume etc on both file but if one of them doesn't have it it'll crash.
The problem is, a new UnityPlayer is being created every-time we switch to the unity fragment and this crashes the app. So we need to create the UnityPlayer only for the first time or only when the player has been stopped. This works on my side.
In the UnityFragment class, my global variables :
protected UnityPlayer mUnityPlayer;
private View view;
private FrameLayout frameLayoutForUnity;
In onCreate a new UnityPlayer is created, which is called only for the first time :
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
mUnityPlayer = new UnityPlayer(getActivity()); // create Unity Player
}
In onCreateView we refresh the view for UnityPlayer :
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
if(mUnityPlayer.getParent() != null){
((ViewGroup)mUnityPlayer.getParent()).removeAllViews();
}
view = inflater.inflate(R.layout.fragment_unity, container, false);
this.frameLayoutForUnity = (FrameLayout) view.findViewById(R.id.unityFragmentLayout);
this.frameLayoutForUnity.addView(mUnityPlayer.getView(),
FrameLayout.LayoutParams.MATCH_PARENT, FrameLayout.LayoutParams.MATCH_PARENT);
mUnityPlayer.requestFocus();
mUnityPlayer.windowFocusChanged(true);
return view;
}
Rest remains same. There could be better solutions than this. Cheers :)

How to implement RecyclerView to Fragment of BottomNavigationBar? [duplicate]

I have problem with showing my activity. I don't know how to implement methods from NoteActivity to HomeFragment. HomeFragment is carried out by BottomNavigationBar without executing a NoteActivity.
NoteActivity-
public class NoteActivity extends AppCompatActivity {
private FirebaseFirestore db = FirebaseFirestore.getInstance();
private CollectionReference notebookRef = db.collection("Notebook");
private NoteAdapter adapter;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.fragment_home);
setUpRecyclerView();
}
public void setUpRecyclerView() {
Query query = notebookRef.orderBy("title", Query.Direction.DESCENDING);
FirestoreRecyclerOptions<Note> options = new FirestoreRecyclerOptions.Builder<Note>()
.setQuery(query, Note.class)
.build();
adapter = new NoteAdapter(options);
RecyclerView recyclerView = findViewById(R.id.recycler_view);
recyclerView.setHasFixedSize(true);
recyclerView.setLayoutManager(new LinearLayoutManager(this));
recyclerView.setAdapter(adapter);
}
#Override
protected void onStart() {
super.onStart();
adapter.startListening();
}
#Override
protected void onStop() {
super.onStop();
adapter.stopListening();
}
}
Simple HomeFragment which should have content of NoteActivity-
public class HomeFragment extends Fragment {
#Nullable
public View onCreateView(LayoutInflater inflater, #Nullable ViewGroup container, #Nullable Bundle savedInstanceState) {
return inflater.inflate(R.layout.fragment_home, container, false);
}
}
BottomNavigationBar which is executing HomeFragment and 2 more activities -
public class BottomNavigationBar extends AppCompatActivity {
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_bottom);
BottomNavigationView bottomNav = findViewById(R.id.bottom_navigation);
bottomNav.setOnNavigationItemSelectedListener(navListener);
bottomNav.setSelectedItemId(R.id.nav_home);
}
private BottomNavigationView.OnNavigationItemSelectedListener navListener =
new BottomNavigationView.OnNavigationItemSelectedListener() {
#Override
public boolean onNavigationItemSelected(#NonNull MenuItem item) {
Fragment selectedFragment = null;
switch (item.getItemId()) {
case R.id.nav_home:
selectedFragment = new HomeFragment();
break;
case R.id.nav_game:
selectedFragment = new GameFragment();
break;
case R.id.nav_user:
selectedFragment = new UserFragment();
break;
}
getSupportFragmentManager()
.beginTransaction()
.replace(R.id.fragment_container,
selectedFragment)
.commit();
return true;
}
};
}
Please help, thanks.

Fragment Error when using Firebase for Android

I am creating a bottom navigation for my android app. I am having the user login using Firebase and going into the first screen(home fragment). This fragment reads a JSON file and displays information which works fine.
The problem:
When you click to switch to the Profile Fragment the app crashes and gives a Fatal error and I do not know how to fix this. I am relatively new to Android and I have tried many different "solution" with no success. Below are my fragments and main activity.
MainActivity.java
public class MainActivity extends AppCompatActivity implements BottomNavigationView.OnNavigationItemSelectedListener {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
loadFragment(new HomeFragment());
//getting bottom navigation view and attaching the listener
BottomNavigationView navigation = findViewById(R.id.navigation);
navigation.setOnNavigationItemSelectedListener(this);
}
private boolean loadFragment(Fragment fragment) {
//switching fragment
if (fragment != null) {
getSupportFragmentManager()
.beginTransaction()
.replace(R.id.fragment_container, fragment)
.commit();
return true;
}
return false;
}
#Override
public boolean onNavigationItemSelected(#NonNull MenuItem item) {
Fragment fragment = null;
switch (item.getItemId()) {
case R.id.navigation_home:
fragment = new HomeFragment();
break;
case R.id.navigation_dashboard:
fragment = new DashboardFragment();
break;
case R.id.navigation_profile:
fragment = new ProfileFragment();
break;
}
return loadFragment(fragment);
}
}
HomeFragment.java
public class HomeFragment extends Fragment {
RecyclerView recyclerView;
List<Articles> articles;
View rootView;
private static String JSON_URL = "https://www.britbound.com/json/articles.json";
Adapter adapter;
#Nullable
#Override
public View onCreateView(LayoutInflater inflater, #Nullable ViewGroup container, #Nullable Bundle savedInstanceState) {
rootView = inflater.inflate(R.layout.fragment_home, container, false);
recyclerView = rootView.findViewById((R.id.recView_articles));
articles = new ArrayList<>();
extractArticles();
return rootView;
}
private void extractArticles(){
RequestQueue queue = Volley.newRequestQueue(getContext());
JsonObjectRequest jsonObjectRequest = new JsonObjectRequest(
Request.Method.GET,
JSON_URL,
null,
new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject response) {
try{
JSONArray array = response.getJSONArray("articles");
for(int i=0;i<array.length();i++){
Articles article = new Articles();
JSONObject articleObj = array.getJSONObject(i);
article.setTitle(articleObj.getString("title").toString());
article.setPublishDate("Published: "+articleObj.getString("date_published").toString());
article.setExcerpt(articleObj.getString("excerpt").toString());
article.setThumbnail(articleObj.getString("thumbnail").toString());
articles.add(article);
}
}catch (JSONException e){
e.printStackTrace();
}
recyclerView.setLayoutManager(new LinearLayoutManager(getContext()));
adapter = new Adapter(getContext(), articles);
recyclerView.setAdapter(adapter);
}
},
new Response.ErrorListener(){
#Override
public void onErrorResponse(VolleyError error){
// Do something when error occurred
Log.d("tag", "onErrorResponse: " + error.getMessage());
}
}
);
// Add JsonObjectRequest to the RequestQueue
queue.add(jsonObjectRequest);
}
}
ProfileFragment.java
public class ProfileFragment extends Fragment {
TextView fullname, email,phone, verifyMsg;
FirebaseAuth fAuth;
FirebaseFirestore fStore;
String userId;
Button resendCode;
View rootView;
#Nullable
#Override
public View onCreateView(LayoutInflater inflater, #Nullable ViewGroup container, #Nullable Bundle savedInstanceState) {
rootView = inflater.inflate(R.layout.fragment_profile, container, false);
phone = rootView.findViewById(R.id.txt_userphonenumber);
fullname = rootView.findViewById(R.id.txt_userfullname);
email = rootView.findViewById(R.id.txt_useremail);
verifyMsg = rootView.findViewById(R.id.txt_emailnotverified);
fAuth = FirebaseAuth.getInstance();
fStore = FirebaseFirestore.getInstance();
resendCode = rootView.findViewById(R.id.btn_verifyemail);
userId = fAuth.getCurrentUser().getUid();
final FirebaseUser user = fAuth.getCurrentUser();
if(!user.isEmailVerified()){
resendCode.setVisibility(View.VISIBLE);
verifyMsg.setVisibility(View.VISIBLE);
resendCode.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
user.sendEmailVerification().addOnSuccessListener(new OnSuccessListener<Void>() {
#Override
public void onSuccess(Void aVoid) {
Toast.makeText(getActivity(), "Verification email has been sent", Toast.LENGTH_SHORT).show();
}
}).addOnFailureListener(new OnFailureListener() {
private static final String TAG = "";
#Override
public void onFailure(#NonNull Exception e) {
Log.d(TAG, "onFailure: Email not sent " + e.getMessage());
}
});
}
});
}
DocumentReference documentReference = fStore.collection("users").document(userId);
ListenerRegistration registration = documentReference.addSnapshotListener(getActivity(), new EventListener<DocumentSnapshot>() {
#Override
public void onEvent(#Nullable DocumentSnapshot documentSnapshot, #Nullable FirebaseFirestoreException e) {
phone.setText(documentSnapshot.getString("phone"));
fullname.setText(documentSnapshot.getString("fullname"));
email.setText(documentSnapshot.getString("email"));
}
});
return rootView;
}
}
ERROR
--------- beginning of crash
E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.britbound.britboundsocial, PID: 6457
java.lang.IllegalStateException: FragmentManager is already executing transactions
at androidx.fragment.app.FragmentManager.ensureExecReady(FragmentManager.java:1776)
at androidx.fragment.app.FragmentManager.execPendingActions(FragmentManager.java:1841)
at androidx.fragment.app.FragmentManager.executePendingTransactions(FragmentManager.java:489)
at com.google.firebase.firestore.core.ActivityScope.lambda$onFragmentActivityStopCallOnce$1(com.google.firebase:firebase-firestore##21.4.0:180)
at com.google.firebase.firestore.core.ActivityScope$$Lambda$2.run(Unknown Source:4)
at android.app.Activity.runOnUiThread(Activity.java:6282)
at com.google.firebase.firestore.core.ActivityScope.onFragmentActivityStopCallOnce(com.google.firebase:firebase-firestore##21.4.0:164)
at com.google.firebase.firestore.core.ActivityScope.bind(com.google.firebase:firebase-firestore##21.4.0:192)
at com.google.firebase.firestore.DocumentReference.addSnapshotListenerInternal(com.google.firebase:firebase-firestore##21.4.0:514)
at com.google.firebase.firestore.DocumentReference.addSnapshotListener(com.google.firebase:firebase-firestore##21.4.0:456)
at com.google.firebase.firestore.DocumentReference.addSnapshotListener(com.google.firebase:firebase-firestore##21.4.0:397)
at com.britbound.britboundsocial.fragments.ProfileFragment.onCreateView(ProfileFragment.java:74)
at androidx.fragment.app.Fragment.performCreateView(Fragment.java:2698)
at androidx.fragment.app.FragmentStateManager.createView(FragmentStateManager.java:310)
at androidx.fragment.app.FragmentManager.moveToState(FragmentManager.java:1185)
at androidx.fragment.app.FragmentManager.moveToState(FragmentManager.java:1354)
at androidx.fragment.app.FragmentManager.moveFragmentToExpectedState(FragmentManager.java:1432)
at androidx.fragment.app.FragmentManager.moveToState(FragmentManager.java:1495)
at androidx.fragment.app.BackStackRecord.executeOps(BackStackRecord.java:447)
at androidx.fragment.app.FragmentManager.executeOps(FragmentManager.java:2167)
at androidx.fragment.app.FragmentManager.executeOpsTogether(FragmentManager.java:1990)
at androidx.fragment.app.FragmentManager.removeRedundantOperationsAndExecute(FragmentManager.java:1945)
at androidx.fragment.app.FragmentManager.execPendingActions(FragmentManager.java:1847)
at androidx.fragment.app.FragmentManager$4.run(FragmentManager.java:413)
at android.os.Handler.handleCallback(Handler.java:873)
at android.os.Handler.dispatchMessage(Handler.java:99)
at android.os.Looper.loop(Looper.java:193)
at android.app.ActivityThread.main(ActivityThread.java:6669)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:493)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:858)
I
Any help would be appreciated. Thank you!

ActionBar Title not show for specific fragments

I've 4 different fragments, however it doesn't show the title for any of the fragments. When i created the fragments, everything was working fine, however now no title shows up on the actionBar. I've done all the changes which i found on the stackoverflow, but non of them worked for me
the code for my main activity is :-
private ActionBar toolbar;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
toolbar = getSupportActionBar();
toolbar.setTitle("Home");
loadFragment(new home());
BottomNavigationView navigation = (BottomNavigationView)findViewById(R.id.navigation);
navigation.setOnNavigationItemSelectedListener(mOnNavigationItemSelectedListener);
}
private BottomNavigationView.OnNavigationItemSelectedListener mOnNavigationItemSelectedListener
= new BottomNavigationView.OnNavigationItemSelectedListener() {
#Override
public boolean onNavigationItemSelected(#NonNull MenuItem menuItem) {
Fragment fragment;
switch (menuItem.getItemId()){
case R.id.navigation_home:
toolbar.setTitle("Home");
fragment = new home();
loadFragment(fragment);
return true;
case R.id.navigation_dashboard:
toolbar.setTitle("Dashboard");
fragment = new Dashboard();
loadFragment(fragment);
return true;
case R.id.navigation_notifications:
toolbar.setTitle("Notifications");
fragment = new Notification();
loadFragment(fragment);
return true;
case R.id.navigation_profile:
toolbar.setTitle("Profile");
fragment = new Profile();
loadFragment(fragment);
return true;
}
return false;
}
};
private void loadFragment(Fragment fragment){
FragmentTransaction transaction = getSupportFragmentManager().beginTransaction();
transaction.replace(R.id.frame_container, fragment);
transaction.addToBackStack(null);
transaction.commit();
}
the code for one of the fragments which contains widgets(Rest of them are yet empty) is below :-
private OnFragmentInteractionListener mListener;
Button AskForHelp, Drafts, LogOut, Settings;
View view;
public Dashboard() {
// Required empty public constructor
}
public static Dashboard newInstance(String param1, String param2) {
Dashboard fragment = new Dashboard();
Bundle args = new Bundle();
args.putString(ARG_PARAM1, param1);
args.putString(ARG_PARAM2, param2);
fragment.setArguments(args);
return fragment;
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
if (getArguments() != null) {
mParam1 = getArguments().getString(ARG_PARAM1);
mParam2 = getArguments().getString(ARG_PARAM2);
}
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
view = inflater.inflate(R.layout.fragment_dashboard, container,false);
AskForHelp = (Button)view.findViewById(R.id.askHelp);
AskForHelp.setOnClickListener(this);
Drafts = (Button)view.findViewById(R.id.drafts);
Drafts.setOnClickListener(this);
LogOut = (Button)view.findViewById(R.id.logOut);
LogOut.setOnClickListener(this);
Settings = (Button)view.findViewById(R.id.settings);
Settings.setOnClickListener(this);
return view;
}
public void onButtonPressed(Uri uri) {
if (mListener != null) {
mListener.onFragmentInteraction(uri);
}
}
#Override
public void onDetach() {
super.onDetach();
mListener = null;
}
#Override
public void onClick(View v) {
switch (v.getId()){
case R.id.askHelp:
Intent intent = new Intent(getContext(), Questions.class);
startActivity(intent);
break;
case R.id.drafts:
Toast.makeText(getContext(),"Function not enabled", Toast.LENGTH_SHORT).show();
break;
case R.id.logOut:
Toast.makeText(getContext(),"Function not enabled", Toast.LENGTH_SHORT).show();
break;
case R.id.settings:
Toast.makeText(getContext(),"Function not enabled", Toast.LENGTH_SHORT).show();
break;
}
}
public interface OnFragmentInteractionListener {
void onFragmentInteraction(Uri uri);
}
I've tried almost everything mentioned below. But it's still the same
In fragment just put this line in onCreatView so it will set your fragment title each time when you load your fragment.
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
getActivity().setTitle("you title here");
...
}

Categories