How to fix TextView being rendered blank on new Activity - java

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

Related

Recyclerview and adapter doesn’t show

https://www.youtube.com/watch?v=M8sKwoVjqU0
i watched this video and i have done evertyhing same with.But there is a problem i guess myadapter class doesn't work because when i click button it comes just white screen as you see on the picture. i couldn't figure out where is the fault when i check the log no problem. but i just wanna take data from firebase to textview. but i can't get any result also at least it must see there just textview which is have text firstname but i can't see on my activity.i might be don't know the true page to will show
---this my myadapter.class----
public class Myadapter extends RecyclerView.Adapter<Myadapter.MyViewHolder> {
Context context;
ArrayList<User> list ;
public Myadapter(Context context, ArrayList<User> list) {
this.context = context;
this.list = list;
}
#NonNull
#Override
public MyViewHolder onCreateViewHolder(#NonNull ViewGroup parent, int viewType) {
View v = LayoutInflater.from(context).inflate(R.layout.item,parent,false);
return new MyViewHolder(v) ;
}
#Override
public void onBindViewHolder(#NonNull MyViewHolder holder, int position) {
User user =list.get(position);
holder.textView.setText(user.getTitle());
}
#Override
public int getItemCount() {
return list.size();
}
public static class MyViewHolder extends RecyclerView.ViewHolder{
TextView textView, TextView;
public MyViewHolder(#NonNull View itemView) {
super(itemView);
TextView = itemView.findViewById(R.id.txtview);
textView=itemView.findViewById(R.id.title);
}
}
---this my userlist.class---
public class userlist extends AppCompatActivity {
RecyclerView recyclerView;
DatabaseReference database;
Myadapter myadapter;
ArrayList<User>list;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_userlist);
recyclerView=findViewById(R.id.userlist);
database = FirebaseDatabase.getInstance().getReference("users");
recyclerView.setHasFixedSize(true);
recyclerView.setLayoutManager(new LinearLayoutManager(this));
list = new ArrayList<>();
myadapter = new Myadapter(this,list);
recyclerView.setAdapter(myadapter);
database.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot snapshot) {
for ( DataSnapshot dataSnapshot: snapshot.getChildren()){
User user=dataSnapshot.getValue(User.class);
list.add(user);
}
myadapter.notifyDataSetChanged();
}
---this my mainactivity.class---
public class MainActivity extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Button button1 = (Button) findViewById(R.id.button);
button1.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Intent i = new Intent(MainActivity.this,userlist.class);
startActivity(i);
finish();}
});
}
}
{
"users" : {
"value1" : {
"title" : "reachthis"
}
}
}
<androidx.constraintlayout.widget.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=".userlist">
---activity_userlist---
<androidx.recyclerview.widget.RecyclerView
android:id="#+id/userlist"
android:layout_width="409dp"
android:layout_height="729dp"
android:layout_marginStart="1dp"
android:layout_marginTop="1dp"
android:layout_marginEnd="1dp"
android:layout_marginBottom="1dp"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintHorizontal_bias="0.0"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent"
app:layout_constraintVertical_bias="0.0" />
</androidx.constraintlayout.widget.ConstraintLayout>```
---item.xml---
<?xml version="1.0" encoding="utf-8"?>
<androidx.cardview.widget.CardView xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
xmlns:app="http://schemas.android.com/apk/res-auto"
app:cardElevation="8dp"
>
<LinearLayout
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:orientation="vertical"> </LinearLayout>
<LinearLayout
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center_vertical"
>
<TextView
android:id="#+id/txtview"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="first name"
android:textColor="#color/black"
android:textSize="26sp"
android:textStyle="bold"></TextView><TextView
android:id="#+id/title"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="first name"
android:textColor="#color/black"
android:textSize="20sp"
></TextView>
</LinearLayout>
</androidx.cardview.widget.CardView>

Add ArrayLIst to Recyclerview

I have an AlertDialog in it there used to be a ListView in which the contents of the ArrayList were displayed. For beauty, I decided to replace it with Recyclerview, Card and the problems started.
Items are added to ArrayList <String> mainListWord during the work and they should be included in the Recyclerview cards. The problem is that either the entire list falls into one card at once, or each next card contains the previous elements + 1. For example: the first card: 1 element, the second card: 2 elements, etc.
How to implement it so that when a new element is added to the array, it will be placed in its own card?
activity_main.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"
tools:context=".MainActivity">
<EditText
android:id="#+id/innerText"
android:layout_width="wrap_content"
android:layout_height="50dp"
android:layout_centerInParent="true"/>
<Button
android:id="#+id/press"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginTop="10dp"
android:text="Press"
android:layout_below="#id/innerText"
android:layout_centerHorizontal="true"
android:onClick="openDialog"/>
</RelativeLayout>
recycler_item.xml
<?xml version="1.0" encoding="utf-8"?>
<androidx.cardview.widget.CardView
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"
xmlns:app="http://schemas.android.com/apk/res-auto"
app:cardCornerRadius="4dp"
android:layout_margin="4dp"
app:cardBackgroundColor="#color/colorCardBack">
<RelativeLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_margin="5dp"
android:background="#color/colorCard">
<ImageView
android:id="#+id/imageView_1"
android:layout_width="50dp"
android:layout_height="50dp"
android:padding="4dp" />
<TextView
android:id="#+id/textview_1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Text_1"
android:textStyle="bold"
android:textColor="#android:color/black"
android:layout_centerInParent="true"
android:textSize="16sp"
android:layout_marginStart="5dp"
android:layout_toEndOf="#id/imageView_1"/>
</RelativeLayout>
</androidx.cardview.widget.CardView>
stats_fragment.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"
tools:context=".MainActivity">
<androidx.recyclerview.widget.RecyclerView
android:id="#+id/recycler_view"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:padding="50dp"
android:layout_margin="10dp"
android:background="#color/colorAccent"
android:scrollbars="vertical"
android:layout_above="#id/butClose"/>
<Button
android:id="#+id/butClose"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginBottom="5dp"
android:layout_centerHorizontal="true"
android:layout_alignParentBottom="true"/>
</RelativeLayout>
MainActivity.java
public class MainActivity extends AppCompatActivity {
private EditText innerText;
private Button press, butClose;
private ArrayList<RecyclerViewItem> recyclerViewItem;
private ArrayList<String> mainListWord;
private AlertDialog OptionDialog;
private RecyclerView recyclerView;
private RecyclerView.Adapter adapter;
private RecyclerView.LayoutManager layoutManager;
#RequiresApi(api = Build.VERSION_CODES.O)
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
recyclerViewItem = new ArrayList<>();
mainListWord = new ArrayList<>();
innerText = findViewById(R.id.innerText);
press = findViewById(R.id.butClose);
}
#RequiresApi(api = Build.VERSION_CODES.O)
public void makeRecyclerList(ArrayList<String> income){
String[] listWord_lenght = income.toArray(new String[0]);
String keyWord = (String.join("", listWord_lenght));
recyclerViewItem.add(new RecyclerViewItem(R.drawable.star, keyWord));
}
#RequiresApi(api = Build.VERSION_CODES.O)
public void openDialog(View v){
String word = innerText.getText().toString();
mainListWord.add(word);
makeRecyclerList(mainListWord);
Dialogus();
innerText.setText("");
}
public void Dialogus(){
LayoutInflater li = (LayoutInflater) this.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
View v = li.inflate(R.layout.stats_fragment, null, false);
OptionDialog = new AlertDialog.Builder(this).create();
OptionDialog.setTitle("TestInfo");
recyclerView = v.findViewById(R.id.recycler_view);
recyclerView.setHasFixedSize(true);
adapter = new RecyclerViewAdapter(recyclerViewItem);
layoutManager = new LinearLayoutManager(this);
recyclerView.setAdapter(adapter);
recyclerView.setLayoutManager(layoutManager);
butClose = v.findViewById(R.id.butClose);
OptionDialog.setView(v);
OptionDialog.setCancelable(true);
butClose.setBackgroundColor(Color.CYAN);
butClose.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
OptionDialog.dismiss();
}
});
OptionDialog.show();
}
}
RecyclerViewAdapter.java
public class RecyclerViewAdapter extends RecyclerView.Adapter<RecyclerViewAdapter.RecyclerViewViewHolder> {
private ArrayList<RecyclerViewItem> arrayList;
public static class RecyclerViewViewHolder extends RecyclerView.ViewHolder {
public ImageView imageView_1;
public TextView textview_1;
public RecyclerViewViewHolder(#NonNull View itemView) {
super(itemView);
imageView_1 = itemView.findViewById(R.id.imageView_1);
textview_1 = itemView.findViewById(R.id.textview_1);
}
}
public RecyclerViewAdapter(ArrayList<RecyclerViewItem> arrayList){
this.arrayList = arrayList;
}
#NonNull
#Override
public RecyclerViewViewHolder onCreateViewHolder(#NonNull ViewGroup viewGroup, int viewType) {
View view = LayoutInflater.from(viewGroup.getContext()).inflate(R.layout.recycler_item, viewGroup, false);
RecyclerViewViewHolder recyclerViewViewHolder= new RecyclerViewViewHolder(view);
return recyclerViewViewHolder;
}
#Override
public void onBindViewHolder(#NonNull RecyclerViewViewHolder recyclerViewViewHolder, int position) {
RecyclerViewItem recyclerViewItem = arrayList.get(position);
recyclerViewViewHolder.imageView_1.setImageResource(recyclerViewItem.getImageResource());
recyclerViewViewHolder.textview_1.setText(recyclerViewItem.getText_1());
}
#Override
public int getItemCount() {
return arrayList.size();
}
}
RecyclerViewItem.java
package freijer.app.one;
public class RecyclerViewItem {
private int imageResource;
private String text_1;
public int getImageResource() {
return imageResource;
}
public void setImageResource(int imageResource) {
this.imageResource = imageResource;
}
public String getText_1() {
return text_1;
}
public void setText_1(String text_1) {
this.text_1 = text_1;
}
public RecyclerViewItem(int imageResource, String text_1) {
this.imageResource = imageResource;
this.text_1 = text_1;
}
}

Widget layout from Activity still appear after fragment add transaction

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

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

RecyclerView create views with x amount of rows

I want to create dynamic views with x number of rows for each CardView that gets created. To help illustrate my idea this image shows what I essentially want to do.
For each CardView I want to be able to put any amount of TableRows into the CardView. So one CardView could have 4 rows whereas the next CardView could have 2 rows and so on.
EDIT: Implementation
Essentially this view is replicated several times, I would like to minimise having to write seperate layouts for each CardView with x amount of rows like in the Card Storage implemenation which is more reusable than what I currently have. As I hit the limit here, I have posted a pastebin of the current layout with rows that I have
https://pastebin.com/9RFDGhXv
Layout: Card Storage
<?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"
android:layout_width="match_parent"
android:layout_height="wrap_content">
<android.support.v7.widget.CardView
app:layout_constraintLeft_toLeftOf="parent"
app:layout_constraintRight_toRightOf="parent"
app:layout_constraintTop_toTopOf="parent"
style="#style/CardStyle">
<android.support.constraint.ConstraintLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
style="#style/MainConstraints" >
<TableRow
android:id="#+id/row_one"
android:layout_width="0dp"
android:layout_height="wrap_content"
app:layout_constraintTop_toTopOf="parent"
app:layout_constraintLeft_toLeftOf="parent"
app:layout_constraintRight_toRightOf="parent">
<TextView
android:id="#+id/card_title"
style="#style/Title"/>
</TableRow>
<TableRow
android:id="#+id/row_two"
android:layout_height="wrap_content"
android:layout_width="0dp"
app:layout_constraintTop_toBottomOf="#+id/row_one"
app:layout_constraintLeft_toLeftOf="parent"
app:layout_constraintRight_toRightOf="parent">
<android.support.constraint.ConstraintLayout>
<ImageView
android:id="#+id/drawable"
android:layout_height="wrap_content"
android:layout_width="wrap_content"
app:layout_constraintTop_toTopOf="parent"
app:layout_constraintLeft_toLeftOf="parent"
style="#style/RowDrawableElement"
/>
<TextView
android:id="#+id/percentage_descriptor"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
app:layout_constraintTop_toTopOf="parent"
app:layout_constraintLeft_toRightOf="#id/drawable"
android:text="#string/percentage_descriptor"
style="#style/RowTextElement" />
<TextView
android:id="#+id/percentage_text"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
app:layout_constraintTop_toTopOf="parent"
app:layout_constraintRight_toRightOf="parent"
style="#style/RowTextElement" />
</android.support.constraint.ConstraintLayout>
</TableRow>
<TableRow
android:id="#+id/row_three"
android:layout_width="match_parent"
android:layout_height="wrap_content"
app:layout_constraintTop_toBottomOf="#id/row_two"
app:layout_constraintRight_toRightOf="parent"
app:layout_constraintLeft_toLeftOf="parent">
<ProgressBar
android:id="#+id/progress_bar"
android:layout_width="match_parent"
android:layout_height="wrap_content"
app:layout_constraintRight_toRightOf="parent"
app:layout_constraintTop_toTopOf="parent"
app:layout_constraintBottom_toBottomOf="parent"
style="?android:attr/progressBarStyleHorizontal"
/>
</TableRow>
<TableRow
android:id="#+id/row_four"
android:layout_width="match_parent"
android:layout_height="wrap_content"
app:layout_constraintTop_toBottomOf="#id/row_three"
app:layout_constraintLeft_toLeftOf="parent"
app:layout_constraintRight_toRightOf="parent">
<android.support.constraint.ConstraintLayout>
<TextView
android:id="#+id/text_used"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
app:layout_constraintTop_toTopOf="parent"
app:layout_constraintLeft_toLeftOf="parent"
/>
<TextView
android:id="#+id/text_total"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
app:layout_constraintTop_toTopOf="parent"
app:layout_constraintRight_toRightOf="parent"/>
</android.support.constraint.ConstraintLayout>
</TableRow>
</android.support.constraint.ConstraintLayout>
</android.support.v7.widget.CardView>
</android.support.constraint.ConstraintLayout>
Adapter
public class StorageAdapter extends RecyclerView.Adapter<StorageAdapter.MyViewHolder> {
private Context mContext;
private List<StorageObjects> mList;
public StorageAdapter(Context context, List<StorageObjects> list) {
this.mContext = context;
this.mList = list;
}
#Override
public MyViewHolder onCreateViewHolder(ViewGroup parent, int i) {
View view = LayoutInflater.from(parent.getContext())
.inflate(R.layout.card_storage, parent, false);
return new MyViewHolder(view);
}
#SuppressLint("SetTextI18n")
#Override
public void onBindViewHolder(MyViewHolder holder, int position) {
StorageObjects storageObjects = mList.get(position);
long used = storageObjects.getUsed();
long total = storageObjects.getTotal();
holder.mProgress.setMax(0);
holder.mProgress.setProgress(0);
holder.mTitle.setText(storageObjects.getTitle());
MiscUtils.testDrawableIdentifier(mContext.getApplicationContext(), holder.mImageViews, storageObjects.getDrawables());
holder.mPercentage.setText(storageObjects.getPercentage() + mContext.getString(R.string.percentage));
holder.mProgress.setMax((int) (total/100000));
holder.mProgress.setProgress((int) (used/100000));
holder.mUsed.setText(MiscUtils.humanReadableByteSize(used));
holder.mTotal.setText(MiscUtils.humanReadableByteSize(total));
}
#Override
public int getItemCount() {
return mList.size();
}
static class MyViewHolder extends RecyclerView.ViewHolder {
#BindView(R.id.card_title) TextView mTitle;
#BindViews({R.id.drawable}) List<ImageView> mImageViews;
#BindView(R.id.percentage_text) TextView mPercentage;
#BindView(R.id.progress_bar) ProgressBar mProgress;
#BindView(R.id.text_used) TextView mUsed;
#BindView(R.id.text_total) TextView mTotal;
MyViewHolder(View view) {
super(view);
ButterKnife.bind(this, view);
}
}
}
Class Storage
public class Storage extends Fragment {
private Unbinder mUnbinder;
private List<StorageObjects> storageList;
private StorageAdapter adapter;
private RecyclerView.LayoutManager mLayoutManager;
#BindArray(R.array.storage_ic_images)
String mDrawables[];
#BindView(R.id.recycler_view)
RecyclerView mRecyclerView;
public Storage() {
// Required empty public constructor
}
public static Storage newInstance() {
return new Storage();
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
View view = inflater.inflate(R.layout.fragment_storage, container, false);
mUnbinder = ButterKnife.bind(this, view);
return view;
}
#Override
public void onViewCreated(View view, #Nullable Bundle savedInstanceState) {
super.onViewCreated(view, savedInstanceState);
}
#Override
public void onResume() {
super.onResume();
initRecyclerView();
}
#Override
public void onDestroy() {
super.onDestroy();
mUnbinder.unbind();
}
private void initRecyclerView() {
storageList = new ArrayList<>();
adapter = new StorageAdapter(getActivity(), storageList);
mRecyclerView.setHasFixedSize(true);
mRecyclerView.setLayoutManager(mLayoutManager = ViewUtils.getLayoutManager(getActivity()));
mRecyclerView.addItemDecoration(new GridSpacingItemDecoration(2, ViewUtils.dpToPx(
getActivity(), 10), true));
mRecyclerView.setItemAnimator(new DefaultItemAnimator());
mRecyclerView.setAdapter(adapter);
prepareView();
}
#SuppressLint("SetTextI18n")
private void prepareView(){
StorageObjects storage
= new StorageObjects(
getActivity().getString(R.string.int_storage_title),
StorageUtils.internalUsed(),
StorageUtils.internalTotal(),
StorageUtils.internalPercentage(),
mDrawables[0]);
storageList.add(storage);
storage = new StorageObjects (
getActivity().getString(R.string.ext_storage_title),
StorageUtils.externalUsed(getActivity()),
StorageUtils.externalTotal(getActivity()),
StorageUtils.externalPercentage(getActivity()),
mDrawables[1]
);
storageList.add(storage);
adapter.notifyDataSetChanged();
}
}
If number of rows per card view is less then you can inflate edit text and add it to linear layout.
Note : It's a bad practice to add scroll view inside a scroll view

Categories

Resources