Fragment Error when using Firebase for Android - java

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!

Related

BottomNavigation.setVisibility doesn't work

I create an application and use a BottomNavigationView in it and one of the fragments calls the other fragment through the adapter. I am trying to make the BottomNavigationView disappear when this fragment is called, for this I use setVisibility (). But the problem is that it doesn’t disappear, maybe someone can tell me what I’m doing wrong
BottomNavigationView:
public class ProfileFragment extends Fragment {
private ImageView avatar;
private TextView nickname, bio, website;
private FirebaseMethods mFirebaseMethods;
private Context mContext;
private AppBarLayout mAppBarLayout;
private Menu mMenu;
private RecyclerView mRecyclerView;
private FirebaseUser mCurrentUser;
private TextView followers, followings;
private BottomNavigationView mBottomNavigationView;
private String[] permissions = {Manifest.permission.WRITE_EXTERNAL_STORAGE, Manifest.permission.READ_EXTERNAL_STORAGE};
private ActivityResultContracts.RequestMultiplePermissions mRequestMultiplePermissions= new ActivityResultContracts.RequestMultiplePermissions();
private DatabaseReference mDatabaseReference;
private DatabaseReference followingRef;
private DatabaseReference followersRef;
private ReadWritePermissions mReadWritePermissions;
private IntentFilter filter = new IntentFilter(DownloadManager.ACTION_DOWNLOAD_COMPLETE);
private String mParam1;
private String mParam2;
public ProfileFragment() {
// Required empty public constructor
}
public static ProfileFragment newInstance(String param1, String param2) {
ProfileFragment fragment = new ProfileFragment();
Bundle args = new Bundle();
fragment.setArguments(args);
return fragment;
}
#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_profile2, container, false);
mContext = container.getContext();
mFirebaseMethods = new FirebaseMethods(mContext);
mCurrentUser = FirebaseAuth.getInstance().getCurrentUser();
mBottomNavigationView = getActivity().findViewById(R.id.bottomNavigation);
followingRef = FirebaseDatabase.getInstance().getReference("Following");
followersRef = FirebaseDatabase.getInstance().getReference("Followers");
Toolbar toolbar = view.findViewById(R.id.toolbar);
mAppBarLayout = view.findViewById(R.id.app_bar);
mRecyclerView = view.findViewById(R.id.posts_recycler);
((AppCompatActivity)getActivity()).setSupportActionBar(toolbar);
((AppCompatActivity)getActivity()).getSupportActionBar().setDisplayShowTitleEnabled(false);
setHasOptionsMenu(true);
toolbar.setNavigationOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
getActivity().finish();
}
});
loadPosts();
avatar = view.findViewById(R.id.profile_avatar);
nickname = view.findViewById(R.id.profile_nickname);
bio = view.findViewById(R.id.profile_bio);
website = view.findViewById(R.id.profile_website);
followers = view.findViewById(R.id.followers_count);
followings = view.findViewById(R.id.following_count);
setFollowingFollowers();
followers.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
FollowersFollowingsFragment fragment = new FollowersFollowingsFragment();
Bundle args = new Bundle();
args.putString("uid", mCurrentUser.getUid());
args.putString("followingsOrFollowers", "followers");
fragment.setArguments(args);
FragmentTransaction fragmentTransaction = getActivity().getSupportFragmentManager().beginTransaction();
fragmentTransaction.add(R.id.frame_container,fragment);
fragmentTransaction.addToBackStack(null);
fragmentTransaction.commit();
}
});
followings.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
FollowersFollowingsFragment fragment = new FollowersFollowingsFragment();
Bundle args = new Bundle();
args.putString("uid", mCurrentUser.getUid());
args.putString("followingsOrFollowers", "followers");
fragment.setArguments(args);
FragmentTransaction fragmentTransaction = getActivity().getSupportFragmentManager().beginTransaction();
fragmentTransaction.add(R.id.frame_container,fragment);
fragmentTransaction.addToBackStack(null);
fragmentTransaction.commit();
}
});
avatar.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
}
});
mFirebaseMethods.getUserDataProfile(avatar, nickname, bio);
return view;
}
private void loadPosts()
{
mReadWritePermissions = new ReadWritePermissions(getActivity().getLifecycle(), getActivity().getActivityResultRegistry());
getLifecycle().addObserver(mReadWritePermissions);
mCurrentUser = FirebaseAuth.getInstance().getCurrentUser();
mDatabaseReference = FirebaseDatabase.getInstance().getReference().child("Posts");
mRecyclerView.setLayoutManager(new LinearLayoutManager(getContext()));
FirebaseRecyclerOptions<Posts> options
= new FirebaseRecyclerOptions.Builder<Posts>()
.setQuery(mDatabaseReference.orderByChild("uid").equalTo(mCurrentUser.getUid()), Posts.class)
.build();
mReadWritePermissions = new ReadWritePermissions(getActivity().getLifecycle(), getActivity().getActivityResultRegistry());
getLifecycle().addObserver(mReadWritePermissions);
PostAdapter adapter = new PostAdapter(options, mContext, mReadWritePermissions);
mRecyclerView.setAdapter(adapter);
adapter.startListening();
}
private void setFollowingFollowers()
{
mCurrentUser = FirebaseAuth.getInstance().getCurrentUser();
followersRef.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot snapshot) {
followers.setText(Integer.toString((int)snapshot.child(mCurrentUser.getUid()).getChildrenCount()));
}
#Override
public void onCancelled(#NonNull DatabaseError error) {
}
});
followingRef.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot snapshot) {
followings.setText(Integer.toString((int)snapshot.child(mCurrentUser.getUid()).getChildrenCount()));
}
#Override
public void onCancelled(#NonNull DatabaseError error) {
}
});
}
#Override
public void onPause() {
super.onPause();
}
#Override
public void onResume() {
super.onResume();
}
}
Use setVisibility(View.GONE) instead.
I had the same problem, for some reason it doesn't work, but in the docs they also use View.GONE.
EDIT: Use the method shown in the docs to hide/show BottomNavigationView depending on the Fragment.
navController.addOnDestinationChangedListener(new NavController.OnDestinationChangedListener() {
#Override
public void onDestinationChanged(#NonNull NavController controller,
#NonNull NavDestination destination, #Nullable Bundle arguments) {
if(destination.getId() == R.id.full_screen_destination) {
toolbar.setVisibility(View.GONE);
bottomNavigationView.setVisibility(View.GONE);
} else {
toolbar.setVisibility(View.VISIBLE);
bottomNavigationView.setVisibility(View.VISIBLE);
}
}
});
Use Navigation component like in this example.
I fixed this by using DataBinding and ObservableField for the visibility, I don't why it didn't work through the normal onDestinationChangedListener on the NavController, it just bluntly ignored that command, everything else in that block worked fine but not the visibility.
So an ObservableField in the databinding did the trick
android:visibility="#{hideBottomNav ? View.GONE : View.VISIBLE}"
And set the value to the observable field in the onDestinationChangedListener to your desired outcome
if(destination.id == R.id.navigation_your_notes){
hideBottomNav.set(true)
} else hideBottomNav.set(false)

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

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.

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.

When I press the back button all the way to Login, the fields show the previous user data inserted

I'm making an android application on Java. The problem with this app is that when I'm in the main fragment and press the back button, I want it to go back to login (which happens) but the fields of username and password show the data from the last user and I want those fields to show empty like if the app was restarted.
This is my loginuser function inside of my login class.
public void loginUser() {
String url = MeuSingleton.servidor + "/login";
loginemail = email.getText().toString().trim();
loginpass = pass.getText().toString().trim();
StringRequest stringRequest = new StringRequest(Request.Method.POST, url,
new Response.Listener<String>() {
#Override
public void onResponse(String response) {
try {
if (response.length() == 9){
Toast.makeText(Login.this, "Login efectuado com sucesso!", Toast.LENGTH_SHORT).show();
Intent i = new Intent(Login.this, MainActivity.class);
startActivity(i);
} else {
mostrarErro(getString(R.string.tituloerro), getString(R.string.login_errado));
}
} catch (Exception e) {
mostrarErro(getString(R.string.tituloerro), getString(R.string.backenderro));
}
}
},
new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
mostrarErro(getString(R.string.tituloerro), getString(R.string.interneterro));
}
}) {
#Override
protected Map<String, String> getParams() throws AuthFailureError {
Map<String, String> map = new HashMap<String, String>();
map.put("email", loginemail);
map.put("password", loginpass);
return map;
}
};
MeuSingleton.getInstance(this).addToRequestQueue(stringRequest);
stringRequest.setRetryPolicy(new DefaultRetryPolicy(350, DefaultRetryPolicy.DEFAULT_MAX_RETRIES, DefaultRetryPolicy.DEFAULT_BACKOFF_MULT));
}
And this is my main activity class:
public class MainActivity extends AppCompatActivity implements
NavigationView.OnNavigationItemSelectedListener{
MainFragment mainFragment;
FragmentManager fragmentManager;
FragmentTransaction fragmentTransaction;
DrawerLayout drawer;
NavigationView navigationView;
ActionBarDrawerToggle toggle;
Toolbar toolbar;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
toolbar = findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
navigationView = findViewById(R.id.nested);
navigationView.setNavigationItemSelectedListener(this);
drawer = findViewById(R.id.drawer);
toggle = new ActionBarDrawerToggle(this,drawer,toolbar,R.string.open,R.string.close);
drawer.addDrawerListener(toggle);
toggle.setDrawerIndicatorEnabled(true);
toggle.syncState();
mainFragment = new MainFragment();
fragmentManager = getSupportFragmentManager();
fragmentTransaction = fragmentManager.beginTransaction();
fragmentTransaction.add(R.id.fragmentContainer,mainFragment);
fragmentTransaction.commit();// add the fragment
}
#Override
public boolean onNavigationItemSelected(#NonNull MenuItem menuItem) {
closeDrawer();
if(menuItem.getItemId() == R.id.submeteralerta){
loadFragment(new InsAlertaFragment());
}
if(menuItem.getItemId() == R.id.veralertas){
loadFragment(new SecondFragment());
}
if(menuItem.getItemId() == R.id.logout){
finish();
}
if(menuItem.getItemId() == R.id.sobremim){
loadFragment(new SobreMimFragment());
}
if(menuItem.getItemId() == R.id.ajuda){
loadFragment(new AjudaFragment());
}
return true;
}
private void loadFragment(Fragment secondFragment) {
fragmentManager = getSupportFragmentManager();
fragmentTransaction = fragmentManager.beginTransaction();
fragmentTransaction.replace(R.id.fragmentContainer,secondFragment);
fragmentTransaction.addToBackStack(null);
fragmentTransaction.commit();
}
private void closeDrawer() {
drawer.closeDrawer(GravityCompat.START);
}
}
And finally my main fragment, which is where I want to press back and go to Login:
public class MainFragment extends Fragment {
#Nullable
#Override
public View onCreateView(#NonNull LayoutInflater inflater, #Nullable ViewGroup container, #Nullable Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_main,container,false);
return view;
}
#Override
public void onViewCreated(#NonNull View view, #Nullable Bundle savedInstanceState) {
super.onViewCreated(view, savedInstanceState);
}
}
Thanks for the help!
If you want a Login activity with empty text fields when you go back, you could just clear the text fields out before you launch MainActivity. For example:
Toast.makeText(Login.this, "Login efectuado com sucesso!", Toast.LENGTH_SHORT).show();
email.setText("");
pass.setText("");
Intent i = new Intent(Login.this, MainActivity.class);
startActivity(i);

how can i refresh current fragment after inserting data?

i'm from indonesia, i want to refresh a fragment after i insert a data to it.. i have try many times to refresh a fragment. but it can't work.
please help me..
here's my code..
class MainActivity
public class MainActivity extends FragmentActivity {
public MainActivity() {
}
DatabaseReference dataBaseref;
StorageReference strRef;
TextView logout;
TabLayout tabLayout;
ViewPager viewPager;
ViewPagerAdapter viewAdapter = null;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
dataBaseref = FirebaseDatabase.getInstance().getReference();
strRef = FirebaseStorage.getInstance().getReference();
tabLayout = findViewById(R.id.tab_layout_isi_menu);
viewPager = findViewById(R.id.view_pager_isi_menu);
logout = findViewById(R.id.text_logout);
viewAdapter = new ViewPagerAdapter(getSupportFragmentManager(), MainActivity.this);
viewAdapter.addFragment(new isi_list_beli(), "Beli");
viewAdapter.addFragment(new isi_list_cek(), "Cek Data");
viewPager.setAdapter(viewAdapter);
tabLayout.setupWithViewPager(viewPager);
logout.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
logOut();
}
});
}
private void logOut() {
AuthUI.getInstance()
.signOut(MainActivity.this)
.addOnCompleteListener(new OnCompleteListener<Void>() {
#Override
public void onComplete(#NonNull Task<Void> task) {
startActivity(new Intent(MainActivity.this, LoginActivity.class));
finish();
}
}).addOnFailureListener(new OnFailureListener() {
#Override
public void onFailure(#NonNull Exception e) {
Toast.makeText(MainActivity.this, "" + e.getMessage(), Toast.LENGTH_LONG).show();
}
});
}
#Override
protected void onResume() {
super.onResume();
}
public void onBackPressed() {
super.finish();
}
}
class isi_list_cek
public class isi_list_cek extends Fragment {
private ListView listView;
public AdapterListCek adapterListCek = null;
private ArrayList<Cek> cekArrayList;
Cursor cursor;
View view;
FloatingActionButton fab;
#Override
public void onCreate(#Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
adapterListCek = new AdapterListCek(getContext(), R.layout.item_in_list_barang, cekArrayList);
adapterListCek.notifyDataSetChanged();
}
#Override
public View onCreateView(#NonNull LayoutInflater inflater, #Nullable ViewGroup container, #NonNull Bundle savedInstanceState) {
view = inflater.inflate(R.layout.list_barang, container, false);
listView = view.findViewById(R.id.list_item_barang);
fab = view.findViewById(R.id.tambah_barang);
cekArrayList = new ArrayList<>();
adapterListCek = new AdapterListCek(getContext(), R.layout.item_in_list_barang, cekArrayList);
listView.setAdapter(adapterListCek);
cursor = fragment_input_data.sqlHelper.getData("SELECT * FROM CEK");
if(cursor.moveToFirst()){
cekArrayList.clear();
do{
int id = cursor.getInt(0);
String kode = cursor.getString(1);
String nama = cursor.getString(2);
String jumlah = cursor.getString(3);
String harga = cursor.getString(4);
byte[] gambar = cursor.getBlob(5);
cekArrayList.add(new Cek(id, kode, nama, harga, jumlah, gambar));
}while (cursor.moveToNext());
fragment_input_data.sqlHelper.close();
}
adapterListCek.notifyDataSetChanged();
listView.setOnLongClickListener(new View.OnLongClickListener() {
#Override
public boolean onLongClick(View view) {
return false;
}
});
fab.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
startActivity(new Intent(getContext(), fragment_input_data.class));
}
});
return view;
}
#Override
public void onResume() {
super.onResume();
}
}
class ViewPagerAdapter
public class ViewPagerAdapter extends FragmentStatePagerAdapter {
private Map<Integer, String> mFragmentTags;
private FragmentManager mFragmentManager;
private Context mContext;
private final List<Fragment> fragmentList = new ArrayList<>();
private final List<String> fragmentListTitle = new ArrayList<>();
public ViewPagerAdapter(FragmentManager fm, Context mContext) {
super(fm);
}
#Override
public Fragment getItem(int position) {
return fragmentList.get(position);
}
#Override
public int getCount() {
return fragmentListTitle.size();
//return 2;
}
#NonNull
#Override
public CharSequence getPageTitle(int position) {
return fragmentListTitle.get(position);
}
public void addFragment (Fragment fragment, String string){
fragmentList.add(fragment);
fragmentListTitle.add(string);
}
}
i expect when i insert some data, fragment will automatically update it's view.
call a function as: just send the new instance of present fragment that you want to recreate
replaceFragment(new YourPresentFragment());
the function can be as below:
private void replaceFragment(Fragment fragment) {
String fragmentTag = fragment.getClass().getName();
FragmentManager manager = getFragmentManager();
FragmentTransaction ft = manager.beginTransaction();
ft.replace(R.id.fragments, fragment, fragmentTag);
ft.addToBackStack("fragments");
ft.commit();
}
this should do the job

Categories