如何使用Android Studio在Firebase子级内部获取信息?

时间:2018-10-24 12:53:07

标签: android firebase firebase-realtime-database

通过参考下图。如果我想让一个模块列出所有事件信息,例如registerEventName,registerEventLocation ....,应该如何调用它?第二行是创建的事件人员ID的uuid,后跟事件ID。提前致谢。我想显示所有用户创建的事件列表的所有信息。请告诉我是否需要其他信息。

Image1

package com.example.jmham.eventuser;

import android.content.Intent;
import android.support.annotation.NonNull;
import android.support.design.widget.FloatingActionButton;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.Editable;
import android.text.TextWatcher;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;

import com.firebase.ui.database.FirebaseRecyclerOptions;
import com.bumptech.glide.Glide;
import com.example.jmham.eventuser.Model.ListInfo;
import com.firebase.ui.database.FirebaseRecyclerAdapter;
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.example.jmham.eventuser.ViewHolder.MenuViewHolder;
import com.firebase.ui.database.FirebaseRecyclerAdapter;
import com.google.firebase.database.DatabaseReference;
import com.google.firebase.database.FirebaseDatabase;
import com.google.firebase.database.Query;
import com.google.firebase.database.ValueEventListener;
import com.google.firebase.storage.FirebaseStorage;
import com.google.firebase.storage.StorageReference;
import com.mancj.materialsearchbar.MaterialSearchBar;
import com.example.jmham.eventuser.Model.User;
import java.util.ArrayList;
import java.util.List;

public class List_Of_Event extends AppCompatActivity {


    FirebaseDatabase database;
    DatabaseReference eventinfo;

    RecyclerView recycle_menu;
    RecyclerView.LayoutManager layoutManager;

    FirebaseStorage storage;
    StorageReference storageRef;
    EditText search_edit_text;
    FloatingActionButton search_item;
    ArrayList<String> fullNameList;
    ArrayList<String> profilePicList;
    ArrayList<String> contectNumber;
    ArrayList<String> EventId;
    ArrayList<String> EventLocation;
    ArrayList<String> EventName;
    ArrayList<String> EventRadiogroup;
    ArrayList<String> EventStartDate;

    //Search functionality
    FirebaseRecyclerAdapter<ListInfo,MenuViewHolder> searchAdapter;
    List<String> suggestList =  new ArrayList<>();
    MaterialSearchBar materialSearchBar;
    FirebaseRecyclerAdapter <ListInfo, MenuViewHolder> adapter;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_list_of_event);

        storage = FirebaseStorage.getInstance();
        storageRef = storage.getReference();

        //search_edit_text = (MaterialSearchBar) findViewById(R.id.search_edit_text);

        search_edit_text = (EditText) findViewById(R.id.search_edit_text);

        /*
        *    ArrayList<String> fullNameList;
    ArrayList<String> profilePicList;
    ArrayList<String> contectNumber;
    ArrayList<String> EventId;
    ArrayList<String> EventLocation;
    ArrayList<String> EventName;
    ArrayList<String> EventRadiogroup;
    ArrayList<String> EventStartDate;   * */
        fullNameList = new ArrayList<>();
        profilePicList = new ArrayList<>();
        contectNumber = new ArrayList<>();
        EventId = new ArrayList<>();
        EventLocation = new ArrayList<>();
        EventName = new ArrayList<>();
        EventRadiogroup = new ArrayList<>();
        EventStartDate = new ArrayList<>();
/*
        search_item.setOnClickListener(new View.OnClickListener(){

            @Override
            public void onClick(View v) {
                Intent search_bar = new Intent(List_Of_Event.this, search_bar.class);
                startActivity(search_bar);
                finish();
            }
        });  */




/*
        search_edit_text.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {

            }

            @Override
            public void afterTextChanged(Editable s) {
              if (!s.toString().isEmpty()){
                  setAdapter(s.toString());
              }
            }
        });
*/




        recycle_menu = (RecyclerView) findViewById(R.id.recycle_menu);
        recycle_menu.setHasFixedSize(true);
        layoutManager = new LinearLayoutManager(this);

        recycle_menu.setLayoutManager(layoutManager);
        database  = FirebaseDatabase.getInstance();
       // eventinfo = database.getReference("ListOfEvent");
        System.out.println();
        loadMenu();
        eventinfo = FirebaseDatabase.getInstance().getReference();
        DatabaseReference ref2,ref3,ref4;
        ref2 = eventinfo.child("ListOfEvent");
        ref3 = ref2.child("ListOfEvent").child();
//DatabaseReference ref = FirebaseDatabase.getInstance().getReference().child("ChatRoom").child(str);
       ref2.addListenerForSingleValueEvent(new ValueEventListener() {
           @Override
           public void onDataChange(@NonNull DataSnapshot dataSnapshot) {


               // Result will be holded Here
               for (DataSnapshot dsp : dataSnapshot.getChildren()) {
                   EventName.add(String.valueOf(dsp.getValue())); //add result into array list

             //      Toast.makeText(List_Of_Event.this, EventName, Toast.LENGTH_SHORT).show();
           }

           }

           @Override
           public void onCancelled(@NonNull DatabaseError databaseError) {

           }
       });
        //System.out.println(eventinfo.child("ListOfEvent").child(RegisterEventId).child("profileImageUr").toString());

        //Search

        materialSearchBar = (MaterialSearchBar)findViewById(R.id.searchBar);
        materialSearchBar.setHint("Enter your Event");
        //materialSearchBar.setSpeechMode(false); No need, becuz we already define it at XML

        // loadSuggest();  //Write function to load Sugggest from Firebase
        // setAdapter();
        materialSearchBar.setLastSuggestions(suggestList);

        materialSearchBar.addTextChangeListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {
                // When user type theri text, we wil change list
                List<String> suggest = new ArrayList<String>();
                for (String search:suggest){
                    if(search.toLowerCase().contains(materialSearchBar.getText().toLowerCase()))
                        suggest.add(search);
                }
                materialSearchBar.setLastSuggestions(suggest);
            }

            @Override
            public void afterTextChanged(Editable s) {

            }
        });

        materialSearchBar.setOnSearchActionListener(new MaterialSearchBar.OnSearchActionListener() {
            @Override
            public void onSearchStateChanged(boolean enabled) {
                //When Search Bar is close
                //Restore original adapter

                // if(! enabled) recycle_menu.setAdapter(adapter);
            }

            @Override
            public void onSearchConfirmed(CharSequence text) {
                // When search finish
                //Show result of search adapter
                //   startSearch(text);
            }

            @Override
            public void onButtonClicked(int buttonCode) {

            }
        });

        //  setAdapter(s.toString());
    }
    /*
        private void startSearch(CharSequence text) {
            searchAdapter = new FirebaseRecyclerAdapter<ListInfo, MenuViewHolder>(
                    ListInfo.class;
                    R.layout.activity_list_of_event,
            MenuViewHolder.class,ListInfo.("registerEventName")



            ) {
                @Override
                protected void populateViewHolder(MenuViewHolder viewHolder, ListInfo model, int position) {

                }
            };
        }
    */
    /*  private void loadSuggest(){
          storageRef.orderByChild("registerEventName".equals()).addValueListener(new ValueEventListener()
                                                                {

                                                                }
          );

      } */
    private void loadSuggest(){




        eventinfo.child("ListInfo").addListenerForSingleValueEvent(new ValueEventListener(){


            @Override
            public void onDataChange(@NonNull DataSnapshot dataSnapshot) {
                for(DataSnapshot postSnapshot:dataSnapshot.getChildren())
                {
                    ListInfo item = postSnapshot.getValue(ListInfo.class);
                    suggestList.add(item.getRegisterEventName()); // add name of food to suggest list

                }

            }

            @Override
            public void onCancelled(@NonNull DatabaseError databaseError) {

            }
        });
    }

    public void loadMenu(){

        Query query = eventinfo.orderByKey();
        FirebaseRecyclerOptions<ListInfo> firebaseRecyclerOptions =
                new FirebaseRecyclerOptions.Builder<ListInfo>()
                        .setQuery(query, ListInfo.class)
                        .build();

        adapter = new FirebaseRecyclerAdapter<ListInfo, MenuViewHolder>(firebaseRecyclerOptions) {


            @NonNull
            @Override
            public MenuViewHolder onCreateViewHolder(@NonNull ViewGroup viewGroup, int i) {
                View view = LayoutInflater.from(viewGroup.getContext()).inflate(R.layout.activity_list,viewGroup,false);
                return new MenuViewHolder(view);
            }

            @Override
            protected void onBindViewHolder(@NonNull MenuViewHolder holder, int position, @NonNull ListInfo model) {
                System.out.println("test ::"+model.getImageToUpload());

                holder.txtRegisterEventStartDate.setText(model.getRegisterEventStartDate());
                holder.txtRegisterEventName.setText(model.getRegisterEventName());
                holder.txtContact_number.setText(model.getRegisterContactNumber());
                holder.txtRegisterEventRadiogroup.setText(model.getRegisterEventRadiogroup());
                holder.txtRegisterEventLocation.setText(model.getRegisterEventLocation());
//               model = storageReference.child("profileImageUrl").child(fileName)
                System.out.println("test ::"+model.getImageToUpload());
                Glide.with(getBaseContext()).load(model.getImageToUpload()
                ).into(holder.imageView);
                System.out.println(model.getRegisterEventName());
                System.out.println(model.getImageToUpload());
//                String URL = FirebaseDatabase.getInstance().getReference().child(model.getRegisterEventId()).child("profileImageUrl");
//                System.out.println("TESTURL: "+URL);

//                Glide.with(getApplicationContext())
//                        .load(URL)
//                        .into(viewHolder.imageView);

                System.out.println(model.getRegisterEventName());
                System.out.println("Highlight" + model.getImageToUpload());

                final ListInfo clickItem = model;
            }


        };
        recycle_menu.setAdapter(adapter);
    }




    @Override
    protected void onStart() {
        super.onStart();
        adapter.startListening();
    }
    @Override
    protected void onStop() {
        super.onStop();
        adapter.stopListening();
    }


//---

}
//search_item

2 个答案:

答案 0 :(得分:0)

希望这对您有所帮助。

databaseRef.child("ListOfEvent").addListenerForSingleValueEvent(new ValueEventListener() {
        @Override
        public void onDataChange(DataSnapshot dataSnapshot) {

            for (DataSnapshot userIdSnapshot : dataSnapshot.getChildren()) {

                for (DataSnapshot snapshot : userIdSnapshot.getChildren()) {

                    String regEventName = snapshot.child("registerEventName").getValue().toString();
                    String regEventLoc = snapshot.child("registerEventLocation").getValue().toString();

                }
            }
        }

        @Override
        public void onCancelled(DatabaseError databaseError) {

        }
    });

答案 1 :(得分:0)

尝试一下

String currentUser = FirebaseAuth.getInstance().getCurrentUser().getUid();
databaseRef.child("ListOfEvent").child(currentUser).addListenerForSingleValueEvent(new ValueEventListener() {
    @Override
    public void onDataChange(DataSnapshot dataSnapshot) {
        for (DataSnapshot objSnapshot: dataSnapshot.getChildren()) {
        String key = objSnapshot.getKey();
                    Toast.makeText(Chat.this, key, Toast.LENGTH_SHORT).show();

           }
     }

    @Override
    public void onCancelled(DatabaseError databaseError) {

     }
 });

希望它能提供全部帮助。