Android - 将数据添加到firebase数据库

时间:2017-08-06 14:17:08

标签: java android firebase firebase-realtime-database firebase-authentication

我正在使用 firebase 开发一个Android应用程序作为我的数据库。我想在button的新闻中插入一些数据,但我想在数据库中插入的一些对象放在我的片段中的不同方法中。如何使用相同按钮

在不同方法中将数据插入数据库
public class mFragment extends Fragment implements 
DateFragment.DatePickerEvent {

DatabaseReference database;
FirebaseAuth mAuth;
EditText text1;
EditText text2;

@Override
public void onDateSelected(String date) {
    Button buttonDateText = (Button) getView().findViewById(R.id.buttonDate);
    buttonDateText.setText(date);
}

@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
                         Bundle savedInstanceState) {

    View rootView = inflater.inflate(R.layout.fragment_frag, container, false);
    database = FirebaseDatabase.getInstance().getReference("Persons");
    mAuth = FirebaseAuth.getInstance();
    final FirebaseUser user = mAuth.getCurrentUser();


    Button pickDateButton = (Button) rootView.findViewById(R.id.buttonDate);
    Button submitButton = (Button) rootView.findViewById(R.id.buttonSubmit);
    text1= (EditText) rootView.findViewById(R.id.oddsView);
    text2= (EditText) rootView.findViewById(R.id.betAmountView);

    pickDateButton.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            DateFragment picker = new DateFragment();
            picker.setDatePickerEvents(mFragment.this);
            picker.show(getFragmentManager(), "datePicker");
        }
    });

    submitButton.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            database.child("Person").addValueEventListener(new ValueEventListener() {
                @Override
                public void onDataChange(DataSnapshot dataSnapshot) {
                    String myText= text1.getText().toString().trim();
                    String myAnotherText= text2.getText().toString().trim();
                    String id = database.push().getKey();
                    database.child(user.getDisplayName()).child(id).child("Adress").setValue(myText);
                    database.child(user.getDisplayName()).child(id).child("name").setValue(myAnotherText);
                }

                @Override
                public void onCancelled(DatabaseError databaseError) {

                }
            });
        }
    });
    return rootView;
}


}

1 个答案:

答案 0 :(得分:0)

您可以使用实例变量。这样的事情:

public class MyFrag extends Fragment {
    private Object obj1, obj2;
    private void method1() {
        obj1 = new Object();
    } 
    private void method2() {
        obj2 = new Object();
    }
    private void doSomething() {
        // obj1 and obj2 are available here
    }
}