calling view in a new method from onCreateview in android studio - java

im trying to call "view" from my inflater in my new method but it won't work, it says unresolved. if i move the whole code under setUpRecyclerView into onCreateView it works. is there a way to make it work as it is so i can keep my onCreatView tidy? all the code is in a Fragment. i alsi tried using getView.findViewById but that also didnt work.
'''
package com.example.hostapp;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.fragment.app.Fragment;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import com.firebase.ui.firestore.FirestoreRecyclerOptions;
import com.google.firebase.firestore.CollectionReference;
import com.google.firebase.firestore.FirebaseFirestore;
import com.google.firebase.firestore.Query;
public class HomeFragment extends Fragment {
private FirebaseFirestore db = FirebaseFirestore.getInstance();
private CollectionReference categoryref = db.collection("categories");
private categoryCardAdapter adapter;
#Nullable
#Override
public View onCreateView(#NonNull LayoutInflater inflater, #Nullable ViewGroup container, #Nullable Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_home, container, false);
return view;
}
public void setUpRecyclerView (){
Query query = categoryref.orderBy("name",Query.Direction.DESCENDING);
FirestoreRecyclerOptions<categoryCard> options = new FirestoreRecyclerOptions.Builder<categoryCard>()
.setQuery(query, categoryCard.class)
.build();
adapter = new categoryCardAdapter(options);
RecyclerView recyclerView = (RecyclerView) view.findViewById(R.id.recycler_category);
recyclerView.setHasFixedSize(true);
recyclerView.setLayoutManager(new LinearLayoutManager(this.getActivity()));
recyclerView.setAdapter(adapter);
}
#Override
public void onStart() {
super.onStart();
adapter.startListening();
}
#Override
public void onStop() {
super.onStop();
adapter.stopListening();
}
}
'''
this is the code that works:
package com.example.hostapp;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.fragment.app.Fragment;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import com.firebase.ui.firestore.FirestoreRecyclerOptions;
import com.google.firebase.firestore.CollectionReference;
import com.google.firebase.firestore.FirebaseFirestore;
import com.google.firebase.firestore.Query;
public class HomeFragment extends Fragment {
private FirebaseFirestore db = FirebaseFirestore.getInstance();
private CollectionReference categoryref = db.collection("categories");
private categoryCardAdapter adapter;
#Nullable
#Override
public View onCreateView(#NonNull LayoutInflater inflater, #Nullable ViewGroup container, #Nullable Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_home, container, false);
Query query = categoryref.orderBy("name",Query.Direction.DESCENDING);
FirestoreRecyclerOptions<categoryCard> options = new FirestoreRecyclerOptions.Builder<categoryCard>()
.setQuery(query, categoryCard.class)
.build();
adapter = new categoryCardAdapter(options);
**RecyclerView recyclerView = (RecyclerView) view.findViewById(R.id.recycler_category);**
recyclerView.setHasFixedSize(true);
recyclerView.setLayoutManager(new LinearLayoutManager(this.getActivity()));
recyclerView.setAdapter(adapter);
return view;
}
public void setUpRecyclerView (){
}
#Override
public void onStart() {
super.onStart();
adapter.startListening();
}
#Override
public void onStop() {
super.onStop();
adapter.stopListening();
}
}

You are not calling the setupRecyclerView() method in your first code sample. You can either call it from your createView() method before returning the view or you can call the method from onViewCreated() method. I would prefer the second option.

Related

Items from Room DB dont show up when using submitList to ListAdapter to RecyclerView in a Fragment

So this is my code for the fragment:
import android.content.Context;
import android.content.Intent;
import android.content.pm.LauncherActivityInfo;
import android.os.Bundle;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.TextView;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.fragment.app.Fragment;
import androidx.lifecycle.ViewModelProvider;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
public class Frag1 extends Fragment {
CustomViewModel viewModel;
#Override
public void onCreate(#Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
}
#Nullable
#Override
public View onCreateView(#NonNull LayoutInflater inflater, #Nullable ViewGroup container, #Nullable Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.frag1_layout, container, false);
viewModel = new ViewModelProvider(this).get(CustomViewModel.class);
RecyclerView recyclerView = rootView.findViewById(R.id.rv1);
final Adapter adapter = new Adapter(new Adapter.Diff());
recyclerView.setAdapter(adapter);
recyclerView.setLayoutManager(new LinearLayoutManager(getActivity()));
viewModel.show().observe(getViewLifecycleOwner(), rEnts -> {
adapter.submitList(rEnts);
Log.d("ItemCount", String.valueOf(adapter.getItemCount()));
});
Log.d("ItemCountOUTSIDE", String.valueOf(adapter.getItemCount()));
return rootView;
}
when I run the app the recycler view is empty, in the logs the "ItemCountOUTSIDE" shows 0 and is written earlier the "ItemCount" which shows 2. RoomDB is capable of showing the 2 items that are in it when the app is run, so i'd imagine its not a problem with the ViewModel. I was able to output the objects in the DB on a TextView using the same observer function and also using the ViewModel. I understand that apparently observer runs in separate thread and that is executed later but I dont know how to fix that since I know concurrency only on a surface level. Also when doing my research this pattern that I'm using seems to be working for others, hence my frustration.
Additional Code for the Adapter and ViewHolder:
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;
import androidx.annotation.NonNull;
import androidx.recyclerview.widget.RecyclerView;
import org.w3c.dom.Text;
public class Holder extends RecyclerView.ViewHolder {
private final TextView textView;
private Holder(#NonNull View itemView) {
super(itemView);
textView = itemView.findViewById(R.id.textName);
}
public void bind(rEnt E){
textView.setText(E.rN);
}
static Holder create(ViewGroup parent){
View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.rv1_item, parent, false);
return new Holder(view);
}
}
and
import android.util.Log;
import android.view.ViewGroup;
import androidx.annotation.NonNull;
import androidx.recyclerview.widget.DiffUtil;
import androidx.recyclerview.widget.ListAdapter;
import androidx.recyclerview.widget.RecyclerView;
import androidx.room.Query;
import java.util.List;
public class Adapter extends ListAdapter<rEnt, Holder> {
List<rEnt> myList = getCurrentList();
public Adapter(#NonNull DiffUtil.ItemCallback<rEnt> diffCB){
super(diffCB);
}
#NonNull
#Override
public Holder onCreateViewHolder(#NonNull ViewGroup parent, int viewType) {
return Holder.create(parent);
}
#Override
public void onBindViewHolder(#NonNull Holder holder, int position) {
rEnt currentEnt = getItem(position);
holder.bind(currentEnt);
}
static class Diff extends DiffUtil.ItemCallback<rEnt>{ //fuck is this as well???
#Override
public boolean areItemsTheSame(#NonNull rEnt oldItem, #NonNull rEnt newItem) {
return oldItem.getId() == newItem.getId();
}
#Override
public boolean areContentsTheSame(#NonNull rEnt oldItem, #NonNull rEnt newItem) {
return oldItem.rN.equals(newItem.rN);
}
}
}

SetAdapter cannot be applied as the adapter of FirestoreRecyclerviewAdapter

I am working on a chat app with firebase and I want to fitch the user information to the recyclerview...my code is correct by when I set the adapter to the recycler view its show an error.
Here is my code:
package com.abdelatif.chatapp;
import android.graphics.Color;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.fragment.app.Fragment;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import androidx.recyclerview.widget.RecyclerView.ViewHolder;
import com.firebase.ui.firestore.FirestoreRecyclerAdapter;
import com.firebase.ui.firestore.FirestoreRecyclerOptions;
import com.google.firebase.auth.FirebaseAuth;
import com.google.firebase.firestore.FirebaseFirestore;
import com.google.firebase.firestore.Query;
import com.squareup.picasso.Picasso;
public class ChatFragment extends Fragment {
private FirebaseFirestore firebaseFirestore;
LinearLayoutManager linearLayoutManager;
private FirebaseAuth firebaseAuth;
ImageView mimageviewofuser;
FirestoreRecyclerAdapter<FireBaseModel, NoteViewHolder> chatAdapter = null;
RecyclerView mrecyclerview;
#Nullable
#Override
public View onCreateView(#NonNull LayoutInflater inflater, #Nullable ViewGroup container, #Nullable Bundle savedInstanceState) {
View v=inflater.inflate(R.layout.chatfragment,container,false);
firebaseAuth=FirebaseAuth.getInstance();
firebaseFirestore= FirebaseFirestore.getInstance();
mrecyclerview=v.findViewById(R.id.recyclerView);
// Query query=firebaseFirestore.collection("Users");
Query query=firebaseFirestore.collection("Users").whereNotEqualTo("uid",firebaseAuth.getUid());
FirestoreRecyclerOptions<FireBaseModel> allusername=new FirestoreRecyclerOptions.Builder<FireBaseModel>().setQuery(query,FireBaseModel.class).build();
chatAdapter=new FirestoreRecyclerAdapter<FireBaseModel, NoteViewHolder>(allusername) {
#Override
protected void onBindViewHolder(#NonNull NoteViewHolder noteViewHolder, int i, #NonNull FireBaseModel firebasemodel) {
noteViewHolder.particularusername.setText(firebasemodel.getName());
String uri=firebasemodel.getImage();
Picasso.get().load(uri).into(mimageviewofuser);
if(firebasemodel.getStatus().equals("Online"))
{
noteViewHolder.statusofuser.setText(firebasemodel.getStatus());
noteViewHolder.statusofuser.setTextColor(Color.GREEN);
}
else
{
noteViewHolder.statusofuser.setText(firebasemodel.getStatus());
}
noteViewHolder.itemView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Toast.makeText(getActivity(), "contactClicked", Toast.LENGTH_SHORT).show();
}
});
}
#NonNull
#Override
public NoteViewHolder onCreateViewHolder(#NonNull ViewGroup parent, int viewType) {
View view=LayoutInflater.from(parent.getContext()).inflate(R.layout.chat_view_layout,parent,false);
return new NoteViewHolder(view);
}
};
mrecyclerview.setHasFixedSize(true);
linearLayoutManager=new LinearLayoutManager(getContext());
linearLayoutManager.setOrientation(RecyclerView.VERTICAL);
mrecyclerview.setLayoutManager(linearLayoutManager);
mrecyclerview.setAdapter(chatAdapter);
chatAdapter.startListening();
return v;
}
public class NoteViewHolder extends android.support.v7.widget.RecyclerView.ViewHolder
{
private TextView particularusername;
private TextView statusofuser;
public NoteViewHolder(#NonNull View itemView) {
super(itemView);
particularusername=itemView.findViewById(R.id.nameOfUser);
statusofuser=itemView.findViewById(R.id.statusOfUser);
mimageviewofuser=itemView.findViewById(R.id.imageViewOfUser);
}
}
}
the error is in the line: mrecyclerview.setAdapter(chatAdapter);
and the error is:
'setAdapter(androidx.recyclerview.widget.RecyclerView.Adapter)' in 'androidx.recyclerview.widget.RecyclerView' cannot be applied to '(com.firebase.ui.firestore.FirestoreRecyclerAdapter<com.abdelatif.chatapp.FireBaseModel,com.abdelatif.chatapp.ChatFragment.NoteViewHolder>)'
I hope someone give me a solution...i searched many time but nothing.
Make sure you call chatAdapter.startListening(); before calling mrecyclerview.setAdapter(chatAdapter);

How to parse only specific data with parseSnapshot?

To put this simple, I have a table called Wishlist in Firebase Database which contains 2 different types of objects: attractions and sights.
Then, in my app I want to show in a fragment only those objects from Wishlist table which are sights. How could I achieve this? Right now, the code is as it follows: (obviously, it will crash if I put return null, but how else could I address this issue?)
package com.example.mytravelapp.Fragments;
import android.os.Bundle;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.fragment.app.Fragment;
import androidx.recyclerview.widget.GridLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import com.example.mytravelapp.Adapters.WishlistViewHolder;
import com.example.mytravelapp.Models.Sight;
import com.example.mytravelapp.Models.Wishlist;
import com.example.mytravelapp.R;
import com.firebase.ui.database.FirebaseRecyclerAdapter;
import com.firebase.ui.database.FirebaseRecyclerOptions;
import com.firebase.ui.database.SnapshotParser;
import com.google.firebase.auth.FirebaseAuth;
import com.google.firebase.auth.FirebaseUser;
import com.google.firebase.database.DataSnapshot;
import com.google.firebase.database.DatabaseReference;
import com.google.firebase.database.FirebaseDatabase;
import java.util.ArrayList;
import java.util.List;
/**
* A simple {#link Fragment} subclass.
*/
public class WishlistSightsFragment extends Fragment {
private RecyclerView wishlist;
private DatabaseReference query;
private FirebaseRecyclerAdapter adapter;
private FirebaseUser user;
public WishlistSightsFragment() {
// Required empty public constructor
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
return inflater.inflate(R.layout.fragment_wishlist_sights, container, false);
}
#Override
public void onViewCreated(#NonNull View view, #Nullable Bundle savedInstanceState) {
super.onViewCreated(view, savedInstanceState);
wishlist = view.findViewById(R.id.rvWishlistSights);
wishlist.setHasFixedSize(true);
user = FirebaseAuth.getInstance().getCurrentUser();
GridLayoutManager grid = new GridLayoutManager(getContext().getApplicationContext(), 1);
wishlist.setLayoutManager(grid);
fetch();
}
private void fetch(){
query = FirebaseDatabase.getInstance().getReference("wishlist").child(user.getUid());
FirebaseRecyclerOptions<Wishlist> options =
new FirebaseRecyclerOptions.Builder<Wishlist>()
.setQuery(query, new SnapshotParser<Wishlist>() {
#NonNull
#Override
public Wishlist parseSnapshot(#NonNull DataSnapshot snapshot) {
Wishlist attraction = new Wishlist(snapshot.child("idWishlist").getValue().toString(),
snapshot.child("idAttraction").getValue().toString(),
snapshot.child("name").getValue().toString(),
snapshot.child("description").getValue().toString(),
snapshot.child("image").getValue().toString(),
snapshot.child("type").getValue().toString());
if(attraction.getType().equals("sight")){
return attraction;
}
return null;
}
})
.build();
adapter = new FirebaseRecyclerAdapter<Wishlist, WishlistViewHolder>(options) {
#Override
public WishlistViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View view = LayoutInflater.from(parent.getContext())
.inflate(R.layout.wishlist_design, parent, false);
return new WishlistViewHolder(view);
}
#Override
protected void onBindViewHolder(final WishlistViewHolder holder, final int position, final Wishlist model) {
holder.setDetails(getActivity(), model.getName(), model.getDescription(), model.getIdAttraction(), model.getImage());
}
};
wishlist.setAdapter(adapter);
}
#Override
public void onStart() {
super.onStart();
adapter.startListening();
}
#Override
public void onStop() {
super.onStop();
adapter.stopListening();
}
}
I think this query is more useful for you.
query = FirebaseDatabase.getInstance().getReference("wishlist").child(user.getUid()).orderByChild("type").equalTo("sight");
FirebaseRecyclerOptions<Wishlist> options =
new FirebaseRecyclerOptions.Builder<Wishlist>()
.setQuery(query, Wishlist.class)
.build();
You can get the list of wish who have type sight.

Want to use a recycler view in a fragment. Created an adapter when I set the adapter it shows me error

I want to build an app by which I can generate bussiness card. So I use navigaion drawer. For navigating menus I use fragment class for each of the menus and corresponding XML layout. In one of the layout I want to show my card view inside recyclerview.
MycardFragment.java
(This is the fragment class where I want show recyclerview)
package com.example.look.np.fragments;
import android.content.Context;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ListAdapter;
import android.widget.TextView;
import com.example.look.np.R;
import com.example.look.np.models.Template;
import com.example.look.np.utils.FirebaseMethod;
import com.example.look.np.utils.RecyclerviewAdapter;
import com.google.firebase.database.DataSnapshot;
import com.google.firebase.database.DatabaseError;
import com.google.firebase.database.DatabaseReference;
import com.google.firebase.database.FirebaseDatabase;
import com.google.firebase.database.ValueEventListener;
import java.util.ArrayList;
import java.util.List;
public class MyCardFragment extends Fragment {
private static final String TAG = "MyCardFragment";
private Context mContext;
private RecyclerView recyclerView;
FirebaseDatabase database;
DatabaseReference myRef ;
List<Template> listdata;
public MyCardFragment() {
// Required empty public constructor
}
//i tried this section but it gimes me error
#Override
public void onAttach(Context context) {
super.onAttach(context);
mContext=context;
}
#Nullable
#Override
public View onCreateView(#NonNull LayoutInflater inflater, #Nullable ViewGroup container, #Nullable Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_mycards,container,false);
database = FirebaseDatabase.getInstance();
myRef = database.getReference("template");
// Initialize Template Model Class
Template template = new Template();
// ...
// Lookup the Recycler view in fragment layout
recyclerView = view.findViewById(R.id.recycler_view);
recyclerView.setHasFixedSize(true);
// Attach the adapter to the recyclerview to populate items
RecyclerviewAdapter adapter = new RecyclerviewAdapter(template,inflater.getContext());//>>>This is the error i'm facig
// Set layout manager to position the items
recyclerView.setLayoutManager(new LinearLayoutManager(getActivity()));
myRef.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot dataSnapshot) {
// This method is called once with the initial value and again
// whenever data at this location is updated.
listdata = new ArrayList<Template>();
for(DataSnapshot dataSnapshot1 :dataSnapshot.child("template").getChildren()){
Template value = dataSnapshot1.getValue(Template.class);
Template fire = new Template();
String name = value.getP_name();
String desig = value.getP_designation();
String email = value.getP_email();
String phone = value.getP_phone();
String address = value.getC_address();
String c_name = value.getC_name();
fire.setP_name(name);
fire.setP_designation(desig);
fire.setP_email(email);
fire.setP_phone(phone);
fire.setC_name(c_name);
fire.setC_address(address);
listdata.add(fire);
}
}
#Override
public void onCancelled(#NonNull DatabaseError databaseError) {
// Failed to read value
Log.w("Hello", "Failed to read value.", databaseError.toException());
}
});
return view;
}
#Override
public void onStart() {
super.onStart();
}
}
I aslo created an adapter for recycler view, when I want to set the adapter to the fragment class it shows error. It takes context and List. For context I add getActivity() bMycardFragment.java
(This is the fragment class where I want show recyclerview)
package com.example.look.np.fragments;
import android.content.Context;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ListAdapter;
import android.widget.TextView;
import com.example.look.np.R;
import com.example.look.np.models.Template;
import com.example.look.np.utils.FirebaseMethod;
import com.example.look.np.utils.RecyclerviewAdapter;
import com.google.firebase.database.DataSnapshot;
import com.google.firebase.database.DatabaseError;
import com.google.firebase.database.DatabaseReference;
import com.google.firebase.database.FirebaseDatabase;
import com.google.firebase.database.ValueEventListener;
import java.util.ArrayList;
import java.util.List;
public class MyCardFragment extends Fragment {
private static final String TAG = "MyCardFragment";
private Context mContext;
private RecyclerView recyclerView;
FirebaseDatabase database;
DatabaseReference myRef ;
List<Template> listdata;
public MyCardFragment() {
// Required empty public constructor
}
//i tried this section but it gimes me error
#Override
public void onAttach(Context context) {
super.onAttach(context);
mContext=context;
}
#Nullable
#Override
public View onCreateView(#NonNull LayoutInflater inflater, #Nullable ViewGroup container, #Nullable Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_mycards,container,false);
database = FirebaseDatabase.getInstance();
myRef = database.getReference("template");
// Initialize Template Model Class
Template template = new Template();
// ...
// Lookup the Recycler view in fragment layout
recyclerView = view.findViewById(R.id.recycler_view);
recyclerView.setHasFixedSize(true);
// Attach the adapter to the recyclerview to populate items
RecyclerviewAdapter adapter = new RecyclerviewAdapter(template,inflater.getContext());//>>>This is the error i'm facig
// Set layout manager to position the items
recyclerView.setLayoutManager(new LinearLayoutManager(getActivity()));
myRef.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot dataSnapshot) {
// This method is called once with the initial value and again
// whenever data at this location is updated.
listdata = new ArrayList<Template>();
for(DataSnapshot dataSnapshot1 :dataSnapshot.child("template").getChildren()){
Template value = dataSnapshot1.getValue(Template.class);
Template fire = new Template();
String name = value.getP_name();
String desig = value.getP_designation();
String email = value.getP_email();
String phone = value.getP_phone();
String address = value.getC_address();
String c_name = value.getC_name();
fire.setP_name(name);
fire.setP_designation(desig);
fire.setP_email(email);
fire.setP_phone(phone);
fire.setC_name(c_name);
fire.setC_address(address);
listdata.add(fire);
}
}
#Override
public void onCancelled(#NonNull DatabaseError databaseError) {
// Failed to read value
Log.w("Hello", "Failed to read value.", databaseError.toException());
}
});
return view;
}
#Override
public void onStart() {
super.onStart();
}
}
MycardFragment.java
(This is the fragment class where I want show recyclerview)
package com.example.look.np.fragments;
import android.content.Context;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ListAdapter;
import android.widget.TextView;
import com.example.look.np.R;
import com.example.look.np.models.Template;
import com.example.look.np.utils.FirebaseMethod;
import com.example.look.np.utils.RecyclerviewAdapter;
import com.google.firebase.database.DataSnapshot;
import com.google.firebase.database.DatabaseError;
import com.google.firebase.database.DatabaseReference;
import com.google.firebase.database.FirebaseDatabase;
import com.google.firebase.database.ValueEventListener;
import java.util.ArrayList;
import java.util.List;
public class MyCardFragment extends Fragment {
private static final String TAG = "MyCardFragment";
private Context mContext;
private RecyclerView recyclerView;
FirebaseDatabase database;
DatabaseReference myRef ;
List<Template> listdata;
public MyCardFragment() {
// Required empty public constructor
}
//i tried this section but it gimes me error
#Override
public void onAttach(Context context) {
super.onAttach(context);
mContext=context;
}
#Nullable
#Override
public View onCreateView(#NonNull LayoutInflater inflater, #Nullable ViewGroup container, #Nullable Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_mycards,container,false);
database = FirebaseDatabase.getInstance();
myRef = database.getReference("template");
// Initialize Template Model Class
Template template = new Template();
// ...
// Lookup the Recycler view in fragment layout
recyclerView = view.findViewById(R.id.recycler_view);
recyclerView.setHasFixedSize(true);
// Attach the adapter to the recyclerview to populate items
RecyclerviewAdapter adapter = new RecyclerviewAdapter(template,inflater.getContext());//>>>This is the error i'm facig
// Set layout manager to position the items
recyclerView.setLayoutManager(new LinearLayoutManager(getActivity()));
myRef.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot dataSnapshot) {
// This method is called once with the initial value and again
// whenever data at this location is updated.
listdata = new ArrayList<Template>();
for(DataSnapshot dataSnapshot1 :dataSnapshot.child("template").getChildren()){
Template value = dataSnapshot1.getValue(Template.class);
Template fire = new Template();
String name = value.getP_name();
String desig = value.getP_designation();
String email = value.getP_email();
String phone = value.getP_phone();
String address = value.getC_address();
String c_name = value.getC_name();
fire.setP_name(name);
fire.setP_designation(desig);
fire.setP_email(email);
fire.setP_phone(phone);
fire.setC_name(c_name);
fire.setC_address(address);
listdata.add(fire);
}
}
#Override
public void onCancelled(#NonNull DatabaseError databaseError) {
// Failed to read value
Log.w("Hello", "Failed to read value.", databaseError.toException());
}
});
return view;
}
#Override
public void onStart() {
super.onStart();
}
}
I have an adapter class which takes context and List of items. Now I want to set my adapter in a fragment by passing context (getActivity() and List but it shows me error
I tried getActivity() but it show me error
i also tried this
#Override
public void onAttach(Context context) {
super.onAttach(context);
mContext=context;
}
//This is adapter class for my Recyclerview
RecyclerAdater.java
package com.example.look.np.utils;
import android.content.Context;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;
import com.example.look.np.R;
import com.example.look.np.models.Template;
import java.util.List;
public class RecyclerviewAdapter extends RecyclerView.Adapter<RecyclerviewAdapter.MyHolder>{
// ... constructor and member variables
// Usually involves inflating a layout from XML and returning the holder
List<Template> listdata;
Context context;
public RecyclerviewAdapter(List<Template> listdata, Context context) {
this.listdata = listdata;
this.context = context;
}
#Override
public MyHolder onCreateViewHolder(ViewGroup parent, int viewType) {
// Inflate the custom layout
View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.cardview,parent,false);
// Return a new holder instance
MyHolder myHolder = new MyHolder(view);
return myHolder;
}
public void onBindViewHolder(MyHolder holder, int position) {
Template data = listdata.get(position);
holder.pname.setText(data.getP_name());
holder.pdesignation.setText(data.getP_designation());
holder.pemail.setText(data.getP_email());
holder.pphone.setText(data.getP_phone());
holder.cname.setText(data.getC_name());
holder.caddress.setText(data.getC_address());
}
#Override
public int getItemCount() {
//return listdata.size();
int arr = 0;
try{
if(listdata.size()==0){
arr = 0;
}
else{
arr=listdata.size();
}
}catch (Exception e){
e.printStackTrace();
}
return arr;
}
class MyHolder extends RecyclerView.ViewHolder{
// Your holder should contain a member variable
// for any view that will be set as you render a row
TextView pname,caddress,pemail,pdesignation,pphone,cname;
// We also create a constructor that accepts the entire item row
// and does the view lookups to find each subview
public MyHolder(View itemView) {
// Stores the itemView in a public final member variable that can be used
// to access the context from any ViewHolder instance.
super(itemView);
pname = (TextView) itemView.findViewById(R.id.txt_personName);
caddress = (TextView) itemView.findViewById(R.id.txt_address);
pemail = (TextView) itemView.findViewById(R.id.txt_email);
pdesignation = (TextView) itemView.findViewById(R.id.txt_designation);
pphone = (TextView) itemView.findViewById(R.id.txt_phone);
cname = (TextView) itemView.findViewById(R.id.txt_companyName);
}
}
}
Point to be noted, don't forget to set layoutManager to recyclerview and to set adapter.
LinearLayoutManager layoutManager = new LinearLayoutManager(getActivity());
layoutManager.setOrientation(LinearLayoutManager.VERTICAL
recyclerview.setLayoutManager(layoutManager);
recyclerview.setHasFixedSize(true);
recyclerviewAdapter adapter = new recyclerviewAdapterAdapter(listdata,getActivity());        
recyclerview.setAdapter(adapter);
Another thing to notice in your code is:
There is network call (Which run in background) in oncreateView(). Before it gives result, the return view; is getting called.
This means the view is not updated while on background job is going.
This can be resolved by calling separate method like setRecyclerView() from onCreateView() method. After getting result from background operation you can set your recyclerview as mentioned above.
Don't forget to call the adapter.notifydatasetchanged() method.

Why won't Fragment Transaction work?

I'm writing a simple program in which a two fragments and one activity is used. Both Fragments are displayed (one at a time) within the activity's Frame Layout. The first fragment is a listview that lists items from which the user can select, then the main activity should swap the first fragment with a detail fragment according to the item position determined by a listener within the first fragment. Trouble is, my program won't actually commence the swap. Here's the code for the activity:
package com.example.user.monkeys;
import android.os.Bundle;
import android.support.v4.app.FragmentActivity;
import android.support.v4.app.FragmentTransaction;
import android.util.Log;
public class ListActivity extends FragmentActivity implements
monkeyListFragment.OnMonkeySelectedListener {
#Override
public void onCreate(Bundle savedInstanceState) {
Log.i("Activity", "onCreate Pre-Fragment 1");
super.onCreate(savedInstanceState);
setContentView(R.layout.monkey_list_frame);
if (findViewById(R.id.fragment_container) != null) {
if (savedInstanceState != null) {
return;
}
monkeyListFragment monkeyList = new monkeyListFragment();
monkeyList.setArguments(getIntent().getExtras());
// Add the fragment to the container
getSupportFragmentManager().beginTransaction()
.add(R.id.fragment_container, monkeyList);
Log.i("Activity", "made it end onCreate");
}
}
#Override
public void onMonkeyItemSelected(int position) {
Log.i("From Activity", "onMonkeyItemSelected");
monkeyDetailsFragment newDetailFrag = new monkeyDetailsFragment();
Bundle args = new Bundle();
args.putInt("itemPosition", position);
newDetailFrag.setArguments(args);
FragmentTransaction transaction = getSupportFragmentManager().beginTransaction();
transaction.replace(R.id.fragment_container, newDetailFrag);
transaction.addToBackStack(null);
transaction.commit();
}
}
And the code for the listview fragment:
package com.example.user.monkeys;
import android.app.Activity;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.ListView;
public class monkeyListFragment extends Fragment{
OnMonkeySelectedListener monkeyCallBack;
private ListView monkeyLV;
private String[] monkeyStrings;
public interface OnMonkeySelectedListener {
public void onMonkeyItemSelected(int position);
}
#Nullable
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
Log.i("Fragment 1", "Made it to onCreateView");
View view = inflater.inflate(R.layout.list_fragment, container, false);
monkeyLV = (ListView) view.findViewById(R.id.monkeyListView);
monkeyStrings = getResources().getStringArray(R.array.monkey_data_list);
ArrayAdapter<String> objAdapter = new ArrayAdapter<String>(this.getActivity(), android.R.layout.simple_list_item_1, monkeyStrings);
monkeyLV.setAdapter(objAdapter);
AdapterView.OnItemClickListener monkeyListen = new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
Log.i("ListFragment-ClckLstnr", "Made it");
monkeyCallBack.onMonkeyItemSelected(position);
}
};
Log.i("Fragment 1", "Made it past OnItemClick Listener");
return view;
}
#Override
public void onAttach(Activity activity) {
super.onAttach(activity);
try {
monkeyCallBack = (OnMonkeySelectedListener) activity;
}
catch (ClassCastException e) {
throw new ClassCastException(activity.toString());
}
}
}
and finally the code for the detail fragment (this isn't fully fleshed out but it should still swap I believe).
package com.example.user.monkeys;
import android.app.Activity;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.ListView;
public class monkeyDetailsFragment extends Fragment {
ImageView monkeyPicture;
#Nullable
#Override
public View onCreateView(LayoutInflater inflater, #Nullable ViewGroup
container, #Nullable Bundle savedInstanceState) {
Log.i("From Detail Fragment", "Got here");
View view = inflater.inflate(R.layout.monkey_detail_fragment, container,
false);
return view;
}
}
I found your missing line of code for the listview fragment:
monkeyLV.setOnItemClickListener(monkeyListen)

Categories