清除捆绑器数据

时间:2018-07-09 15:39:54

标签: java android firebase android-recyclerview

在我的片段中,我有一个EditText,它基本上允许在提交时查询Firebase Realtime数据库中的值,并将其显示在 Recycler View 中。 第一次搜索时一切都很好,但是当我搜索不止一次时,以前的结果将保留在“回收者视图”中。 我试图清除清单,但没有成功。我想我找到了问题,但我解决不了。每当我从数据库将检索到的值从一个片段传递到另一个片段时,都需要清除我的捆绑包。这是我的片段代码(我在其中称为适配器,而不是在我检索数据库值的地方)

public class FilteredResultsFragment extends android.support.v4.app.Fragment {
ImageAdapter imageAdapter;
List<String> listOfImages = new ArrayList<>();
List<String> listOfNames = new ArrayList<>();
private RecyclerView recyclerView;


@Nullable
@Override
public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {

    View viewFilteredResults = inflater.inflate(R.layout.fragment_filtered_results, container, false);

    recyclerView = viewFilteredResults.findViewById(R.id.recyclerViewFiltered);
    recyclerView.setLayoutManager(new LinearLayoutManager(getContext()));
    imageAdapter = new ImageAdapter(listOfImages, listOfNames, getContext());
    recyclerView.setAdapter(imageAdapter);

    return viewFilteredResults;
}

@Override
public void onViewCreated(@NonNull View view, @Nullable Bundle savedInstanceState) {
    super.onViewCreated(view, savedInstanceState);
    if (getArguments() != null) {
        removeAll();
        listOfImages.addAll(getArguments().getStringArrayList("listOfImages"));
        listOfNames.addAll(getArguments().getStringArrayList("listOfNames"));
        Log.d("IMAGENS", "img "+listOfImages);
        Log.d("Nomes","nome "+listOfNames);
        imageAdapter.notifyDataSetChanged();
    }
}

public void removeAll(){
    listOfImages.clear();
    listOfNames.clear();
    imageAdapter.notifyDataSetChanged();
}

}

如您所见,我创建了一个函数,该函数应允许我清除数据...这是我的 Adaptor

public class ImageAdapter extends RecyclerView.Adapter<ImageAdapter.ImageViewHolder> {
List<String> listaPaisesFiltrados;
List<String> listaNomesFiltrados;
android.content.Context context;
ImageAdapter(List<String> listaPaisesFiltrados, List<String> listaNomesFiltrados, android.content.Context c) {
    this.listaPaisesFiltrados = listaPaisesFiltrados;
    this.listaNomesFiltrados = listaNomesFiltrados;
    this.context = c;
}

@NonNull
@Override
public ImageViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
    View itemView = LayoutInflater.from(parent.getContext())
            .inflate(R.layout.list_item_view, parent, false);

    return new ImageViewHolder(itemView);
}

@Override
public void onBindViewHolder(@NonNull ImageViewHolder holder, int position) {
    String imageUrl = listaPaisesFiltrados.get(holder.getAdapterPosition());
    String nomePais = listaNomesFiltrados.get(holder.getAdapterPosition());
    android.content.Context context1 = context.getApplicationContext();
    Log.d("ADAPTER", "imageUrl : " + imageUrl + " position : " + holder.getAdapterPosition());

    Typeface tpPaisNome = Typeface.createFromAsset(holder.itemView.getContext().getAssets(),"fonts/RobotoSlab-Bold.ttf"); // Define a Typeface
    holder.textView.setTypeface(tpPaisNome);
    holder.textView.setText(nomePais);

    Glide.with(holder.imageView.getContext()).load(imageUrl).centerCrop().into(holder.imageView);
}

@Override
public int getItemCount() {
    Log.d("ADAPTER", "SIZE : " + listaPaisesFiltrados.size());
    return listaPaisesFiltrados.size();
}


public class ImageViewHolder extends RecyclerView.ViewHolder {
    ImageView imageView;
    TextView textView;

    public ImageViewHolder(View itemView) {

        super(itemView);
        imageView = itemView.findViewById(R.id.imgPaisFiltrado);
        textView = itemView.findViewById(R.id.txtNomePaisFiltrado);
        }
    }
}

编辑

在我的ExploreFragment(那里有查询和EditText)中,我通过Bundle向打开适配器的片段发送了两个ArrayList。我需要清除Bundler,但是当我使用blunder.clear()时,没有值传递到另一个片段,也没有图像显示。这是我的代码

srcView.setOnEditorActionListener(new EditText.OnEditorActionListener() {
        @Override
        public boolean onEditorAction(TextView v, int actionId, KeyEvent event) {
            boolean handled = false;
            if (actionId == EditorInfo.IME_ACTION_DONE) {
                txtRecomendado.setVisibility(View.INVISIBLE);
                scrollView.setVisibility(View.INVISIBLE);
                final Bundle bundler = new Bundle();
                bundler.clear();
                FirebaseDatabase mDatabase = FirebaseDatabase.getInstance();
                    DatabaseReference paisNomeContinentes = mDatabase.getReference().child("paises");
                    Query queries = paisNomeContinentes.orderByChild("Nome").startAt(String.valueOf(srcView.getText())).endAt(String.valueOf(srcView.getText())+"\uf8ff");
                    Log.d("AQUIPUTO","teste "+String.valueOf(srcView.getText()));
                    queries.addListenerForSingleValueEvent(new com.google.firebase.database.ValueEventListener() {
                        @Override
                        public void onDataChange(@NonNull DataSnapshot dataSnapshot) {

                            List<String> imagemPaisList = new ArrayList<>();
                            List<String> nomePaisList = new ArrayList<>();
                            for (DataSnapshot ds : dataSnapshot.getChildren()) {
                                String imagemPais = ds.child("Imagem").getValue(String.class);
                                String nomePais = ds.child("Nome").getValue(String.class);
                                imagemPaisList.add(imagemPais);
                                nomePaisList.add(nomePais);
                            }
                            int urlCount = imagemPaisList.size();

                            //  int randomImage = new Random().nextInt(urlCount);

                            for (int i = 0; i < nomePaisList.size(); i++) {

                                //Integer randomVariavel = new Random().nextInt(urlCount);

                                randomImagemPaisList.add(imagemPaisList.get(i));
                                randomNomePaisList.add(nomePaisList.get(i));

                            }

                            getFragmentManager().popBackStack();
                            FragmentTransaction transaction = getActivity().getSupportFragmentManager().beginTransaction();
                            transaction.setCustomAnimations(R.anim.slide_up_info,R.anim.slide_down_info);
                            FilteredResultsFragment fragment = new FilteredResultsFragment();
                            bundler.putStringArrayList("listOfImages", (ArrayList<String>) randomImagemPaisList);
                            bundler.putStringArrayList("listOfNames", (ArrayList<String>) randomNomePaisList);
                            fragment.setArguments(bundler);
                            transaction.replace(R.id.fragContainerExploreFilteredResults, fragment);
                            transaction.addToBackStack(null);
                            transaction.commit();

                        }

如何清除我的包裹?使用后,我尝试清除它:

  bundler.putStringArrayList("listOfImages", (ArrayList<String>) randomImagemPaisList);
                            bundler.putStringArrayList("listOfNames", (ArrayList<String>) randomNomePaisList);
                            fragment.setArguments(bundler);

如果执行此操作,则没有值从一个片段传递到另一个片段。我已经尝试在fragment.trasaction完成后清除它,但仍然出现相同的“错误” ...

3 个答案:

答案 0 :(得分:0)

当您尝试通过调用removeAll进行清除时,只清除了Fragment类中的列表对象。您需要清除RecyclerView.Adapter类中的列表对象。

尝试一下:

  1. removeAll移动到适配器。这样,您可以清除该适配器中的列表对象。
  2. 在片段中,只需从适配器调用removeAll

示例代码:

Fragment.java

//No more removeAll() here
public void callAdapterToRemove() {
   imageAdapter.removeAll();
}

ImageAdapter.java

//Now it's here
public void removeAll() {
   listaPaisesFiltrados.clear();
   listaNomesFiltrados.clear();
   notifyDataSetChanged();
}

答案 1 :(得分:0)

可能没有用recyclerview通知更新的数据,您可以在适配器类中创建doRefresh方法,然后更新列表并通知它,请参见下面的代码

片段代码

public class FilteredResultsFragment extends android.support.v4.app.Fragment {
    ImageAdapter imageAdapter;
    List<String> listOfImages = new ArrayList<>();
    List<String> listOfNames = new ArrayList<>();
    private RecyclerView recyclerView;


    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {

        View viewFilteredResults = inflater.inflate(R.layout.fragment_filtered_results, container, false);

       setAdapter();

        return viewFilteredResults;
    }

    @Override
    public void onViewCreated(@NonNull View view, @Nullable Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);
        if (getArguments() != null) {
            listOfImages.clear();
            listOfNames.clear();    
            listOfImages.addAll(getArguments().getStringArrayList("listOfImages"));
            listOfNames.addAll(getArguments().getStringArrayList("listOfNames"));
            Log.d("IMAGENS", "img "+listOfImages);
            Log.d("Nomes","nome "+listOfNames);
            setAdapter();
        }
    }

    private void setAdapter() {
        if (listOfImages != null && listOfNames != null) {

            if (imageAdapter == null) {
                imageAdapter = new ImageAdapter(getContext());
            }

            imageAdapter.doRefresh(listOfImages, listOfNames);

            if (recyclerView.getAdapter() == null) {
                recyclerView = viewFilteredResults.findViewById(R.id.recyclerViewFiltered);
                recyclerView.setLayoutManager(new LinearLayoutManager(getContext()));

                recyclerView.setAdapter(imageAdapter);
            }
        }
    }
}

和下面的适配器类

public class ImageAdapter extends RecyclerView.Adapter<ImageAdapter.ImageViewHolder> {
    List<String> listaPaisesFiltrados;
    List<String> listaNomesFiltrados;
    android.content.Context context;
    ImageAdapter(android.content.Context c) {
        this.context = c;
    }

    public void doRefresh(List<String> listaPaisesFiltrados, List<String> listaNomesFiltrados) {
        this.listaPaisesFiltrados = listaPaisesFiltrados;
        this.listaNomesFiltrados = listaNomesFiltrados;
        notifyDataSetChanged();
    }

    @NonNull
    @Override
    public ImageViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
        View itemView = LayoutInflater.from(parent.getContext())
                .inflate(R.layout.list_item_view, parent, false);

        return new ImageViewHolder(itemView);
    }

    @Override
    public void onBindViewHolder(@NonNull ImageViewHolder holder, int position) {
        String imageUrl = listaPaisesFiltrados.get(holder.getAdapterPosition());
        String nomePais = listaNomesFiltrados.get(holder.getAdapterPosition());
        android.content.Context context1 = context.getApplicationContext();
        Log.d("ADAPTER", "imageUrl : " + imageUrl + " position : " + holder.getAdapterPosition());

        Typeface tpPaisNome = Typeface.createFromAsset(holder.itemView.getContext().getAssets(),"fonts/RobotoSlab-Bold.ttf"); // Define a Typeface
        holder.textView.setTypeface(tpPaisNome);
        holder.textView.setText(nomePais);

        Glide.with(holder.imageView.getContext()).load(imageUrl).centerCrop().into(holder.imageView);
    }

    @Override
    public int getItemCount() {
        Log.d("ADAPTER", "SIZE : " + listaPaisesFiltrados.size());
        return listaPaisesFiltrados.size();
    }


    public class ImageViewHolder extends RecyclerView.ViewHolder {
        ImageView imageView;
        TextView textView;

        public ImageViewHolder(View itemView) {

            super(itemView);
            imageView = itemView.findViewById(R.id.imgPaisFiltrado);
            textView = itemView.findViewById(R.id.txtNomePaisFiltrado);
        }
    }
}

答案 2 :(得分:0)

您可以尝试创建新的适配器并将其设置为回收站。

listOfImages.clear();
listOfNames.clear();
/* 
   Adding your new searching data here 
*/
recyclerView.setAdapter(new ImageAdapter(listOfImages, listOfNames, getContext());
recyclerView.invalidate();