I am very...very new to android development and I am trying to recreate a hybrid app I built in ionic, but do it in actual android.
I am having an issue with either layouts or fragment loading that I can't figure out.
What I want is something similar to the IG layout, where there is a bar at the bottom for navigation, clicking the button would load the new page. From my understanding the best way to accomplish that is to use a main activity, then each of the tabs at the bottom are fragments.
So I built that, but I want the top toolbar to disappear on the second tab, so in the second tab "onCreateView" method I added the toolbar.setVisibility(View.GONE); however, as soon as I load the app, even on the first tab, the toolbar at the top is gone, signifying it is loading the views for each fragment when the app loads. I would think that would severely impact performance on a large app. Am I crazy?
Here is my main layout for the main activity...
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/apk/res-auto"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:id="#+id/main_layout">
<android.support.v7.widget.Toolbar
android:id="#+id/toolbar"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_alignParentTop="true"
android:background="#color/colorPrimary"
android:elevation="6dp"
android:minHeight="?attr/actionBarSize"
android:theme="#style/ThemeOverlay.AppCompat.Dark.ActionBar"
app:popupTheme="#style/ThemeOverlay.AppCompat.Light" />
<android.support.v4.view.ViewPager
android:id="#+id/content"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_below="#+id/toolbar" />
<android.support.design.widget.TabLayout
android:id="#+id/tab_layout"
android:layout_width="match_parent"
android:layout_height="wrap_content"
app:tabMode="fixed"
android:gravity="center_horizontal"
android:layout_gravity="center_horizontal"
android:background="?attr/colorPrimary"
android:elevation="6dp"
app:tabSelectedTextColor="#FFFFFF"
app:tabTextColor="#D3D3D3"
app:tabIndicatorColor="#FF00FF"
android:minHeight="?attr/actionBarSize"
android:layout_alignParentBottom="true" />
</RelativeLayout>
Then my HomeActivity class..
public class HomeActivity extends BaseActivity implements OnFragmentTouched {
private TextView mTextMessage;
private static final String SELECTED_ITEM = "arg_selected_item";
private int mSelectedItem;
private BottomNavigationView mBottomNav;
private FirebaseUser user = FirebaseAuth.getInstance().getCurrentUser();
#Override
protected void onSaveInstanceState(Bundle outState) {
outState.putInt(SELECTED_ITEM, mSelectedItem);
super.onSaveInstanceState(outState);
}
#Override
public void onBackPressed() {
MenuItem homeItem = mBottomNav.getMenu().getItem(0);
if (mSelectedItem != homeItem.getItemId()) {
// select home item
selectFragment(homeItem);
} else {
super.onBackPressed();
}
}
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_home);
ViewPager pager = (ViewPager) findViewById(R.id.content);
PagerAdapter pagerAdapter = (PagerAdapter) new PagerAdapter(getSupportFragmentManager(), HomeActivity.this);
pager.setAdapter(pagerAdapter);
TabLayout tabLayout = (TabLayout) findViewById(R.id.tab_layout);
tabLayout.setupWithViewPager(pager);
for(int i = 0; i < tabLayout.getTabCount(); i++) {
TabLayout.Tab tab = tabLayout.getTabAt(i);
tab.setCustomView(pagerAdapter.getTabView(i));
}
}
private void selectFragment(MenuItem item) {
Fragment frag = null;
switch(item.getItemId()) {
case R.id.navigation_home:
frag = new AllPostsFragment();
break;
case R.id.navigation_dashboard:
frag = ProfileFragment.newInstance(user.getUid());
break;
case R.id.navigation_notifications:
frag = new ChatListFragment();
break;
}
mSelectedItem = item.getItemId();
}
#VisibleForTesting
public ProgressDialog mProgressDialog;
public void showProgressDialog() {
if (mProgressDialog == null) {
mProgressDialog = new ProgressDialog(this);
mProgressDialog.setMessage(getString(R.string.loading));
mProgressDialog.setIndeterminate(true);
}
mProgressDialog.show();
}
public void hideProgressDialog() {
if (mProgressDialog != null && mProgressDialog.isShowing()) {
mProgressDialog.dismiss();
}
}
#Override
public void onStop() {
super.onStop();
hideProgressDialog();
}
#Override
public void onFragmentTouched(Fragment fragment, float x, float y) {
Log.d("FRAGMENT_TOUCHED", "The ChatListFragment touch happened");
if(fragment instanceof ChatFragment) {
final ChatFragment theFragment = (ChatFragment) fragment;
Animator unreveal = theFragment.prepareUnrevealAnimator(x, y);
unreveal.addListener(new Animator.AnimatorListener() {
#Override
public void onAnimationStart(Animator animation) {
}
#Override
public void onAnimationEnd(Animator animation) {
getSupportFragmentManager().beginTransaction().remove(theFragment).commit();
getSupportFragmentManager().executePendingTransactions();
}
#Override
public void onAnimationCancel(Animator animation) {}
#Override
public void onAnimationRepeat(Animator animation) {}
});
unreveal.start();
}
}
public String getUid() {
return FirebaseAuth.getInstance().getCurrentUser().getUid();
}
private class PagerAdapter extends FragmentPagerAdapter {
Context context;
String tabTitles[] = new String[] {"Home", "Profile", "Chat"};
public PagerAdapter(FragmentManager fm, Context context) {
super(fm);
this.context = context;
}
#Override
public Fragment getItem(int pos) {
switch(pos) {
case 0: return new AllPostsFragment();
case 1: return ProfileFragment.newInstance(user.getUid());
case 2: return new ChatListFragment();
default:
return new AllPostsFragment();
}
}
#Override
public int getCount() {
return tabTitles.length;
}
#Override
public CharSequence getPageTitle(int position) {
return tabTitles[position];
}
public View getTabView(int position) {
View tab = LayoutInflater.from(HomeActivity.this).inflate(R.layout.custom_tab, null);
TextView tv = (TextView) tab.findViewById(R.id.custom_text);
tv.setText(tabTitles[position]);
return tab;
}
}
}
So, in the "ProfileFragment" in the onCreateView method I have...
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment_profile, container, false);
recyclerView = (RecyclerView) rootView.findViewById(R.id.userPostsRecycler);
RecyclerView.LayoutManager layoutManager = new GridLayoutManager(getContext(), 2);
recyclerView.setLayoutManager(layoutManager);
Toolbar toolbar = getActivity().findViewById(R.id.toolbar);
toolbar.setVisibility(View.GONE);
followingCountText = rootView.findViewById(R.id.following_count);
followersCountText = rootView.findViewById(R.id.followers_count);
titleLayout = rootView.findViewById(R.id.toolbar_layout);
titleLayout.setTitle(user.getDisplayName());
fab1Container = rootView.findViewById(R.id.fab_1);
fab2Container = rootView.findViewById(R.id.fab_2);
ImageView profilePhoto = (ImageView) rootView.findViewById(R.id.profile_photo);
Glide.with(this).load(user.getPhotoUrl()).into(profilePhoto);
fabContainer = (LinearLayout) rootView.findViewById(R.id.fabContainerLayout);
fab = (FloatingActionButton) rootView.findViewById(R.id.profile_fab);
instigatingFab = fab;
fabBaseX = fab.getX();
fabBaseY = fab.getY();
fab.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
showBlurredDialog();
}
});
progressDialog = new ProgressDialog(getContext());
uploads = new ArrayList<>();
progressDialog.setMessage("Please wait...");
progressDialog.show();
DatabaseReference followersDB = FirebaseDatabase
.getInstance()
.getReference("followers")
.child(user.getUid())
.child("count");
followersDB.addListenerForSingleValueEvent(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
int followersCount = dataSnapshot.getValue(Integer.class);
followersCountText.setText(Integer.toString(followersCount));
}
#Override
public void onCancelled(DatabaseError databaseError) {
}
});
DatabaseReference followingReference = FirebaseDatabase.getInstance().getReference("following").child(user.getUid()).child("users");
followingReference.addListenerForSingleValueEvent(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
}
#Override
public void onCancelled(DatabaseError databaseError) {
}
});
DatabaseReference followingDB = FirebaseDatabase.getInstance().getReference("following").child(user.getUid()).child("count");
followingDB.addListenerForSingleValueEvent(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
int followingCount = dataSnapshot.getValue(Integer.class);
followingCountText.setText(Integer.toString(followingCount));
}
#Override
public void onCancelled(DatabaseError databaseError) {
}
});
mDatabase = FirebaseDatabase.getInstance().getReference("/userPosts").child(user.getUid()).child("posts");
mDatabase.limitToFirst(25).addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
progressDialog.dismiss();
for(DataSnapshot postSnapshot : dataSnapshot.getChildren()) {
String postID = postSnapshot.getKey();
uploads.add(postID);
}
uploads.add("-KtvzkOL_75wiKA4CMsr");
adapter = new ProfileUserPostsViewHolder(getContext(), uploads);
recyclerView.setAdapter(adapter);
}
#Override
public void onCancelled(DatabaseError databaseError) {
progressDialog.dismiss();
}
});
return rootView;
}
As you can see I am setting the visibility for the toolbar from the HomeActivity to View.GONE, however, the toolbar is gone from all fragments now. I just want a bottom navigation setup with a top toolbar that can be hidden when certain fragments load, but is visible in other fragments. Is that even possible? Thank you.
You can control the numbers of fragments loading in view pager by simply using this method:
viewPager.setOffscreenPageLimit(1); // where n is the number of offscreen pages you want to load.
you can increase or decrease the number of fragments loading according to your requirements but atleast 1.
hope this will help you.
Related
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)
So when I click my EditText field called Search, I get the keyboard, and for a brief second I see the vatical line you see when you are typing. But then the recyclerview is updated, and the typo input is removed, and the keyboard is still showing, but when I type nothing happens, until I click on the EditText field a second time. How can this be??
This is my Fragment where I have the Recyclerview & EditText
public class FragmentST extends Fragment {
private final static String TAG = FragmentST.class.getSimpleName();
private FloatingActionButton addP, searchP;
private FirebaseFirestore firestore;
String editName, editNumber;
EditText textN, textID, searchText;
//https://www.youtube.com/watch?v=b_tz8kbFUsU&ab_channel=TVACStudio
public RecyclerView mResultList;
public FirestoreRecyclerAdapter adapter;
#Nullable
#Override
public View onCreateView(#NonNull LayoutInflater inflater, #Nullable ViewGroup container, #Nullable Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_st, container, false);
firestore = FirebaseFirestore.getInstance();
addP = (FloatingActionButton) view.findViewById(R.id.addP);
searchP = (FloatingActionButton) view.findViewById(R.id.searchP);
mResultList = (RecyclerView) view.findViewById(R.id.patientResults);
searchText = (EditText) view.findViewById(R.id.search_field);
setPatientView();
addPatientOnClick();
search();
return view;
}
private class PViewHolder extends RecyclerView.ViewHolder {
private TextView List_name, List_cpr;
private ImageView icon;
public PViewHolder(#NonNull View itemView) {
super(itemView);
List_name = itemView.findViewById(R.id.Pname);
List_cpr = itemView.findViewById(R.id.Pcpr);
icon = itemView.findViewById(R.id.pb);
}
}
private void setPatientView() {
//Query -->https://www.youtube.com/watch?v=cBwaJYocb9I&ab_channel=TVACStudio
Query query = firestore.collection("patients");
Log.d(TAG, "setPatientView: " + query);
//RecyclerOptions
FirestoreRecyclerOptions<users> options = new FirestoreRecyclerOptions.Builder<users>()
.setQuery(query, users.class)
.build();
adapter = new FirestoreRecyclerAdapter<users, PViewHolder>(options) {
#NonNull
#Override
public PViewHolder onCreateViewHolder(#NonNull ViewGroup parent, int viewType) {
View view1 = LayoutInflater.from(parent.getContext()).inflate(R.layout.list_patients_layout, parent, false);
return new PViewHolder(view1);
}
#Override
protected void onBindViewHolder(#NonNull PViewHolder holder, int position, #NonNull users model) {
holder.List_name.setText(model.getName());
holder.List_cpr.setText("CPR: " + model.getCpr());
System.out.println("last character: " + model.getCpr().substring(model.getCpr().length() - 1));
if ((Integer.parseInt(model.getCpr().substring(model.getCpr().length() - 1)) % 2) == 0) {
// number is even
int id = getResources().getIdentifier("com.example.wrd:drawable/female", null, null);
holder.icon.setImageResource(id);
} else {
// number is odd
int id = getResources().getIdentifier("com.example.wrd:drawable/male", null, null);
holder.icon.setImageResource(id);
}
}
};
mResultList.setHasFixedSize(true);
mResultList.setLayoutManager(new LinearLayoutManager(getActivity()));
mResultList.setAdapter(adapter);
}
private void search() {
searchP.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Toast.makeText(getActivity(), "HELLO "+searchText.getText().toString(), Toast.LENGTH_SHORT).show();
}
});
}
private void addPatientOnClick() {
addP.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Toast.makeText(getActivity(), "Button Clicked", Toast.LENGTH_SHORT).show();
//https://stackoverflow.com/questions/23669296/create-a-alertdialog-in-android-with-custom-xml-view
// custom dialog
final Dialog dialog = new Dialog(getActivity(), android.R.style.Theme_Material_Light_NoActionBar_Fullscreen);
dialog.setContentView(R.layout.fragment_add_patient);
dialog.setTitle("Add patient");
// set the custom dialog components - text, button
TextView text = (TextView) dialog.findViewById(R.id.text);
text.setText("Name");
TextView text2 = (TextView) dialog.findViewById(R.id.text2);
text2.setText("ID");
Button dialogButtonOk = (Button) dialog.findViewById(R.id.dialogButtonOK);
Button dialogButtonCancel = (Button) dialog.findViewById(R.id.dialogButtonCancel);
// if button is clicked, close the custom dialog
dialogButtonOk.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
textN = (EditText) dialog.findViewById(R.id.editName);
textID = (EditText) dialog.findViewById(R.id.editNumber);
editName = textN.getText().toString();
editNumber = textID.getText().toString();
editNumber.length();
if (editNumber != null && editNumber.length() > 9) {
Log.d(TAG, "dialog: \ncpr: " + editNumber);
} else {
return;
}
if (editName.matches("")) {
return;
} else {
Log.d(TAG, "dialog: \n Name: " + editName);
}
DocumentReference documentReference = firestore.collection("patients").document(editNumber);
Map<String, Object> patient = new HashMap<>();
patient.put("name", editName);
patient.put("cpr", editNumber);
documentReference.set(patient).addOnSuccessListener(new OnSuccessListener<Void>() {
#Override
public void onSuccess(Void aVoid) {
dialog.dismiss();
}
}).addOnFailureListener(new OnFailureListener() {
#Override
public void onFailure(#NonNull Exception e) {
}
});
}
});
dialogButtonCancel.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
dialog.dismiss();
}
});
dialog.show();
}
});
}
#Override
public void onDestroy() {
super.onDestroy();
}
#Override
public void onStop() {
super.onStop();
adapter.stopListening();
}
#Override
public void onStart() {
super.onStart();
adapter.startListening();
}
#Override
public void onPause() {
super.onPause();
}
#Override
public void onResume() {
super.onResume();
}
}
In the XML the EditText is set to the following
<EditText
android:id="#+id/search_field"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_marginStart="15dp"
android:layout_marginLeft="15dp"
android:layout_marginEnd="10dp"
android:layout_marginRight="10dp"
android:background="#drawable/search_layout"
android:ems="10"
android:hint="Search"
android:inputType="textPersonName"
android:paddingLeft="20dp"
android:paddingTop="10dp"
android:paddingRight="20dp"
android:paddingBottom="10dp"
android:textSize="16sp"
android:layout_weight="1"
app:layout_constraintBottom_toBottomOf="#+id/searchP"
app:layout_constraintEnd_toStartOf="#+id/searchP"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="#+id/searchP" />
I am trying to display a word from a second activity to my main activity which is inform of a recycler view with a textview item.
I have created my adapter and I am assuming it works fine the only problem is once I launch my floating button to access my display word activities it does not display on the main activity, what am I doing wrong, I am new to Android.
My Adapter :
public class RoomAdapter extends RecyclerView.Adapter<RoomAdapter.RoomViewHolder> {
private List <RoomPojo> word;
public RoomAdapter(List <RoomPojo> word1){
this.word = word1;
}
#NonNull
#Override
public RoomViewHolder onCreateViewHolder(#NonNull ViewGroup parent, int viewType) {
View layoutInflater = LayoutInflater.from(parent.getContext()).inflate(R.layout.word_item,parent,false);
return new RoomViewHolder(layoutInflater);
}
#Override
public void onBindViewHolder(#NonNull RoomViewHolder holder, int position) {
holder.wordTextView.setText(word.get(position).getWord());
}
#Override
public int getItemCount() {
return word.size();
}
public class RoomViewHolder extends RecyclerView.ViewHolder{
private TextView wordTextView;
public RoomViewHolder(View itemView) {
super(itemView);
wordTextView = itemView.findViewById(R.id.display_word);
}
}
}
Here is my Main activity:
public class MainActivity extends AppCompatActivity {
private RoomAdapter roomAdapter;
public static final int NEW_WORD_ACTIVITY_REQUEST_CODE = 1;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
RecyclerView recyclerView = findViewById(R.id.rv_word);
recyclerView.setAdapter(roomAdapter);
LinearLayoutManager linearLayoutManager = new LinearLayoutManager(this);
recyclerView.setLayoutManager(linearLayoutManager);
FloatingActionButton floatingActionButton = findViewById(R.id.fab);
floatingActionButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent(getApplicationContext(), DisplayWord.class);
String word = getIntent().getStringExtra(DisplayWord.EXTRA_KEY);
startActivityForResult(intent,NEW_WORD_ACTIVITY_REQUEST_CODE);
}
});
}
}
Here is my display word which has a button and a edit text which should take just one string.
public class DisplayWord extends AppCompatActivity {
public static final String EXTRA_KEY = "key";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_display_word);
final EditText editText = findViewById(R.id.word_edit_text);
Button button = findViewById(R.id.word_button);
button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent replyIntent = new Intent();
if(TextUtils.isEmpty(editText.getText())){
setResult(RESULT_CANCELED, replyIntent);
}else {
String word = editText.getText().toString();
replyIntent.putExtra(EXTRA_KEY,word);
}
finish();
}
});
}
}
Main.xml
<?xml version="1.0" encoding="utf-8"?>
<android.support.constraint.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".MainActivity">
<android.support.v7.widget.RecyclerView
android:id="#+id/rv_word"
android:layout_width="368dp"
android:layout_height="433dp"
android:layout_marginLeft="8dp"
android:layout_marginStart="8dp"
android:layout_marginTop="8dp"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent" />
<android.support.design.widget.FloatingActionButton
android:id="#+id/fab"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="bottom|end"
android:layout_marginLeft="328dp"
android:layout_marginStart="328dp"
android:layout_marginTop="12dp"
android:src="#drawable/ic_add_black_24dp"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toBottomOf="#+id/rv_word" />
</android.support.constraint.ConstraintLayout>
Your code should be like this :
button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent replyIntent = new Intent();
if(TextUtils.isEmpty(editText.getText())){
setResult(RESULT_CANCELED, replyIntent);
}else {
String word = editText.getText().toString();
replyIntent.putExtra(EXTRA_KEY,word);
setResult(RESULT_OK, replyIntent); //missing
}
finish();
}
});
Then After handle it in MainActivity.java
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
try {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == REQUEST_CODE && resultCode == RESULT_OK) {
String requiredValue = data.getStringExtra(DisplayWord.EXTRA_KEY);
}
} catch (Exception ex) {
Toast.makeText(Activity.this, ex.toString(),
Toast.LENGTH_SHORT).show();
}
}
In my project I have a main activity with 3 fragments that are displayed via a ViewPager in a TabLayout on launch. In one of my fragments I have a RecyclerView and a FAB that, when clicked, launches an alert dialog that captures user input to be displayed in the RV in the fragment. Upon clicking ADD in the dialog, nothing appears in the RV but when I click the FAB and try again, it appears in the RV. So what I am saying, I have to input info in the FAB twice before it displays in my RV in my fragment. So I was wondering if someone could help me understand why this is happening. It seems like my RV in my frag is not being created right away, but all in all my app is not crashing so I have no log to post. I've research but to no avail. I am self taught so any help would be appreciated.
Fragment
public class SubjectsFrag extends DialogFragment implements CardAdapter.ClickListener,
SubjectsEditor.OnAddSubjectListener
{
private static final String TAG = SubjectsFrag.class.getSimpleName();
#NonNull
Context context;
private EditText titleView, teacherView;
private String sTitle, sTeacher;
public EmptyRecyclerView recyclerView;
public RecyclerView.LayoutManager layoutManager;
public CardAdapter cardAdapter;
public SubjectsModel model = null;
public ArrayList<SubjectsModel> subMod = new ArrayList<>();
DbHelper dbHelper;
#BindView(R.id.main_root)
ViewGroup root;
public SubjectsFrag() {
}
#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_subjects, container, false);
FloatingActionButton fab = view.findViewById(R.id.fab_sub);
fab.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
showDialog();
}
});
titleView = view.findViewById(R.id.edit_subject);
teacherView = view.findViewById(R.id.edit_subject_teacher);
View emptyView = view.findViewById(R.id.empty_subject_view);
recyclerView = view.findViewById(R.id.recycler_view);
recyclerView.setHasFixedSize(true);
cardAdapter = new CardAdapter(getContext(), subMod);
layoutManager = new LinearLayoutManager(getActivity());
recyclerView.setLayoutManager(layoutManager);
recyclerView.setAdapter(cardAdapter);
return view;
}
#Override
public void itemClicked(View view, int position) {
}
#Override
public void OnAddSubjectSubmit(String title, String teacher)
{
SubjectsModel model = new SubjectsModel(sTitle, sTeacher);
model.setmTitle(title);
model.setmTeacher(teacher);
subMod.add(model);
cardAdapter.notifyDataSetChanged();
}
private void showDialog()
{
SubjectsEditor addSubjectDialog = new SubjectsEditor();
addSubjectDialog.setTargetFragment(this, 0);
addSubjectDialog.show(getFragmentManager(), null);
}
}
Dialog Fragment
public class SubjectsEditor extends DialogFragment
{
Context context;
private OnAddSubjectListener listener;
#BindView(R.id.main_root)
ViewGroup root;
public interface OnAddSubjectListener
{
void OnAddSubjectSubmit(String title, String teacher);
}
#Override
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
try{
listener = (OnAddSubjectListener) getTargetFragment();
} catch (ClassCastException e) {
throw new ClassCastException("Calling fragment must implement onAddSubjectListener");
}
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
return inflater.inflate(R.layout.editor_subjects, container, false);
}
public Dialog onCreateDialog(Bundle savedInstanceState)
{
View view = LayoutInflater.from(getActivity()).inflate(R.layout.editor_subjects, root);
final EditText mTitle = view.findViewById(R.id.edit_subject);
final EditText mTeacher = view.findViewById(R.id.edit_subject_teacher);
AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());
builder.setView(view)
.setTitle("Add Subject")
.setPositiveButton("Add", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
final String sTitle = mTitle.getText().toString();
final String sTeacher = mTeacher.getText().toString();
listener.OnAddSubjectSubmit(sTitle, sTeacher);
}
})
.setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
dialog.dismiss();
}
});
return builder.create();
}
}
Recycler Adapter
public class CardAdapter extends RecyclerView.Adapter<CardAdapter.CardViewHolder>
{
public ArrayList<SubjectsModel> subMod;
private OnItemClicked onClick;
static ClickListener clickListener;
Context context;
public CardAdapter(Context context, ArrayList<SubjectsModel> items)
{
this.context = context;
this.subMod = items;
}
#NonNull
#Override
public CardAdapter.CardViewHolder onCreateViewHolder(#NonNull ViewGroup parent, int viewType)
{
return new CardViewHolder(LayoutInflater.from(context).inflate(R.layout.subjects_item_list,
parent, false));
}
#Override
public void onBindViewHolder(final CardAdapter.CardViewHolder holder, final int position)
{
SubjectsModel currentSubject = subMod.get(position);
holder.titleView.setText(currentSubject.getmTitle());
holder.teacher.setText(currentSubject.getmTeacher());
}
public class CardViewHolder extends RecyclerView.ViewHolder implements
View.OnClickListener
{
TextView titleView;
TextView teacher;
CardView cardView;
public CardViewHolder(View itemView)
{
super(itemView);
titleView = itemView.findViewById(R.id.subject_subject);
teacher = itemView.findViewById(R.id.subject_teacher_text);
cardView = itemView.findViewById(R.id.card_view);
cardView.setOnClickListener(this);
}
#Override
public void onClick(View view)
{
if (clickListener != null)
{
clickListener.itemClicked(view, getAdapterPosition());
Toast.makeText(context, R.string.hello_blank_fragment, Toast.LENGTH_SHORT).show();
}
}
}
#Override
public int getItemCount()
{
return subMod.size();
}
public interface OnItemClicked
{
void onItemClick(int position);
}
public void setOnClick(OnItemClicked onClick)
{
this.onClick = onClick;
}
public void setClickListener(ClickListener clicked)
{
CardAdapter.clickListener = clicked;
}
public interface ClickListener
{
public void itemClicked(View view, int position);
}
}
Fragment xml
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:id="#+id/main_root">
<com.example.ashleighwilson.schoolscheduler.adapter.EmptyRecyclerView
android:id="#+id/recycler_view"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_marginTop="60dp"/>
<RelativeLayout
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerInParent="true">
<TextView
android:id="#+id/empty_subject_view"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:gravity="center"
android:visibility="gone"
android:text="#string/no_subjects"/>
</RelativeLayout>
<android.support.design.widget.FloatingActionButton
android:id="#+id/fab_sub"
style="#style/FAB" />
</RelativeLayout>
Main Activity
public class OverviewActivity extends AppCompatActivity
{
private NavigationView mNavigationView;
private DrawerLayout drawer;
private ActionBarDrawerToggle toggle;
CharSequence tabTitles[] = {"SUBJECTS", "TASKS", "CALENDER"};
int numOfTabs = 3;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main_nav);
Toolbar toolbar = findViewById(R.id.main_toolbar);
setSupportActionBar(toolbar);
final ViewPager viewPager = findViewById(R.id.viewpager);
ViewPagerAdapter adapter = new ViewPagerAdapter(this, getSupportFragmentManager(), tabTitles, numOfTabs);
viewPager.setAdapter(adapter);
TabLayout tabLayout = findViewById(R.id.tabs);
tabLayout.setupWithViewPager(viewPager);
drawer = findViewById(R.id.drawer_layout);
toggle = new ActionBarDrawerToggle(
this, drawer, toolbar, R.string.navigation_drawer_open, R.string.navigation_drawer_close);
toggle.syncState();
mNavigationView = findViewById(R.id.nav_view);
setupDrawerContent(mNavigationView);
/* FloatingActionButton fab = findViewById(R.id.fab);
fab.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Snackbar.make(view, "Replace with your own action", Snackbar.LENGTH_LONG)
.setAction("Action", null).show();
}
}); */
viewPager.addOnPageChangeListener(new TabLayout.TabLayoutOnPageChangeListener(tabLayout));
tabLayout.addOnTabSelectedListener(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) {
}
});
}
#Override
public void onBackPressed()
{
//DrawerLayout drawer = findViewById(R.id.drawer_layout);
if (drawer.isDrawerOpen(GravityCompat.START))
{
drawer.closeDrawer(GravityCompat.START);
}
else
super.onBackPressed();
}
#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_nav, 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.
int id = item.getItemId();
//noinspection SimplifiableIfStatement
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
private void setupDrawerContent(NavigationView navigationView)
{
navigationView.setNavigationItemSelectedListener(new NavigationView.OnNavigationItemSelectedListener() {
#Override
public boolean onNavigationItemSelected(#NonNull MenuItem menuItem)
{
selectDrawerItem(menuItem);
return true;
}
});
}
public void selectDrawerItem(MenuItem menuItem)
{
switch (menuItem.getItemId())
{
case R.id.nav_grades:
Intent gradesIntent = new Intent(this, GradesActivity.class);
startActivity(gradesIntent);
break;
case R.id.nav_notes:
Intent notesIntent = new Intent(this, NotesActivity.class);
startActivity(notesIntent);
break;
}
menuItem.setChecked(true);
setTitle(menuItem.getTitle());
drawer.closeDrawer(GravityCompat.START);
}
}
Using notifyDataSetChanged() should do the trick. Check this answer
Giving it a once-over, nothing jumped out. You can use either the debugger or Log.d(String, String) calls to challenge your assumptions about what’s being called when. I’d take a closer look at when you call your adapter’s notifyDataSetChanged() and then at the getItemCount and bind or createViewHolder calls inside the adapter itself.
I have tried every solution I found on-line and anywhere. But I still can't solve this problem. It keeps giving me this error "E/RecyclerView: No adapter attached; skipping layout". I tried to use breakpoint to test each code. From the result, I get that data is successfully retrieved from firebase and save in ArrayList and the size of mItems is correct. But this is the result I get.Please somebody help me.
The Result I get
My firebase structure
ShowBookedSlotActivity.java
public class ShowBookedSlotActivity extends AppCompatActivity {
private static final String TAG ="Show Booked Activity" ;
private FirebaseAuth.AuthStateListener authListener;
private FirebaseAuth auth;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_show_booked_slot);
setTitle("Booked Gym Slot");
Log.d(TAG, "on create");
//Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
//setSupportActionBar(toolbar);
//getSupportActionBar().setDisplayHomeAsUpEnabled(true);
// getSupportActionBar().setHomeButtonEnabled(true);
auth = FirebaseAuth.getInstance();
FragmentManager fm = getSupportFragmentManager();
Fragment fragment = fm.findFragmentById(R.id.fragmentContainer);
if (fragment == null) {
fragment = new ListBookedSlotFragment();
Bundle bundle = new Bundle();
bundle.putString("UID", auth.getCurrentUser().getUid());
fragment.setArguments(bundle);
fm.beginTransaction()
.add(R.id.fragmentContainer, fragment)
.commit();
}
}
#Override
protected void onResume() {
super.onResume();
}
#Override
public void onStart() {
super.onStart();
}
#Override
public void onStop() {
super.onStop();
}
#Override
public void onBackPressed()
{
super.onBackPressed();
startActivity(new Intent(ShowBookedSlotActivity.this, UserHomeActivity.class));
finish();
}
}
ListBookedSlotFragment.java
public class ListBookedSlotFragment extends Fragment {
private final String TAG = "ListBookedSlotFragment";
private ArrayList<BookedSlot> mItems;
private ArrayList<String> mItemsKey;
private RecyclerView mItemRecyclerView;
private ItemAdapter mAdapter;
private DatabaseReference mItemRef;
private DatabaseReference mDatabase;
private String UID;
private Query mBookedSlotQuery;
private DatabaseReference mBookedSlotRef;
private ValueEventListener mBookedSlotQueryVEL;
#SuppressLint("LongLogTag")
#Override
public void onCreate(Bundle savedInstanceState) {
UID = this.getArguments().getString("UID");
Log.d(TAG, "UID: " + UID);
mDatabase = FirebaseDatabase.getInstance().getReference();
mItems = new ArrayList<>();
if (UID != null) {
mItemsKey = new ArrayList<>();
mBookedSlotQuery = mDatabase.child("booked_slot").orderByChild("UserID").equalTo(UID);
Log.d(TAG, "mItemRef:" + mBookedSlotQuery);
mBookedSlotQueryVEL = mBookedSlotQuery.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
mItems.clear();
mItemsKey.clear();
Log.d(TAG, "onDataChange");
for (DataSnapshot d : dataSnapshot.getChildren()) {
BookedSlot bookedSlot = d.getValue(BookedSlot.class);
Log.d(TAG, "bookedSlot:" + bookedSlot.getUserID());
mItems.add(bookedSlot);
mItemsKey.add(d.getKey());
}
updateUI();
/* TextView infoTextTextview = (TextView) getActivity().findViewById(R.id.info_text); //show_booked_slot.xml
if (mItems.isEmpty()) {
infoTextTextview.setText(R.string.Empty);
} else {
// infoTextTextview.setVisibility(View.GONE);
infoTextTextview.setText("Size: ".concat(Integer.toString(mItems.size())));
}*/
}
#Override
public void onCancelled(DatabaseError databaseError) {
Log.d(TAG, "show booked slot databaseError: " + databaseError);
}
});
}
else{
Log.d(TAG, "UID: "+UID);
}
super.onCreate(savedInstanceState);
}
#Override
public void onDestroy() {
super.onDestroy();
// if (mBookedSlotQuery != null) mBookedSlotRef.removeEventListener(mBookedSlotQueryVEL);
}
#Override
public void onDetach() {
super.onDetach();
// if (mBookedSlotQuery != null) mBookedSlotRef.removeEventListener(mBookedSlotQueryVEL);
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_list_booked_slot, container, false);
mItemRecyclerView = (RecyclerView) view.findViewById(R.id.item_recycler_view); //in fragment_list_item_booked_slot.xml
DividerItemDecoration dividerItemDecoration = new DividerItemDecoration(mItemRecyclerView.getContext(), new LinearLayoutManager(getActivity()).getOrientation());
mItemRecyclerView.addItemDecoration(dividerItemDecoration);
mItemRecyclerView.setLayoutManager(new LinearLayoutManager(getActivity()));
return view;
}
private void updateUI() {
Log.d(TAG, "Enter updateUI(); mItems: " + mItems);
mAdapter = new ItemAdapter(mItems);
mItemRecyclerView.setAdapter(mAdapter);
}
private class ItemHolder extends RecyclerView.ViewHolder {
BookedSlot mItems;
TextView mNameTextView;
TextView mDateTextView;
TextView mTimeTextView;
ItemHolder(final View itemView) {
super(itemView);
//refer list_booked_gym_slot.xml
mNameTextView = (TextView) itemView.findViewById(R.id.textview_name);
mDateTextView = (TextView) itemView.findViewById(R.id.textview_date);
mTimeTextView = (TextView) itemView.findViewById(R.id.textview_time);
if (UID != null) {
itemView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Log.d(TAG, "UID != null");
AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());
builder
.setMessage("Delete This Slot?")
.setPositiveButton(R.string.yes, new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
deleteSlot(mItems);
}
}).setNegativeButton(R.string.no, new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
// User cancelled the dialog
}
});
AlertDialog dialog = builder.create();
dialog.show();
}
});
}
}
void bindData(BookedSlot s){
mItems = s;
mNameTextView.setText(s.getUsername());
mDateTextView.setText(s.getBookedDate());
mTimeTextView.setText(s.getBookedTime());
}
}
private class ItemAdapter extends RecyclerView.Adapter<ItemHolder>{
private ArrayList<BookedSlot> mItems;
ItemAdapter(ArrayList<BookedSlot> Items){
this.mItems = Items;
}
#Override
public ItemHolder onCreateViewHolder(ViewGroup parent, int viewType) {
LayoutInflater layoutInflater = LayoutInflater.from(getActivity());
View view = layoutInflater.inflate(R.layout.list_booked_gym_slot,parent,false);
return new ItemHolder(view);
}
#Override
public void onBindViewHolder(ItemHolder holder, int position) {
BookedSlot s = mItems.get(position);
holder.bindData(s);
}
#Override
public int getItemCount() {
return mItems.size();
}
}
private void deleteSlot(final BookedSlot itemClicked) {
mDatabase.child("booked_slot").child(UID).child(mItemsKey.get(mItems.indexOf(itemClicked))).removeValue(new DatabaseReference.CompletionListener() {
#Override
public void onComplete(DatabaseError databaseError, DatabaseReference databaseReference) {
if(databaseError == null){
Toast.makeText(getActivity(), itemClicked.getBookedDate() + " " + itemClicked.getBookedTime() +" Slot Deleted", Toast.LENGTH_SHORT).show();
}else{
Toast.makeText(getActivity(), "Something went wrong. Please try again later.", Toast.LENGTH_SHORT).show();
}
}
});
}
}
ShowBookedSlotActivity.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
tools:context="com.example.jaseline.myfyp.ShowBookedSlotActivity">
<android.support.design.widget.AppBarLayout
android:layout_width="match_parent"
android:layout_height="wrap_content">
</android.support.design.widget.AppBarLayout>
<TextView
android:id="#+id/info_text"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:paddingLeft="5dp"
android:paddingRight="5dp"
android:textSize="18sp" />
<RelativeLayout
android:id="#+id/fragmentContainer"
android:layout_width="match_parent"
android:layout_height="match_parent"
app:layout_behavior="#string/appbar_scrolling_view_behavior"
tools:context="com.example.jaseline.myfyp.ShowBookedSlotActivity"
tools:showIn="#layout/activity_show_booked_slot">
</RelativeLayout>
</LinearLayout>
fragment_list_booked_slot.xml
<?xml version="1.0" encoding="utf-8"?>
<android.support.v7.widget.RecyclerView
xmlns:android="http://schemas.android.com/apk/res/android"
android:id="#+id/item_recycler_view"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:scrollbars="vertical">
</android.support.v7.widget.RecyclerView>
list_booked_slot.xml
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:padding="5dp">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_centerVertical="true"
android:layout_marginLeft="10dp"
android:layout_marginStart="10dp"
android:orientation="vertical">
<TextView
android:id="#+id/textview_name"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:textSize="18sp"
android:textStyle="bold" />
<TextView
android:id="#+id/textview_date"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textSize="14sp" />
<TextView
android:id="#+id/textview_time"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textSize="14sp" />
</LinearLayout>
</RelativeLayout>
The Fragment Life Cycle is as follows :
1. constructor
2. onAttach
3. onCreate
4. onCreateView
So you cant call updateUI() method to set data to RecyclerView before setting LayoutManager.
Only after setting LayoutManager should you give data to RecyclerView