Я сохранил все свои данные в облачном хранилище firebase. Попытка показать их на recyclerView, а также сделать их фильтруемыми. Но когда я нахожусь на фрагменте, где реализован recycleView, ничего не отображается, пока я не нажму на панель поиска EditText. Чтобы понять проблему, нажмите здесь https://imgur.com/6CVTKCu, чтобы посмотреть видео.
MarketFragment. java
package com.example.farmersapp;
import android.os.Bundle;
import android.text.Editable;
import android.text.TextWatcher;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.EditText;
import androidx.annotation.NonNull;
import androidx.constraintlayout.widget.ConstraintLayout;
import androidx.fragment.app.Fragment;
import androidx.fragment.app.FragmentManager;
import androidx.fragment.app.FragmentTransaction;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import com.firebase.ui.firestore.FirestoreRecyclerOptions;
import com.google.android.gms.tasks.OnFailureListener;
import com.google.android.gms.tasks.OnSuccessListener;
import com.google.android.material.floatingactionbutton.FloatingActionButton;
import com.google.firebase.firestore.CollectionReference;
import com.google.firebase.firestore.FirebaseFirestore;
import com.google.firebase.firestore.Query;
import com.google.firebase.firestore.QuerySnapshot;
import java.util.ArrayList;
import java.util.List;
public class MarketFragment extends Fragment {
private static final String ARG_PARAM1 = "param1";
private static final String ARG_PARAM2 = "param2";
private FloatingActionButton floatingAddNewItemButton;
private String mParam1;
private String mParam2;
RecyclerView marketRecyleView;
ListAdapter_Market marketListAdapter;
ArrayList<productsListOfMarketFirestore> mData;
ConstraintLayout rootLayout;
EditText searchInput;
CharSequence search = "";
FirestoreRecyclerOptions<productsListOfMarketFirestore> options;
AlternateListAdapter_Market adapter;
private FirebaseFirestore firebaseFirestore = FirebaseFirestore.getInstance();
private CollectionReference productsOfMarketCollectionRef = firebaseFirestore.collection("products_of_market");
public MarketFragment() {
}
public static MarketFragment newInstance(String param1, String param2) {
MarketFragment fragment = new MarketFragment();
Bundle args = new Bundle();
args.putString(ARG_PARAM1, param1);
args.putString(ARG_PARAM2, param2);
fragment.setArguments(args);
return fragment;
}
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
if (getArguments() != null) {
mParam1 = getArguments().getString(ARG_PARAM1);
mParam2 = getArguments().getString(ARG_PARAM2);
}
}
productsListOfMarketFirestore[] item = new productsListOfMarketFirestore[100];
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
View contentView =inflater.inflate(R.layout.fragment_market, container, false);
floatingAddNewItemButton = contentView.findViewById(R.id.floatingActionButton);
marketRecyleView = contentView.findViewById(R.id.market_rv);
rootLayout = contentView.findViewById(R.id.root_layout);
searchInput = contentView.findViewById(R.id.search_input);
mData = new ArrayList<>();
searchInput.setBackgroundResource(R.drawable.search_input_style);
rootLayout.setBackgroundColor(getResources().getColor(R.color.white));
getDataToArray();
setUpRecyclerViewManual();
searchInput.addTextChangedListener(new TextWatcher() {
@Override
public void beforeTextChanged(CharSequence s, int start, int count, int after) {
}
@Override
public void onTextChanged(CharSequence s, int start, int before, int count) {
adapter.getFilter().filter(s);
search = s;
}
@Override
public void afterTextChanged(Editable s) {
}
});
Log.d("checked","i am here");
floatingAddNewItemButton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Fragment fragment = new AddNewItemFragment();
FragmentManager fragmentManager = getActivity().getSupportFragmentManager();
FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction();
fragmentTransaction.setCustomAnimations(R.anim.enter_from_right, R.anim.exit_to_right, R.anim.enter_from_right, R.anim.exit_to_right);
fragmentTransaction.replace(R.id.container, fragment);
fragmentTransaction.addToBackStack(null);
fragmentTransaction.commit();
}
});
return contentView;
}
@Override
public void onStart() {
super.onStart();
}
@Override
public void onStop() {
super.onStop();
}
private void getDataToArray() {
productsOfMarketCollectionRef.get().addOnSuccessListener(new OnSuccessListener<QuerySnapshot>() {
@Override
public void onSuccess(QuerySnapshot queryDocumentSnapshots) {
if (queryDocumentSnapshots.isEmpty()) {
Log.d("checked", "database is empty");
} else {
List<productsListOfMarketFirestore> data = queryDocumentSnapshots.toObjects(productsListOfMarketFirestore.class);
mData.addAll(data);
Log.d("checked success:", "ok " + mData);
}
}
}).addOnFailureListener(new OnFailureListener() {
@Override
public void onFailure(@NonNull Exception e) {
Log.d("checked", "data load failed");
}
});
}
private void setUpRecyclerViewManual() {
marketRecyleView.setHasFixedSize(true);
RecyclerView.LayoutManager layoutManager = new LinearLayoutManager(this.getContext());
adapter = new AlternateListAdapter_Market(mData,this.getContext());
marketRecyleView.setAdapter(adapter);
Log.d("checked","adapter called");
marketRecyleView.setLayoutManager(layoutManager);
}
}
AlternateListAdapter_Market . java
package com.example.farmersapp;
import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.Bundle;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.animation.AnimationUtils;
import android.widget.Filter;
import android.widget.Filterable;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;
import androidx.annotation.NonNull;
import androidx.fragment.app.Fragment;
import androidx.fragment.app.FragmentActivity;
import androidx.fragment.app.FragmentManager;
import androidx.fragment.app.FragmentTransaction;
import androidx.recyclerview.widget.RecyclerView;
import com.google.android.gms.tasks.OnSuccessListener;
import com.google.firebase.storage.FileDownloadTask;
import com.google.firebase.storage.FirebaseStorage;
import com.google.firebase.storage.StorageReference;
import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
public class AlternateListAdapter_Market extends RecyclerView.Adapter<AlternateListAdapter_Market.AlternateListHolder_Market> implements Filterable {
List<productsListOfMarketFirestore>filterList;
List<productsListOfMarketFirestore>mainList;
Context mContext;
@NonNull
@Override
public AlternateListHolder_Market onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
View layout;
layout = LayoutInflater.from(mContext).inflate(R.layout.customlist_item_market, parent, false);
return new AlternateListHolder_Market(layout);
}
@Override
public void onBindViewHolder(@NonNull final AlternateListHolder_Market holder, int position) {
productsListOfMarketFirestore curretItem = filterList.get(position);
holder.imageView.setAnimation(AnimationUtils.loadAnimation(mContext,R.anim.fade_transition_animation));
holder.container.setAnimation(AnimationUtils.loadAnimation(mContext,R.anim.fade_scale_animation));
holder.textView_productId.setText(curretItem.getProductId());
holder.textView_price.setText(curretItem.getProductPrice());
holder.textView_title.setText(curretItem.getProductTitle());
StorageReference storageReference = FirebaseStorage.getInstance().getReferenceFromUrl("gs://app-31e12.appspot.com/user_image1/").child(curretItem.getProductId() + ".jpg");
try {
final File file = File.createTempFile("image", "jpg");
storageReference.getFile(file).addOnSuccessListener(new OnSuccessListener<FileDownloadTask.TaskSnapshot>() {
@Override
public void onSuccess(FileDownloadTask.TaskSnapshot taskSnapshot) {
Bitmap bitmap = BitmapFactory.decodeFile(file.getAbsolutePath());
holder.imageView.setImageBitmap(bitmap);
}
});
} catch (IOException e) {
e.printStackTrace();
}
}
@Override
public int getItemCount() {
return filterList.size();
}
@Override
public Filter getFilter() {
return filteredData;
}
private Filter filteredData= new Filter() {
@Override
protected FilterResults performFiltering(CharSequence constraint) {
List<productsListOfMarketFirestore> filteredList = new ArrayList<>();
if (constraint == null || constraint.length() == 0) {
filterList = mainList;
} else {
String filterPattern = constraint.toString().toLowerCase().trim();
for (productsListOfMarketFirestore item : mainList) {
if (item.getProductTitle().toLowerCase().contains(filterPattern)) {
Log.d("checked","productTitle check "+item.getProductTitle());
filteredList.add(item);
}
}
filterList = filteredList;
}
FilterResults results = new FilterResults();
results.values = filterList;
return results;
}
@Override
protected void publishResults(CharSequence constraint, FilterResults results) {
filterList =(List<productsListOfMarketFirestore>)results.values;
notifyDataSetChanged();
}
};
class AlternateListHolder_Market extends RecyclerView.ViewHolder{
ImageView imageView;
TextView textView_title;
TextView textView_price,textView_productId;
RelativeLayout container;
public AlternateListHolder_Market(@NonNull View itemView) {
super(itemView);
imageView = itemView.findViewById(R.id.imageView_item_market);
textView_title = itemView.findViewById(R.id.textView_item_title_market);
textView_price = itemView.findViewById(R.id.textView_price);
textView_productId = itemView.findViewById(R.id.textView_productId);
container = itemView.findViewById(R.id.item_container_market);
itemView.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Fragment itemFragment = MarketItemDetails.newInstance("", "");
if (itemFragment != null) {
FragmentManager fragmentManager = ((FragmentActivity) v.getContext()).getSupportFragmentManager();
FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction();
Bundle args = new Bundle();
args.putString("productId", textView_productId.getText().toString());
itemFragment.setArguments(args);
fragmentTransaction.setCustomAnimations(R.anim.enter_from_right, R.anim.exit_to_right, R.anim.enter_from_right, R.anim.exit_to_right);
fragmentTransaction.replace(R.id.container, itemFragment);
fragmentTransaction.addToBackStack(null);
fragmentTransaction.commit();
} else {
Log.d("error", "null exception");
}
}
});
}
}
AlternateListAdapter_Market(List<productsListOfMarketFirestore > exampleList,Context Context) {
this.filterList = exampleList;
this.mainList = exampleList;
this.mContext = Context;
}
public void setFilterList(List<productsListOfMarketFirestore> mList)
{
this.filterList = mList;
notifyDataSetChanged();
}
}
productsListOfMarketFirestore. java
package com.example.farmersapp;
public class productsListOfMarketFirestore {
String productArea,productCategory,productCondition,productDescription;
String productId,productOwner,productPrice,productRegion,productTitle;
public productsListOfMarketFirestore() {
}
public productsListOfMarketFirestore(String productArea, String productCategory, String productCondition, String productDescription, String productId, String productOwner, String productPrice, String productRegion, String productTitle) {
this.productArea = productArea;
this.productCategory = productCategory;
this.productCondition = productCondition;
this.productDescription = productDescription;
this.productId = productId;
this.productOwner = productOwner;
this.productPrice = productPrice;
this.productRegion = productRegion;
this.productTitle = productTitle;
}
public String getProductArea() {
return productArea;
}
public String getProductCategory() {
return productCategory;
}
public String getProductCondition() {
return productCondition;
}
public String getProductDescription() {
return productDescription;
}
public String getProductId() {
return productId;
}
public String getProductOwner() {
return productOwner;
}
public String getProductPrice() {
return productPrice;
}
public String getProductRegion() {
return productRegion;
}
public String getProductTitle() {
return productTitle;
}
}
fragment_market. xml
<?xml version="1.0" encoding="utf-8"?>
<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=".MainActivity"
android:background="@color/white"
android:id="@+id/root_layout">
<androidx.recyclerview.widget.RecyclerView
android:id="@+id/market_rv"
android:layout_width="411dp"
android:layout_height="672dp"
android:layout_marginEnd="8dp"
android:paddingTop="20dp"
android:paddingBottom="20dp"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintHorizontal_bias="0.0"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toBottomOf="@+id/search_input"
tools:listitem="@layout/customlist_item_market" />
<com.google.android.material.floatingactionbutton.FloatingActionButton
android:id="@+id/floatingActionButton"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:clickable="true"
android:src="@drawable/ic_add_black_24dp"
app:backgroundTint="#0979D3"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintHorizontal_bias="0.915"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent"
app:layout_constraintVertical_bias="0.845" />
<EditText
android:drawablePadding="8dp"
android:drawableLeft="@drawable/ic_search_gray_24dp"
android:textColor="@color/content_text_color"
android:hint="search"
android:background="@drawable/search_input_style"
android:id="@+id/search_input"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_marginStart="24dp"
android:layout_marginLeft="24dp"
android:layout_marginTop="8dp"
android:layout_marginEnd="16dp"
android:layout_marginRight="16dp"
android:ems="10"
android:inputType="textPersonName"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent"/>
</androidx.constraintlayout.widget.ConstraintLayout>
customlist_item_market. xml
<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.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:layout_marginTop="8dp">
<RelativeLayout
android:id="@+id/item_container_market"
android:layout_width="385dp"
android:layout_height="136dp"
android:layout_marginStart="24dp"
android:background="@color/card_bg_color"
android:paddingBottom="16dp"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintHorizontal_bias="0.0"
app:layout_constraintStart_toStartOf="parent">
<TextView
android:id="@+id/textView_item_title_market"
android:layout_width="207dp"
android:layout_height="32dp"
android:layout_alignParentStart="true"
android:layout_alignParentLeft="true"
android:layout_alignParentTop="true"
android:layout_marginStart="112dp"
android:layout_marginLeft="112dp"
android:layout_marginTop="44dp"
android:text="Simple Title Text "
android:textColor="@color/title_text_color"
android:textStyle="bold" />
<TextView
android:id="@+id/textView_price"
android:layout_width="69dp"
android:layout_height="wrap_content"
android:layout_alignParentStart="true"
android:layout_alignParentLeft="true"
android:layout_alignParentTop="true"
android:layout_marginStart="116dp"
android:layout_marginLeft="116dp"
android:layout_marginTop="85dp"
android:text="TextView" />
<TextView
android:id="@+id/textView_productId"
android:layout_width="69dp"
android:layout_height="wrap_content"
android:layout_alignParentStart="true"
android:layout_alignParentLeft="true"
android:layout_alignParentTop="true"
android:layout_marginStart="113dp"
android:layout_marginLeft="113dp"
android:layout_marginTop="10dp"
android:text="TextView" />
</RelativeLayout>
<ImageView
android:id="@+id/imageView_item_market"
android:layout_width="131dp"
android:layout_height="137dp"
android:layout_marginStart="8dp"
android:layout_marginTop="16dp"
android:layout_marginEnd="8dp"
app:layout_constraintEnd_toStartOf="@+id/container"
app:layout_constraintStart_toStartOf="@+id/container"
app:layout_constraintTop_toTopOf="@+id/container"
app:srcCompat="@mipmap/ic_launcher" />
</androidx.constraintlayout.widget.ConstraintLayout>
Кто-нибудь может помочь, пожалуйста? ...:)