Widget layout from Activity still appear after fragment add transaction - java

I have a problem with fragments. I add fragments dynamically without removing old fragments so they can be recalled when I return. But when I applied the following snippet I found that some of the views that came from the activity did not disappear, such as the Button, TextView, and so on. The results I get are overlapping views
MainActivity.Java
public class MainActivity extends AppCompatActivity implements BlankFragment.OnFragmentInteractionListener {
private static final String TAG = "MainActivity";
private Unbinder unbinder;
private FragmentManager fragmentManager;
#BindView(R.id.dynamic_fragment_frame)
FrameLayout frameLayout;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_reading);
unbinder = ButterKnife.bind(this);
fragmentManager = this.getSupportFragmentManager();
}
public void openFragment(View view) {
BlankFragment fragment = BlankFragment.newInstance("Test 1");
FragmentTransaction transaction = fragmentManager.beginTransaction();
transaction.setCustomAnimations(R.anim.enter_from_right, R.anim.exit_to_right, R.anim.enter_from_right, R.anim.exit_to_right);
transaction.addToBackStack(null);
transaction.add(R.id.dynamic_fragment_frame, fragment, "BLACK_FRAGMENT");
transaction.commit();
}
#Override
protected void onDestroy() {
unbinder.unbind();
super.onDestroy();
}
#Override
public void onFragmentInteraction(String text) {
Log.d(TAG, "onFragmentInteraction: " + text);
onBackPressed();
}
}
activity_reading.xml
<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/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="#00d9ff"
tools:context=".MainActivity">
<FrameLayout
android:id="#+id/dynamic_fragment_frame"
android:layout_width="match_parent"
android:layout_height="match_parent"/>
<TextView
android:id="#+id/title_read_news"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Ini Judul"
android:textAppearance="#style/TextAppearance.AppCompat.Large"
android:layout_gravity="center"
android:paddingBottom="5dp"/>
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerInParent="true"
android:onClick="openFragment"
android:text="Open"
android:stateListAnimator="#null"/>
</RelativeLayout>
BlankFragment.java
public class BlankFragment extends Fragment {
private static final String ARG_TEXT = "TEXT";
private Unbinder unbinder;
private String mParam1;
private OnFragmentInteractionListener mListener;
#BindView(R.id.tv_blank_fragment)
TextView tvTitle;
#BindView(R.id.back_btn)
Button backBtn;
#BindView(R.id.next_btn)
Button nextBtn;
private FragmentManager fragmentManager;
public BlankFragment() {
// Required empty public constructor
}
public static BlankFragment newInstance(String param1) {
BlankFragment fragment = new BlankFragment();
Bundle args = new Bundle();
args.putString(ARG_TEXT, param1);
fragment.setArguments(args);
return fragment;
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
if (getArguments() != null) {
mParam1 = getArguments().getString(ARG_TEXT);
}
fragmentManager = getFragmentManager();
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
return inflater.inflate(R.layout.fragment_blank, container, false);
}
#Override
public void onViewCreated(#NonNull View view, #Nullable Bundle savedInstanceState) {
super.onViewCreated(view, savedInstanceState);
unbinder = ButterKnife.bind(this, view);
tvTitle.setText(mParam1);
backBtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
String test = "test dari fragment";
sendBack(test);
}
});
nextBtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
}
});
}
public void sendBack(String sendback) {
if (mListener != null) {
mListener.onFragmentInteraction(sendback);
}
}
#Override
public void onAttach(Context context) {
super.onAttach(context);
if (context instanceof OnFragmentInteractionListener) {
mListener = (OnFragmentInteractionListener) context;
} else {
throw new RuntimeException(context.toString()
+ " must implement OnFragmentInteractionListener");
}
}
#Override
public void onDetach() {
super.onDetach();
mListener = null;
}
public interface OnFragmentInteractionListener {
void onFragmentInteraction(String text);
}
}
fragment_blank.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="match_parent"
android:background="#cfcf1d"
tools:context=".BlankFragment">
<TextView
android:id="#+id/tv_blank_fragment"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:text="#string/hello_blank_fragment" />
<Button
android:id="#+id/next_btn"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_above="#+id/back_btn"
android:layout_alignParentStart="true"
android:text="Create new Fragment" />
<Button
android:id="#+id/back_btn"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_alignParentStart="true"
android:layout_alignParentBottom="true"
android:text="back" />
</RelativeLayout>
Everything went smoothly but the result of my Mainactivity layout still appeared on fragment. Please help me
Result as shows as below:
here 1
here 2

In activity_reading, the fragment container view (dynamic_fragment_frame) is declared first, so the button and the text view will be displayed on top of it. If you move the fragment container to the bottom, the fragments will be displayed correctly, so the layout should look something like this:
<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/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="#00d9ff"
tools:context=".MainActivity">
<TextView
android:id="#+id/title_read_news"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Ini Judul"
android:textAppearance="#style/TextAppearance.AppCompat.Large"
android:layout_gravity="center"
android:paddingBottom="5dp"/>
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerInParent="true"
android:onClick="openFragment"
android:text="Open"
android:stateListAnimator="#null"/>
<FrameLayout
android:id="#+id/dynamic_fragment_frame"
android:layout_width="match_parent"
android:layout_height="match_parent"/>
</RelativeLayout>

<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/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="#00d9ff"
tools:context=".MainActivity">
<FrameLayout
android:id="#+id/dynamic_fragment_frame"
android:layout_width="match_parent"
android:layout_height="match_parent"/>
<TextView
android:id="#+id/title_read_news"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Ini Judul"
android:textAppearance="#style/TextAppearance.AppCompat.Large"
android:layout_gravity="center"
android:paddingBottom="5dp"/>
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerInParent="true"
android:onClick="openFragment"
android:text="Open"
android:stateListAnimator="#null"/>
</RelativeLayout>
With the above layout, Imagine that the TextView and Button are over the FragmeLayout. So when you add a Fragment to the FrameLayout, the TextView and Button are still over the FragmeLayout. To hide these views, you should use TextView.setVisibility(View.GONE) and Button.setVisibility(View.GONE) when adding a Fragment

Related

How to open and close fragment,clicking on the same button in android

how to open and close fragment while clicking on same button . Just like amazon filter button.
when we click first time fragment should apper and then we click on that button again fragment should disapper.
business activity java file
public class business extends AppCompatActivity {
TextView t1, t2;
Button hello;
boolean flag = false;
FragmentTransaction fragmentTransaction;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_business);
hello = findViewById(R.id.hello);
t1=findViewById(R.id.text1);
t2=findViewById(R.id.textt2);
}
#Override
protected void onStart() {
super.onStart();
hello.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
FragmentManager manager = getSupportFragmentManager();
BusinessSort businessSort = new BusinessSort();
fragmentTransaction = manager.beginTransaction();
if (flag) {
fragmentTransaction.remove(businessSort);
flag=false;
} else {
fragmentTransaction.add(R.id.frgmCont, businessSort);
flag=true;
}
fragmentTransaction.commit();
}
});
}
public void f1(String s1, String s2) {
t1.setText(s1);
t2.setText(s2);
}
}
activity_business.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"
tools:context=".business"
android:orientation="vertical"
android:id="#+id/businessLinearLayout">
<Button
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="hello"
android:id="#+id/hello"
/>
<TextView
android:id="#+id/text1"
android:layout_width="match_parent"
android:layout_height="50dp"
android:text="edit1"/>
<TextView
android:layout_width="match_parent"
android:layout_height="50dp"
android:text="edit2"
android:id="#+id/textt2"/>
<FrameLayout
android:id="#+id/frgmCont"
android:layout_width="match_parent"
android:layout_height="match_parent">
</FrameLayout>
Fagment file BusinessSort.java
public class BusinessSort extends Fragment {
EditText editText1,editText2;
Button submit;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
View view =inflater.inflate(R.layout.fragment_business_sort, container, false);
editText1=view.findViewById(R.id.edit1);
editText2=view.findViewById(R.id.edit2);
submit=view.findViewById(R.id.businessfragment_submit);
submit.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
String s1 = editText1.getText().toString();
String s2 = editText2.getText().toString();
business business = (com.example.project.business) getActivity();
business.f1(s1,s2);
}
});
return view;
}
fragment_business_sort.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".BusinessSort"
android:orientation="vertical">
<EditText
android:id="#+id/edit1"
android:layout_width="match_parent"
android:layout_height="50dp"/>
<EditText
android:id="#+id/edit2"
android:layout_width="match_parent"
android:layout_height="50dp"/>
<Button
android:id="#+id/businessfragment_submit"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="SUBMIT"/>
</LinearLayout>
Try replacing the fragment.
fragmentTransaction.replace(R.id.frgmCont, businessSort);
flag = true;
I hope the code is mostly similar to my approach so let me know if the problem still persists so that I will look into it deeper.
public static boolean fragmentState = false;
onClick(){
if(fragmentState){
fragmentState = false;
getActivity().getFragmentManager().beginTransaction().
remove(SomeFragment.this).commit();
}
else{
fragmentState = true;
Fragment someFragment = new SomeFragment();
FragmentTransaction transaction =
getFragmentManager().beginTransaction();
transaction.replace(R.id.fragment_container, someFragment );
transaction.addToBackStack(null);
transaction.commit();
}
}
Please make sure that your button is not a part of that fragment.
You need to save the state of the fragment.

Null pointer error when calling communicating between an activity and a fragement

I have been attempting to call a method from my home activity which should fire once a button is clicked on my settings fragment. The result of this button click should call the greenTorso() and swap an image on my avatar fragment. I am currently getting a null pointer error, please see the logcat attached. I'm not even sure if this is the right way to go about this, but been stuck for a couple of days now and hoped someone could help. Thanks in advance.
My home activity:
public class Home extends AppCompatActivity implements SettingsFragment.Communicator {
private TextView name, email;
Button LogoutButton;
UserSessionManager sessionManager;
Button button;
ImageView Torso;
public void communicateWith(){
AvatarFragment avatarFragment = (AvatarFragment)getSupportFragmentManager().findFragmentById(R.id.nav_avatar);
avatarFragment.greenTorso();
}
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.home);
getWindow().setBackgroundDrawableResource(R.drawable.background2); // sets background to background2.png
this.getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_ALWAYS_HIDDEN); // hides keyboard on boot
sessionManager = new UserSessionManager(getApplicationContext());
TextView lblName = (TextView) findViewById(R.id.lblName);
TextView lblEmail = (TextView) findViewById(R.id.lblEmail);
BottomNavigationView bottomNav = findViewById(R.id.bottom_nav);
bottomNav.setOnNavigationItemSelectedListener(navListener);
getSupportFragmentManager().beginTransaction().replace(R.id.fragment_container,
new HomeFragment()).commit();
if(sessionManager.checkLogin())
finish();
// get user data from session
HashMap<String, String> user = sessionManager.getUserDetails();
// get name
String name = user.get(UserSessionManager.KEY_NAME);
// get email
String email = user.get(UserSessionManager.KEY_EMAIL);
//lblName.setText(Html.fromHtml("Name: <b>" + name + "</b>"));
lblEmail.setText(Html.fromHtml("Welcome: <b>" + email + "</b>"));
LogoutButton=(Button)findViewById(R.id.LogoutButton);
Toast.makeText(getApplicationContext(),
"User Login Status: " + sessionManager.isUserLoggedIn(),
Toast.LENGTH_LONG).show();
LogoutButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View arg0) {
// Clear the User session data
// and redirect user to LoginActivity
sessionManager.logoutUser();
}
});
}
private BottomNavigationView.OnNavigationItemSelectedListener navListener =
new BottomNavigationView.OnNavigationItemSelectedListener() {
#Override
public boolean onNavigationItemSelected(#NonNull MenuItem menuItem) {
Fragment selectedFragment = null;
switch (menuItem.getItemId()) {
case R.id.nav_steps:
selectedFragment = new HomeFragment();
break;
case R.id.nav_avatar:
selectedFragment = new AvatarFragment();
break;
case R.id.nav_settings:
selectedFragment = new SettingsFragment();
break;
}
getSupportFragmentManager()
.beginTransaction().replace(R.id.fragment_container,selectedFragment).commit();
return true;
}
};
}
My settings fragment:
public class SettingsFragment extends Fragment {
public Button button;
public ImageView Torso;
public ImageView ShopGreenTorso;
private Communicator interfaceImplementor;
public interface Communicator
{
public void communicateWith();
}
#Override
public void onAttach(Activity context) {
super.onAttach(context);
this.interfaceImplementor = (Communicator)context;
}
#Nullable
#Override
public View onCreateView(#NonNull LayoutInflater inflater, #Nullable ViewGroup container, #Nullable Bundle savedInstanceState) {
return inflater.inflate(R.layout.fragment_settings, container, false);
}
#Override
public void onActivityCreated(#Nullable Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
Button button = (Button) getActivity().findViewById(R.id.button1);
button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// ImageView torso = (ImageView) getActivity().findViewById(R.id.Torso);
interfaceImplementor.communicateWith();
}
});
}
}
My avatar fragment:
public class AvatarFragment extends Fragment {
public ImageView IV;
#Override
public View onCreateView(#NonNull LayoutInflater inflater, #Nullable ViewGroup container, #Nullable Bundle savedInstanceState)
{
View rootView = inflater.inflate(R.layout.fragment_avatar, container, false);
return rootView;
}
public void greenTorso()
{
ImageView IV =(ImageView) getActivity().findViewById(R.id.Torso);
IV.setBackgroundResource(R.drawable.torso2green);
}
}
Avatar layout:
<?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"
xmlns:src="http://schemas.android.com/apk/res-auto"
android:background="#android:color/holo_orange_dark"
>
<ImageView
android:layout_width="500dp"
android:layout_height="530dp"
android:layout_centerInParent="true"
android:orientation="vertical"
android:layout_marginStart="30dp"
android:layout_marginEnd="30dp"
android:id="#+id/Torso"
android:src="#drawable/torso2" >
</ImageView>
</RelativeLayout>
Settings layout:
<?xml version="1.0" encoding="utf-8"?>
<ScrollView 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"
android:background="#D3D3D3"
android:weightSum="10"
tools:context=".Home">
<LinearLayout
android:orientation="vertical"
android:layout_width="match_parent"
android:layout_height="wrap_content">
<TextView
android:layout_marginTop="100dp"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:text="Shop"
android:textSize="26sp"
android:textStyle="bold"
android:gravity="center"
android:layout_marginBottom="10dp"/>
<androidx.cardview.widget.CardView
android:id="#+id/cardview1"
android:layout_width="match_parent"
android:layout_height="150dp"
android:layout_below="#+id/cardview"
android:layout_centerHorizontal="true"
android:layout_centerVertical="true"
android:layout_marginLeft="16dp"
android:layout_marginTop="10dp"
android:layout_marginRight="16dp"
app:cardBackgroundColor="#color/white"
app:cardCornerRadius="15dp"
app:cardElevation="10dp">
<LinearLayout
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:orientation="vertical">
</LinearLayout>
<TextView
android:id="#+id/textView"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginTop="10dp"
android:gravity="center_horizontal"
android:paddingLeft="10dp"
android:text="Green Torso"
android:textColor="#color/cardview_dark_background"
android:textSize="20sp"
android:textStyle="bold" />
<ImageView
android:id="#+id/ShopGreenTorso"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center_horizontal"
android:background="#drawable/torso2green" />
<Button
android:id="#+id/button1"
android:layout_width="match_parent"
android:layout_height="30dp"
android:layout_gravity="bottom"
android:layout_marginLeft="10dp"
android:layout_marginRight="10dp"
android:layout_marginBottom="10dp"
android:background="#drawable/register_button"
android:shadowColor="#color/colorPrimary"
android:text="10,000S Buy"
android:textColor="#color/white">
</Button>
</androidx.cardview.widget.CardView>
My navigation:
<?xml version="1.0" encoding="utf-8"?>
<menu xmlns:android="http://schemas.android.com/apk/res/android">
<item
android:id="#+id/nav_steps"
android:icon="#drawable/ic_directions_walk_black_24dp"
android:title="Steps" />
<item
android:id="#+id/nav_avatar"
android:icon="#drawable/ic_face_black_24dp"
android:title="Avatar" />
<item
android:id="#+id/nav_settings"
android:icon="#drawable/ic_build_black_24dp"
android:title="Settings" />
</menu>

How to fix TextView being rendered blank on new Activity

I'm trying to start another activity after clicking on a CardView inside a RecyclerView. The new activity renders after the click on any of the items inside the RecyclerView (It does the transition and changes the title TextView), but it does not show any of the TextView's inside the CardView on the layout.
The OnClick method is being set as an interface and being implemented in the first Activity.
Here is my first activity. I'm loading the data here from a SQLite database, but it's not relevant for the question to show the code from it.
public class MainActivity extends AppCompatActivity implements RecipeAdapterMain.OnCardListener {
private TextView tv;
ArrayList<RecipeObject> recipes = new ArrayList<>();
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
RecyclerView rv = findViewById(R.id.recipeListMain);
LinearLayoutManager llm = new LinearLayoutManager(this);
rv.setLayoutManager(llm);
RecipeAdapterMain adapter = new RecipeAdapterMain(recipes, this);
rv.setAdapter(adapter);
tv = findViewById(R.id.title);
}
#Override
public void onCardClick(int position) {
Intent intent = new Intent(this, RecipeActivity.class);
startActivity(intent);
}
}
This is my Adapter.
public class RecipeAdapterMain extends RecyclerView.Adapter<RecipeAdapterMain.RecipeListViewHolder> {
RecyclerView mRecyclerView;
ArrayList<RecipeObject> recipeList;
private OnCardListener mOnCardListener;
public RecipeAdapterMain(Context context, ArrayList<RecipeObject> recipeList, OnCardListener onCardListener) {
this.mOnCardListener = onCardListener;
this.recipeList = recipeList;
}
#Override
public void onAttachedToRecyclerView(RecyclerView recyclerView) {
mRecyclerView = recyclerView;
super.onAttachedToRecyclerView(recyclerView);
}
#Override
public RecipeListViewHolder onCreateViewHolder(ViewGroup parent, int i) {
View layoutView = LayoutInflater.from(parent.getContext()).inflate(R.layout.layout_recipe_main, parent, false);
RecipeListViewHolder rcv = new RecipeListViewHolder(layoutView, mOnCardListener);
return rcv;
}
#Override
public void onBindViewHolder(#NonNull RecipeListViewHolder holder, int position) {
holder.mName.setText(recipeList.get(position).getName());
}
#Override
public int getItemCount(){
return recipeList.size();
}
public class RecipeListViewHolder extends RecyclerView.ViewHolder implements View.OnClickListener{
public TextView mName;
OnCardListener onCardListener;
public RecipeListViewHolder(final View view, OnCardListener onCardListener) {
super(view);
mName = view.findViewById(R.id.textViewTitle);
this.onCardListener = onCardListener;
view.setOnClickListener(this);
}
#Override
public void onClick(View v) {
onCardListener.onCardClick(getAdapterPosition());
}
}
public interface OnCardListener {
void onCardClick(int position);
}
}
My second activity:
public class RecipeActivity extends AppCompatActivity {
#Override
public void onCreate(#Nullable Bundle savedInstanceState, #Nullable PersistableBundle persistentState) {
super.onCreate(savedInstanceState, persistentState);
setContentView(R.layout.layout_recipe);
}
}
This is the layout from the second activity. (layout_recipe):
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical" android:layout_width="match_parent"
android:layout_height="wrap_content">
<androidx.cardview.widget.CardView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_gravity="center">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical">
<TextView
android:id="#+id/textViewName"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="This is a test"
android:textColor="#1A1A1A"
android:textSize="18sp" />
<TextView
android:id="#+id/textViewIngr"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="This is a test"
android:textColor="#1A1A1A"
android:textSize="18sp" />
<TextView
android:id="#+id/textViewDire"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="This is a test"
android:textColor="#1A1A1A"
android:textSize="18sp" />
</LinearLayout>
</androidx.cardview.widget.CardView>
</LinearLayout>
And this is the layout from the first activity (activity_main):
<?xml version="1.0" encoding="utf-8"?>
<androidx.coordinatorlayout.widget.CoordinatorLayout 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">
<com.google.android.material.appbar.AppBarLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:theme="#style/AppTheme.AppBarOverlay">
</com.google.android.material.appbar.AppBarLayout>
<androidx.recyclerview.widget.RecyclerView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:id="#+id/recipeListMain"
android:scrollbars="vertical">
</androidx.recyclerview.widget.RecyclerView>
<com.google.android.material.floatingactionbutton.FloatingActionButton
android:id="#+id/fab"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
app:backgroundTint="#color/colorAccent"
android:layout_gravity="end|bottom"
android:layout_margin="16dp"
android:layout_marginBottom="16dp"
android:contentDescription="#string/submit"
android:src="#drawable/ic_add_black_24dp"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
android:onClick="openActivityCreate"/>
</androidx.coordinatorlayout.widget.CoordinatorLayout>
From clicking in a Card on the MainActivity, I expected to render the second activity with it's TextViews (This is a test), but it's rendering a blank page instead.
try removing #Nullable PersistableBundle persistentState from onCreate on your second activity

android recyclerview show data only at first time

I have a problem ,I create recyclerview and its work fine at the first search data from api , it display fine but when I try to search with new data ( second time ) it is not display anything i try to test and debug every every thing work fine and new data enter to adapter and get the result fine and set adapter to recyclerview but it is not showing any thing
I try several method like use only one adapter and change it's list of Date and use notifyDataSetChange but not work still only show at the first time
Below activity is use to search get date ( use in searching data )
fromDate to toDate
DeliveryReportActivity.java
public class DeliveryReportActivity extends AppCompatActivity
implements DateDialogFromFragment.SelectDateFromInterface,
DateDialogToFragment.SelectDateToInterface {
Button btn_from;
Button btn_to;
EditText et_fromDate;
EditText et_toDate;
Button search_btn;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_delivery_report);
btn_from=(Button)findViewById(R.id.btn_fromDate);
btn_to=(Button)findViewById(R.id.btn_toDate);
et_fromDate = (EditText) findViewById(R.id.from_date);
et_toDate = (EditText) findViewById(R.id.to_date);
search_btn=(Button)findViewById(R.id.search_delivery_report_btn);
et_fromDate.setText(new SimpleDateFormat("yyyy-MM-dd").format(new
Date()));
et_toDate.setText(new SimpleDateFormat("yyyy-MM-dd").format(new
Date()));
btn_from.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
DateDialogFromFragment dateDialogFragment = new
DateDialogFromFragment();
android.app.FragmentTransaction ft =
getFragmentManager().beginTransaction();
dateDialogFragment.show(ft, "DatePicker");
}
});
btn_to.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
DateDialogToFragment dateDialogFragment = new
DateDialogToFragment();
android.app.FragmentTransaction ft =
getFragmentManager().beginTransaction();
dateDialogFragment.show(ft, "DatePicker");
}
});
search_btn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Bundle bundle=new Bundle();
bundle.putString("from",et_fromDate.getText().toString()+ "
00:00:00");
bundle.putString("to",et_toDate.getText().toString()+" 23:59:59");
Intent intent =new
Intent(DeliveryReportActivity.this,DeliveryReportListActivity.class);
intent.putExtras(bundle);
startActivity(intent);
}
});
}
#Override
public void onGetSelectFromDate(String fromDate) {
et_fromDate.setText(fromDate);
}
#Override
public void onGetSelectToDate(String toDate) {
et_toDate.setText(toDate);
}
}
and it's view activity_delivery_report.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:layout_margin="20dp"
android:orientation="vertical"
tools:context="com.exatech.groupsmsandroid.activity.
deliveryReport.DeliveryReportActivity">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="horizontal">
<Button
android:id="#+id/btn_fromDate"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="#string/From"
android:textSize="18dp" />
<EditText
android:id="#+id/from_date"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="2017-12-26" />
</LinearLayout>
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginTop="50dp"
android:orientation="horizontal">
<Button
android:id="#+id/btn_toDate"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="#string/to" />
<EditText
android:id="#+id/to_date"
android:text="2017-12-26"
android:layout_width="match_parent"
android:layout_height="wrap_content" />
</LinearLayout>
<RelativeLayout
android:layout_width="match_parent"
android:layout_height="wrap_content">
<Button
android:layout_centerInParent="true"
android:gravity="center"
android:layout_marginTop="20dp"
android:id="#+id/search_delivery_report_btn"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:background="#color/colorPrimary"
android:text="#android:string/search_go" />
</RelativeLayout>
</LinearLayout>
after I press the search button it's start new activity that show my recylerview the new activity is
DeliveryReportListActivity .java
public class DeliveryReportListActivity extends AppCompatActivity implements
DeliveryReportService.DeliveryReportServiceInterface {
private static final String TAG = "GSMS";
private Bundle bundle;
private RecyclerView recyclerView;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_delivery_report_list);
recyclerView = (RecyclerView) findViewById(R.id.delivery_report_rv);
}
#Override
protected void onResume() {
super.onResume();
bundle = getIntent().getExtras();
String from = bundle.getString("from");
String to = bundle.getString("to");
DeliveryReportService.getInstance(this).
getDeliveryReportFromDateToDate(from, to);// Call api get deliver
}
#Override
public void onGetDeliveryReport(Response<List<DeliveryReportResource>>
listResponse) {// response
Log.i(TAG, "onGetDeliveryReport: listResponse.body():" +
listResponse.body());
DeliveryReportAdapter deliveryReportAdapter = new
DeliveryReportAdapter(DeliveryReportListActivity.this, listResponse.body());
recyclerView.setAdapter(deliveryReportAdapter);
deliveryReportAdapter.notifyDataSetChanged();
Toast.makeText(DeliveryReportListActivity.this, "Delivery Report Success
", Toast.LENGTH_SHORT).show();
}
#Override
public void onDeliveryConnectionFailed() {
Toast.makeText(DeliveryReportListActivity.this, "Connect Error ",
Toast.LENGTH_SHORT).show();
}
}
and it's view activity_delivery_report_list.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.exatech.groupsmsandroid.activity.deliveryReport.
DeliveryReportListActivity">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="horizontal">
<TextView
android:text="#string/text"
android:layout_weight="3"
android:layout_width="match_parent"
android:layout_height="wrap_content" />
<TextView
android:layout_weight="4"
android:text="#string/phone_no"
android:layout_width="match_parent"
android:layout_height="wrap_content" />
<TextView
android:layout_weight="4"
android:text="#string/status"
android:layout_width="match_parent"
android:layout_height="wrap_content" />
</LinearLayout>
<android.support.v7.widget.RecyclerView
android:id="#+id/delivery_report_rv"
android:layout_width="match_parent"
app:layoutManager="LinearLayoutManager"
android:layout_height="match_parent"
tools:listitem="#layout/delivery_report_list_content"/>
</LinearLayout>
Below is Myadapter Class
**DeliveryReportAdapter.java**
public class DeliveryReportAdapter extends
RecyclerView.Adapter<DeliveryReportAdapter.ViewHolder> {
List<DeliveryReportResource> listDeliveryReport;
Context context;
public DeliveryReportAdapter(Context context, List<DeliveryReportResource>
listDeliveryReport) {
this.listDeliveryReport = listDeliveryReport;
this.context = context;
}
#Override
public ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View view =
LayoutInflater.from(parent.getContext()).
inflate(R.layout.delivery_report_list_content, parent, false);
return new ViewHolder(view);
}
#Override
public void onBindViewHolder(final ViewHolder holder, int position) {
holder.item = listDeliveryReport.get(position);
holder.text.setText(holder.item.getText());
CustomAdapterFroDeliveryReport adapterFroDeliveryReport = new
CustomAdapterFroDeliveryReport(context, R.layout.two_text_contect,
listDeliveryReport.get(position).getSmsSubscribedRecipientsResourceList());
holder.phoneNoAndStatus.setAdapter(adapterFroDeliveryReport);
holder.view.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Toast.makeText(context, "click message no=" +
holder.item.getText(), Toast.LENGTH_SHORT).show();
}
});
}
#Override
public int getItemCount() {
return listDeliveryReport.size();
}
class ViewHolder extends RecyclerView.ViewHolder {
View view;
TextView text;
ListView phoneNoAndStatus;
DeliveryReportResource item;
public ViewHolder(View itemView) {
super(itemView);
view = itemView;
text = (TextView) itemView.findViewById(R.id.message_tv);
phoneNoAndStatus = (ListView)
itemView.findViewById(R.id.phoneNo_and_status_lv);
}
}
}
Try to create an adapter once and then update items
Add next code to your adapter class
ArrayList<DeliveryReportResource> listDeliveryReport = new ArrayList<DeliveryReportResource>();
public DeliveryReportAdapter(Context context) {
this.context = context;
}
public void updateItems(List<DeliveryReportResource> list) {
listDeliveryReport.clear();
listDeliveryReport.addAll(list);
notifyDataSetChanged();
}
Then create adapter once in onCreate() and place it as global variable
And now you should call adapter.updateItems(...) every time you want to change data

The ListView from Fragment extending ListFragment is repeating itself. Any idea what's wrong?

This is the activity
public class Homepage extends FragmentActivity implements ChatFragment.OnFragmentInteractionListener{
SearchFragment searchFragment;
ChatFragment chatFragment;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_homepage);
searchFragment = new SearchFragment();
chatFragment = new ChatFragment();
if(savedInstanceState == null){
getFragmentManager().beginTransaction().replace(R.id.homepageFragment,chatFragment).commit();
}
}
#Override
protected void onResume(){
Bundle bundle = getIntent().getExtras();
if(bundle != null){
//text.setText("user_id: " + bundle.get("user_id") + " ,username: " + bundle.get("username") + " ,password: " + bundle.get("password"));
}
super.onResume();
}
#Override
public void onChatFragmentInteraction(Uri uri){
}
public void openSearchFragment(View view){
if(!searchFragment.isAdded())
getFragmentManager().beginTransaction().replace(R.id.homepageFragment,searchFragment).commit();
}
public void openChatFragment(View view){
if(!chatFragment.isAdded())
getFragmentManager().beginTransaction().replace(R.id.homepageFragment,chatFragment).commit();
}
public void openProfile(View view){
}
}
This is the layout of the activity
I like making my activities screen responsive.
<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context="the_activity_location"
android:orientation="vertical">
<LinearLayout
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:weightSum="100"
android:orientation="vertical">
<LinearLayout
android:layout_width="fill_parent"
android:layout_height="0dp"
android:paddingLeft="#dimen/activity_horizontal_margin"
android:paddingRight="#dimen/activity_horizontal_margin"
android:paddingTop="#dimen/activity_vertical_margin"
android:paddingBottom="#dimen/activity_vertical_margin"
android:layout_weight="90"
android:orientation="vertical">
<fragment
android:id="#+id/homepageFragment"
android:name="com.example.summer.toothbrush.SearchFragment"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
tools:layout="#layout/fragment_search"/>
</LinearLayout>
<LinearLayout
android:layout_width="fill_parent"
android:layout_height="0dp"
android:backgroundTint="#color/whiteClr"
android:background="#color/whiteClr"
android:layout_weight="10"
android:orientation="horizontal"
android:weightSum="100">
<ImageButton
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:src="#drawable/search_img"
android:background="#null"
android:layout_weight="25"
android:layout_marginLeft="0dp"
android:layout_gravity="center"
android:onClick="openSearchFragment"/>
<ImageButton
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:src="#drawable/chat_img"
android:background="#null"
android:layout_weight="50"
android:layout_gravity="center"
android:onClick="openChatFragment"/>
<ImageButton
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:src="#drawable/profile_img"
android:background="#null"
android:layout_weight="25"
android:layout_gravity="center"
android:onClick="openProfile"/>
</LinearLayout>
</LinearLayout>
This is the fragment
public class SearchFragment extends ListFragment implements AdapterView.OnItemClickListener{
ArrayList<String> list;
ListViewAdapter myAdapter;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstance){
View view = inflater.inflate(R.layout.fragment_search,container,false);
list = new ArrayList<String>();
list.add("I");
list.add("am");
list.add("Iron");
myAdapter = new ListViewAdapter(list,getActivity().getBaseContext());
setListAdapter(myAdapter);
return view;
}
#Override
public void onActivityCreated(Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
getListView().setOnItemClickListener(this);
}
public void onItemClick(AdapterView<?> parent, View view, int position,long id) {
Toast.makeText(getActivity(), "Item: " + position, Toast.LENGTH_SHORT).show();
}
}
The Layout of the fragment is inside a linear layout consisting of a
ListView with "#android:id/list" as the ID and a TextView.
Don't worry about the adapter. it's working fine.. I tested it out on an activity. Works perfectly fine.
This is what it looks like now
It is correct. You have two SearchFragment. One declared static in your layout, the other added through a FragmentTransaction. Fragments declared static in the layout can't be replaced using a programmatically transaction. Just replace
<fragment
android:id="#+id/homepageFragment"
android:name="com.example.summer.toothbrush.SearchFragment"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
tools:layout="#layout/fragment_search"/>
with
<FrameLayout
android:id="#+id/homepageFragment"
android:layout_width="fill_parent"
android:layout_height="fill_parent"/>
and it is going to work as you expect

Categories

Resources