在一个活动中将数据写入firebase实时数据库并在另一个活动中读取数据

时间:2017-07-27 03:23:48

标签: android firebase firebase-realtime-database

App的前提:CatalogActivity显示已输入并存储在Firebase实时数据库中的宠物列表。它有一个浮动操作按钮,通向EditorActivity,允许用户插入有关Pet的信息并将其添加到CatalogActivity中的列表。

问题:我可以在EditorActivity中将数据写入Firebase Realtime数据库,但是我无法将数据读入CatalogActivity中的适配器。由于我在EditorActivity的onCreate中定义并附加了我的childEventListener,因此当我第一次打开应用程序时,目录布局为空,直到我单击浮动操作按钮。 当我第一次打开应用程序时,我如何才能使所有数据显示在目录布局中?我正在考虑在CatalogActivity中实例化所有firebase变量,然后将它们设置为静态公共,以便EditorActivity可以在必要时使用它们。那会有用吗?

CatalogActivity

public class CatalogActivity extends AppCompatActivity {

    private ListView mPetListView;
    public static PetAdapter mPetAdapter;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_catalog);

        // Initialize reference to views
        mPetListView = (ListView) findViewById(R.id.list);
        View emptyView = findViewById(R.id.empty_view);
        mPetListView.setEmptyView(emptyView);

        // Initialize pet ListView and its adapter
        List<Pet> pets = new ArrayList<>();
        mPetAdapter = new PetAdapter(this, R.layout.list_item, pets);
        mPetListView.setAdapter(mPetAdapter);

        // Setup FAB to open EditorActivity
        FloatingActionButton fab = (FloatingActionButton) findViewById(R.id.fab);
        fab.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                Intent intent = new Intent(CatalogActivity.this, EditorActivity.class);
                startActivity(intent);
            }
        });
    }
...
}

EditorActivity

public class EditorActivity extends AppCompatActivity{

    // EditText fields to enter the pet's name, breed, weight, and gender
    private EditText mNameEditText;
    private EditText mBreedEditText;
    private EditText mWeightEditText;
    private Spinner mGenderSpinner;

    // Gender of the pet. The possible values are 0 for unknown, 1 for male, and 2 for female
    private int mGender = 0;

    ...

    private Pet mPet;

    // Firebase instance variables
    private FirebaseDatabase mFirebaseDatabase;
    private DatabaseReference mDatabaseReference;
    private ChildEventListener mChildEventListener;

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_editor);

        mFirebaseDatabase = FirebaseDatabase.getInstance();
        mDatabaseReference = mFirebaseDatabase.getReference().child("pets");

        ...

        // Find all relevant views that we will need to read user input from
        mNameEditText = (EditText) findViewById(R.id.edit_pet_name);
        mBreedEditText = (EditText) findViewById(R.id.edit_pet_breed);
        mWeightEditText = (EditText) findViewById(R.id.edit_pet_weight);
        mGenderSpinner = (Spinner) findViewById(R.id.spinner_gender);

        // Setup OnTouchListeners on all the input fields, so we can determine if the user
        // has touched or modified them. This will let us know if there are unsaved changes
        // or not, if the user tries to leave the editor without saving.
        mNameEditText.setOnTouchListener(mTouchListener);
        mBreedEditText.setOnTouchListener(mTouchListener);
        mWeightEditText.setOnTouchListener(mTouchListener);
        mGenderSpinner.setOnTouchListener(mTouchListener);

        setupSpinner();

        mChildEventListener = new ChildEventListener() {
            @Override
            public void onChildAdded(DataSnapshot dataSnapshot, String s) {
                mPet = dataSnapshot.getValue(Pet.class);
                PetAdapter petAdapter = CatalogActivity.mPetAdapter;
                petAdapter.add(mPet);
            }

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

            @Override
            public void onChildRemoved(DataSnapshot dataSnapshot) {}

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

            @Override
            public void onCancelled(DatabaseError databaseError) {}
        };
        mDatabaseReference.addChildEventListener(mChildEventListener);
    }
...
}

3 个答案:

答案 0 :(得分:1)

如果您不使用侦听器,则无法显示Firebase数据库中的数据,这就是ListView为空的原因。因此,您只需在EditorActivity中添加一个新的侦听器即可正确显示这些项目。

答案 1 :(得分:0)

在CatalogActivity中的“onResume()”方法中更新mPetAdapter数据。或者使用“观察者模式”监听数据库。

答案 2 :(得分:0)

您必须在CatalogActivity中创建firebase实例 并实现Firebase的 addValueEventListener 。添加/更新新数据时 onDataChange 会监听

示例代码

    mFirebaseInstance.getReference("abc").addValueEventListener(new ValueEventListener() {
            @Override
            public void onDataChange(DataSnapshot dataSnapshot) {

            }

            @Override
            public void onCancelled(DatabaseError error) {

            }
        });