I made my DataFakeGenerator
to create some fake data to test my Recycelerview
, but when i want to use it in one of my Fragments i have an error.
My error is in this line:
PostAdapter postAdapter = new PostAdapter(DataFakeGenerator.getData(this));
it says that i can not use this
, so what statement can i use in this parentheses?
Here is my Fragment :
public class Frag_joke extends Fragment {
public static Fragment instance(){
Fragment fragment = new Frag_joke();
return fragment;
}
@Nullable
@Override
public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
ViewGroup layout = (ViewGroup)inflater.inflate(R.layout.frag_joke,null);
RecyclerView recyclerView = (RecyclerView)layout.findViewById(R.id.recycler_view);
PostAdapter postAdapter = new PostAdapter(DataFakeGenerator.getData(this));
recyclerView.setLayoutManager(new LinearLayoutManager(this.getActivity()));
recyclerView.setAdapter(postAdapter);
return layout;
}
@Override
public void onActivityCreated(@Nullable Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
}
}
Here is my DataFakeGenerator :
public class DataFakeGenerator {
public static List<Post> getData(){
List<Post> posts= new ArrayList<>();
for(int i=0;i<=6;i++){
Post post= new Post();
post.setId(i);
post.setContent("sample text");
posts.add(post);
}
return posts;
}
}
And here is my PostAdapter:
public class PostAdapter extends RecyclerView.Adapter<PostAdapter.PostViewHolder>{
private Context context;
private List<Post> posts;
public PostAdapter(Context context, List<Post>posts){
this.context = context;
this.posts = posts;
}
@Override
public PostViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View view = LayoutInflater.from(context).inflate(R.layout.layout_post,parent,false);
return new PostViewHolder(view);
}
@Override
public void onBindViewHolder(PostViewHolder holder, int position) {
Post post=posts.get(position);
holder.content.setText(post.getContent());
}
@Override
public int getItemCount() {
return posts.size();
}
public class PostViewHolder extends RecyclerView.ViewHolder{
private TextView content;
public PostViewHolder(View itemView) {
super(itemView);
content=(TextView)itemView.findViewById(R.id.post_content);
}
}
}
You are probably confused with your implementation. DataFakeGenerator.getData()
does not need any parameter. It's your adapter constructor that has 2.
To create your adapter you can use the following instead:
PostAdapter postAdapter = new PostAdapter(getContext(), DataFakeGenerator.getData());
PS: this
wouldn't work with the adapter creation (if that's the code you are actually trying to use), as the Fragment
is not a context (but the Activity is, which is why you can access it with getContext()
from the fragment