Home > Software engineering >  Android studio java can't get context in Fragment
Android studio java can't get context in Fragment

Time:06-19

I am absolute beginner for this, I'm sorry if this such a dumb mistakes. so, I created fragment in which i have got recyclerView, but my recycler view is empty, i saw that my context is empty, and i think, that it can be the reason of this, i try to use getActivity

here is code of my fragment

package com.example.pocketcinema;

import android.content.Context;
import android.content.Intent;
import android.os.Bundle;

import androidx.annotation.NonNull;
import androidx.fragment.app.Fragment;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;

import com.google.android.gms.tasks.OnCompleteListener;
import com.google.android.gms.tasks.Task;
import com.google.firebase.firestore.FirebaseFirestore;
import com.google.firebase.firestore.QueryDocumentSnapshot;
import com.google.firebase.firestore.QuerySnapshot;

import java.util.ArrayList;
import java.util.List;


public class SearchFragment extends Fragment implements RecyclerViewInterface {

private RecyclerView recyclerView;
RecyclerViewInterface rci;
MyAdapter myAdapter;
public List<String> nameOfFilm, youTubeUrl, photoUrl, descriptionToFilm, category;
FirebaseFirestore db = FirebaseFirestore.getInstance();

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

    recyclerView = inflater.inflate(R.layout.fragment_search, container, 
false).findViewById(R.id.filmsList);
    rci = this;
    nameOfFilm = new ArrayList<>();
    youTubeUrl = new ArrayList<>();
    photoUrl = new ArrayList<>();
    descriptionToFilm = new ArrayList<>();
    category = new ArrayList<>();
   
    loadFilmsFromDB();

    return inflater.inflate(R.layout.fragment_search, container, false);

}

private void loadFilmsFromDB() {
  Context context = requireContext();

    db.collection("films").get().addOnCompleteListener(new 
OnCompleteListener<QuerySnapshot>() 
 {
        @Override
        public void onComplete(@NonNull Task<QuerySnapshot> task) {
            for (QueryDocumentSnapshot document : task.getResult()) {

                nameOfFilm.add(document.get("nameOfFilm").toString());
                descriptionToFilm.add(document.get("descriptionToFilm").toString());
                photoUrl.add(document.get("imageUrl").toString());
                youTubeUrl.add(document.get("videoURL").toString());
                category.add(document.get("category").toString());
   myAdapter =  new MyAdapter(context, nameOfFilm, descriptionToFilm, 
   photoUrl, youTubeUrl, 
   rci, category);
                recyclerView.setAdapter(myAdapter);
                recyclerView.setLayoutManager(new LinearLayoutManager(context));


            }

        }
    });


}

here is screenshot with debuger, you can see that context = null

context = null

here you can see that i set layout for recyclerView with logcat

here is Adapter

package com.example.pocketcinema;

import android.content.Context;
import android.content.Intent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.TextView;

import androidx.annotation.NonNull;
import androidx.cardview.widget.CardView;
import androidx.recyclerview.widget.RecyclerView;

import com.squareup.picasso.Picasso;

import java.util.List;

public class MyAdapter extends 
RecyclerView.Adapter<MyAdapter.MyViewHolder> {

Context ct;
List<String> name, description, image, video, category;
private final RecyclerViewInterface recyclerViewInterface;

public MyAdapter(Context ct, List<String> nameOfFilm, List<String> 
descriptionOfFilm, List<String> imageUrl, List<String> videoUrl, 
RecyclerViewInterface rci,List<String> category) {
    name = nameOfFilm;
    description = descriptionOfFilm;
    image = imageUrl;
    video = videoUrl;
    this.ct = ct;
    recyclerViewInterface = rci;
    this.category = category;
}

@NonNull
@Override
public MyViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int 
viewType) {
    LayoutInflater inflater = LayoutInflater.from(ct);
    View view = inflater.inflate(R.layout.my_row, parent, false);

    return new MyViewHolder(view, recyclerViewInterface);
}

@Override
public void onBindViewHolder(@NonNull MyViewHolder holder, int 
position) {
    holder.nameFilm.setText(name.get(position));
    holder.cardView.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            Intent intent = new Intent(ct, PlayerActivity.class);

        }
    });
    Picasso.get().load(image.get(position)).into(holder.image2);

}

@Override
public int getItemCount() {
    return image.size();
}


public static class MyViewHolder extends RecyclerView.ViewHolder {
    TextView nameFilm;
    ImageView image2;
    CardView cardView;

    public MyViewHolder(@NonNull View itemView, RecyclerViewInterface 
 recyclerViewInterface) {
        super(itemView);
        nameFilm = itemView.findViewById(R.id.nameTV);
        image2 = itemView.findViewById(R.id.imageView2);
        cardView = itemView.findViewById(R.id.cardView);
        



 itemView.findViewById(R.id.sectionOFRecyclerView).setOnClickListener 
 (new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (recyclerViewInterface != null) {
                    int pos = getAdapterPosition();
                    if (pos != RecyclerView.NO_POSITION) {
                        recyclerViewInterface.onItemClick(pos);
                    }
                }
            }
        });

    }


}
}

myAdapter isn't null

CodePudding user response:

You are trying to create an instance of activity as global variable. That means the context has not been generated yet.

Basically you can just use requireContext() method of Fragment class. This will provide you the context.

As I have mentioned in comment, you need to update your onCreateView method as below:

@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { 
    return inflater.inflate(R.layout.fragment_search, container, false);
}

Then, you need to initialize your view and other stuff on onViewCreated method. You can update that method like this:

@Override
public void onViewCreated(@NonNull View view, @Nullable Bundle savedInstanceState) {
    super.onViewCreated(view, savedInstanceState);
    recyclerView = view.findViewById(R.id.filmsList);
    textView = view.findViewById(R.id.test);
    
    rci = this;
    nameOfFilm = new ArrayList<>();
    youTubeUrl = new ArrayList<>();
    photoUrl = new ArrayList<>();
    descriptionToFilm = new ArrayList<>();
    category = new ArrayList<>();
    
    loadFilmsFromDB();
}

Notes

  • You don't have to send many string parameters to your adapter. It is better to create a Model class for that item, and send the list of that item. So, model classes will have all the data you need, and you can use them from that model. This will give you better coding style and will let you manage your data easier.
  • To communicate with your XML layout, you can use ViewBinding or DataBinding for that. This will also help you to use your view elements without creating variables for each of them.
  • Related