Firebase数据库与片段中的回收者视图

时间:2016-12-19 14:00:25

标签: android android-fragments firebase android-recyclerview firebase-realtime-database

我在这里遇到代码问题,recyclerview没有显示任何数据。 这是我的片段类

public class Fragment extends android.support.v4.app.Fragment {
String title, url;
RecyclerView recyclerView;
int ARG_SECTION_NUMBER;
AdapterContact adapterContact;
AlertDialog.Builder dialogBuilder;
AlertDialog b;
Context context;
EditText edt1,edt2,edt3,edt4;
FloatingActionButton floatingActionButton;
    static String DB_URL = "https://banda-virasat-6812b.firebaseio.com/";
int status = 0;
ArrayList<Contact> contacts = new ArrayList<>();
private DatabaseReference databaseReference;
FirebaseDatabase mFirebaseDatabase;
Firebase firebase;

public Fragment() {
}


public static Fragment newInstance(String title, String DB_URL){
    Fragment fragment1 = new Fragment();
    Bundle args = new Bundle();
    args.putString("title", title);
    fragment1.setArguments(args);



    //args.putParcelableArrayList("contact", contacts);
    //fragment1.setArguments(args);
    return fragment1;
}



@Override
public void onCreate(@Nullable Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);

    //contacts = getArguments().getParcelableArrayList("contact");
    mFirebaseDatabase = FirebaseDatabase.getInstance();
    DB_URL = String.valueOf(mFirebaseDatabase.getReference().child("Contact"));

}


public void saveOnline(String contactProfession, String contactName, String contactAddress, int contactNumber, int contactStatus){
    Contact contact = new Contact();
    contact.setContactProfession(contactProfession);
    contact.setContactName(contactName);
    contact.setContactAddress(contactAddress);
    contact.setContactNumber(contactNumber);
    contact.setContactStatus(contactStatus);

    firebase.child("Contact").push().setValue(contact);

}


public void refreshData(){
    firebase.addChildEventListener(new ChildEventListener() {
        @Override
        public void onChildAdded(DataSnapshot dataSnapshot, String s) {
            getUpdates(dataSnapshot);
        }

        @Override
        public void onChildChanged(DataSnapshot dataSnapshot, String s) {
            getUpdates(dataSnapshot);
        }

        @Override
        public void onChildRemoved(DataSnapshot dataSnapshot) {

        }

        @Override
        public void onChildMoved(DataSnapshot dataSnapshot, String s) {


        }

        @Override
        public void onCancelled(FirebaseError firebaseError) {
            Log.w(TAG, "Failed to read value.", firebaseError.toException());

        }
    });
}

private void getUpdates(DataSnapshot dataSnapshot) {
    contacts.clear();
    for (DataSnapshot dataSnapshot1 : dataSnapshot.getChildren()) {
        Contact contact = new Contact();
        contact.setContactProfession(dataSnapshot1.getValue(Contact.class).getContactProfession());
        contact.setContactName(dataSnapshot1.getValue(Contact.class).getContactName());
        contact.setContactAddress(dataSnapshot1.getValue(Contact.class).getContactAddress());
        contact.setContactNumber(dataSnapshot1.getValue(Contact.class).getContactNumber());
        contact.setContactStatus(dataSnapshot1.getValue(Contact.class).getContactStatus());
        contacts.add(contact);

    }
    System.out.println(contacts.size());
}
@Nullable
@Override
public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
    View view = inflater.inflate(R.layout.fragment_main, container, false);
    title = getArguments().getString("title");
    databaseReference = FirebaseDatabase.getInstance().getReference();
    floatingActionButton = (FloatingActionButton)view.findViewById(R.id.fab);
    floatingActionButton.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            dialogBuilder = new AlertDialog.Builder(getContext());
            final View dialogView = LayoutInflater.from(getContext()).inflate(R.layout.dialog_contact, null);
            edt1 = (EditText) dialogView.findViewById(R.id.edit1);
            edt2 = (EditText) dialogView.findViewById(R.id.edit2);
            edt3 = (EditText) dialogView.findViewById(R.id.edit3);
            edt4 = (EditText) dialogView.findViewById(R.id.edit4);
            dialogBuilder.setTitle("Add Contact");
            dialogBuilder.setOnDismissListener(null);
            dialogBuilder.setIcon(R.drawable.contact_not_selected);
            dialogBuilder.setMessage("Note: Contacts will only show if approved by admin");

            dialogBuilder.setPositiveButton("Add", new DialogInterface.OnClickListener() {
                public void onClick(DialogInterface dialog, int whichButton) {
                    //do something with edt.getText().toString();
                    if(edt1.length() != 0  && edt2.length() !=0 && edt3.length() != 0 && edt4.length() != 0){
                        System.out.println(edt1.getText().toString());
                        saveOnline(edt1.getText().toString(),edt2.getText().toString(),edt3.getText().toString(), status, status);
                        edt1.setText("");
                        edt2.setText("");
                        edt3.setText("");
                        edt4.setText("");
                        Toast.makeText(getContext(),"Your request has been submitted, pending for approval", 1).show();
                    }
                    else{
                        Toast.makeText(getContext(),"Fill all fields", 1).show();
                    }

                }
            });
            dialogBuilder.setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
                public void onClick(DialogInterface dialog, int whichButton) {
                    //pass
                }
            });
            dialogBuilder.setView(dialogView);
            b = dialogBuilder.create();
            b.show();


        }
    });

    //dummy = (TextView) view.findViewById(R.id.dummy);
    //dummy.setText(title);
    recyclerView = (RecyclerView)view.findViewById(R.id.recycler);
    recyclerView.setHasFixedSize(true);
    context = getContext();
    if (getArguments() != null && getArguments().containsKey("title")) {
        if(title.equalsIgnoreCase("contact")) {
            adapterContact = new AdapterContact(context,contacts);
            recyclerView.setAdapter(adapterContact);
        }
        else if (title.equalsIgnoreCase("news")) {
            AdapterNews adapter2 = new AdapterNews(new String[]{"Monkey", "Lion", "Tiger", "Chimp", "Cat", "Cat", "Dog"});
            recyclerView.setAdapter(adapter2);
        }
        else if (title.equalsIgnoreCase("travel")) {
            AdapterTravel adapter3 = new AdapterTravel(new String[]{"", ""});
            recyclerView.setAdapter(adapter3);
        }



        LinearLayoutManager llm = new LinearLayoutManager(getActivity());
        recyclerView.setLayoutManager(llm);
        return view;
    }



/*@Override
public void onStart() {
    super.onStart();
    if(adapterContact  == null){
        //TODO make network call
    }
    else{
        //recyclerView.setAdapter(adapterContact);
    }*/
    return view;
}

@Override
public void onStart() {
    super.onStart();
    Firebase.setAndroidContext(getContext());
    firebase = new Firebase(DB_URL);

    if(contacts != null){

    }
    else {
        refreshData();
    }
    if(title.equalsIgnoreCase("contact")){
        floatingActionButton.setVisibility(View.VISIBLE);
    }
    else {
        floatingActionButton.setVisibility(View.GONE);
    }

}
}

这是我的适配器

public class AdapterContact extends RecyclerView.Adapter<AdapterContact.MyViewHolder> {
Context context;
ArrayList<Contact> contacts;



public static class MyViewHolder extends RecyclerView.ViewHolder {
    public CardView mCardView1;
    public TextView mTextView1,mTextView2,mTextView3,mTextView4;
    public MyViewHolder(View v) {
        super(v);
        mCardView1 = (CardView) v.findViewById(R.layout.item_contact);
        mTextView1 = (TextView) v.findViewById(R.id.contact_profession);
        mTextView2 = (TextView) v.findViewById(R.id.contact_name);
        mTextView3 = (TextView) v.findViewById(R.id.contact_address);
        mTextView4 = (TextView) v.findViewById(R.id.contact_number);
    }
}
public AdapterContact(Context context,ArrayList<Contact> contacts) {
    this.contacts = contacts;
    this.context = context;

}
@Override
public AdapterContact.MyViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
    View v = LayoutInflater.from(parent.getContext())
            .inflate(R.layout.item_contact, parent, false);
    // set the view's size, margins, paddings and layout parameters
    return new MyViewHolder(v);
}

@Override
public void onBindViewHolder(MyViewHolder holder, int position) {

    holder.mTextView1.setText(contacts.get(position).getContactProfession());
    holder.mTextView2.setText(contacts.get(position).getContactName());
    holder.mTextView3.setText(contacts.get(position).getContactAddress());
    holder.mTextView4.setText(contacts.get(position).getContactNumber());
    int x = contacts.get(position).getContactStatus();

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

这是我的Model类 Contact.java

public class Contact {
private String contactProfession, contactName, contactAddress;
private int contactNumber, contactStatus;

public Contact(){
}

public String getContactProfession(){
    return contactProfession;
}
public void setContactProfession(String contactProfession){
    this.contactProfession = contactProfession;
}


public String getContactName(){
    return contactName;
}
public void setContactName(String contactName){
    this.contactName = contactName;
}


public String getContactAddress(){
    return contactAddress;
}
public void setContactAddress(String contactAddress){
    this.contactAddress = contactAddress;
}


public int getContactNumber(){
    return contactNumber;
}
public void setContactNumber(int contactNumber){
    this.contactNumber = contactNumber;
}


public int getContactStatus(){
    return contactStatus;
}
public void setContactStatus(int contactStatus){
    this.contactStatus = contactStatus;
}


}

我已经实现了所有依赖关系&amp;许可(互联网)。 Recyclerview没有填充。

2 个答案:

答案 0 :(得分:0)

仅仅为了遗产,我会发布答案:

每当您更改必须由ListViewReciclerView显示的数据时,您都不会使用适配器提供的方法,例如add/remove您&#39 ; ll必须通知适配器数据已更改。

因此,问题在于AdapterContact并不知道有新数据,因此需要调用notifyDataSetChanged

答案 1 :(得分:0)

在初始时不要通过联系人列表。适配器删除联系人列表参数,如下所示。

public AdapterContact(Context context) {
      this.context = context;
}

现在在联系人适配器中创建一个setter方法,如下所示,并传递您的联系人列表以在recyclerview中设置。

public void setContactsList (ArrayList<Contact> contacts) {
      this.contacts = contacts;
      notifyDataSetChanged();  //never forget to do this
}

现在只要从firebase获取数据,就可以通过联系人列表。

private void getUpdates(DataSnapshot dataSnapshot) {
    contacts.clear();
    for (DataSnapshot dataSnapshot1 : dataSnapshot.getChildren()) {
        Contact contact = new Contact();
        contact.setContactProfession(dataSnapshot1.getValue(Contact.class).getContactProfession());
        contact.setContactName(dataSnapshot1.getValue(Contact.class).getContactName());
        contact.setContactAddress(dataSnapshot1.getValue(Contact.class).getContactAddress());
        contact.setContactNumber(dataSnapshot1.getValue(Contact.class).getContactNumber());
        contact.setContactStatus(dataSnapshot1.getValue(Contact.class).getContactStatus());
        contacts.add(contact);

    }
    System.out.println(contacts.size());

    //pass your contact list here
    adapterContact.setContactList(contacts);
}