addValueEventListener Firebase Android之后数据丢失

时间:2018-03-04 05:05:22

标签: android firebase firebase-realtime-database

在addValueEventListener中,我正确获取firebase数据库的数据。我将该数据复制到名为newDay的变量中。但是,一旦我离开addValueEventListener,数据就会消失。如何确保数据保持不变?

        mCurrentUser = FirebaseAuth.getInstance().getCurrentUser();
        String current_uid = mCurrentUser.getUid();
        mUserDatabase = FirebaseDatabase.getInstance().getReference().child("Users").child(current_uid).child("week").child(day);
        newDay = new ArrayList<Integer>();
        mUserDatabase.addValueEventListener(new ValueEventListener() {
            @Override
            public void onDataChange(DataSnapshot dataSnapshot) {
                newDay.addAll((ArrayList<Integer>)dataSnapshot.getValue());
                Log.d("newday", "onDataChange:"+newDay.toString());

            }

            @Override
            public void onCancelled(DatabaseError databaseError) {

            }
        });
        Log.d("after","value " +newDay.toString());

这些是日志结果:

03-04 00:01:28.475 7961-7961/com.example.fake9.tendee D/newday: onDataChange:[0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]

之后,newDay奇怪地空了。

03-04 00:04:54.665 9906-9906/com.example.fake9.tendee D/after: value []

如果细节不够,则提供整个代码。许多部分似乎无关紧要:

public class ScheduleActivity extends AppCompatActivity implements AdapterView.OnItemSelectedListener {

    private Toolbar mToolbar;
    private Spinner chooseDay;
    private TimePicker startTime;
    private TimePicker endTime;
    private Button busyBtn;
    private Button freeBtn;
    String day;
    Map<String,ArrayList<Integer>> changeweek;
    ArrayList<Integer> test;
    ArrayList<Integer> newDay;

    private DatabaseReference mUserDatabase;
    private FirebaseUser mCurrentUser;

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

        mToolbar = (Toolbar)findViewById(R.id.schedule_toolbar);
        setSupportActionBar(mToolbar);
        getSupportActionBar().setDisplayHomeAsUpEnabled(true);
        getSupportActionBar().setTitle("Schedule");

        chooseDay = (Spinner)findViewById(R.id.chooseDay_spinner);
        chooseDay.setOnItemSelectedListener(this);
        List<String> week = new ArrayList<String>();
        week.add("Monday");
        week.add("Tuesday");
        week.add("Wednesday");
        week.add("Thursday");
        week.add("Friday");
        ArrayAdapter<String> dataAdapter = new ArrayAdapter<String>(this,android.R.layout.simple_spinner_item,week);
        dataAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
        chooseDay.setAdapter(dataAdapter);

        startTime = (TimePicker)findViewById(R.id.start_timePicker);
        endTime = (TimePicker)findViewById(R.id.end_timePicker);
        freeBtn = (Button)findViewById(R.id.free_btn);
        freeBtn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                int startHour = startTime.getCurrentHour();
                int startMin = startTime.getCurrentMinute();
                int endHour = endTime.getCurrentHour();
                int endMin = endTime.getCurrentMinute();
                int startIndex = 0;
                int endIndex = 0;
                int intervals = 0;
                //Log.d("hour", "onClick: "+startHour);
                //Log.d("minute", "onClick: "+startMin);
                if (startHour < 9 || startHour > 17 || endHour < 9 || endHour > 17) {
                    Toast.makeText(ScheduleActivity.this, "invalid time", Toast.LENGTH_SHORT).show();
                    return;
                }
                if (startHour > endHour) {
                    Toast.makeText(ScheduleActivity.this, "impossible time", Toast.LENGTH_SHORT).show();
                    return;
                }
                startIndex = (startHour - 9) * 2;
                if (startMin >= 30) {
                    startIndex = startIndex + 1;
                }
                //Log.d("startIndex", "onClick: "+startIndex);
                endIndex = (endHour - 9) * 2;
                if (endMin >= 30) {
                    endIndex = endIndex + 1;
                }
                final int finalstart = startIndex;
                final int finalend = endIndex;
                //Log.d("endIndex", "onClick: "+endIndex);
                mCurrentUser = FirebaseAuth.getInstance().getCurrentUser();
                String current_uid = mCurrentUser.getUid();
                mUserDatabase = FirebaseDatabase.getInstance().getReference().child("Users").child(current_uid).child("week").child(day);
                newDay = new ArrayList<Integer>();
                mUserDatabase.addValueEventListener(new ValueEventListener() {
                    @Override
                    public void onDataChange(DataSnapshot dataSnapshot) {
                        newDay.addAll((ArrayList<Integer>)dataSnapshot.getValue());
                        Log.d("newday", "onDataChange:"+newDay.toString());

                    }

                    @Override
                    public void onCancelled(DatabaseError databaseError) {

                    }
                });
                Log.d("after","value " +newDay.toString());
                intervals = endIndex - startIndex;
                for (int i = startIndex; i < endIndex; i++) {
                    Log.d("indexes", "onClick: "+i);
                }
            }
        });
    }

1 个答案:

答案 0 :(得分:1)

该行

  

Log.d(“after”,“valu”+ newDay.toString());

在firebase从数据库获取结果之前调用。 您需要做的就是创建一个方法

public void printResult(){
  Log.d("after","valu" + newDay.toString());
}

现在将此方法称为

newDay = new ArrayList<Integer>();
        mUserDatabase.addValueEventListener(new ValueEventListener() {
            @Override
            public void onDataChange(DataSnapshot dataSnapshot) {


newDay.addAll((ArrayList<Integer>)dataSnapshot.getValue());
                Log.d("newday", "onDataChange:"+newDay.toString());
                printResult();
        }

        @Override
        public void onCancelled(DatabaseError databaseError) {

        }
    });

<强>原因

Firebase拥有自己的异步机制,就像volcol库onDataChange函数一样,当firebase从互联网上获得一些结果并执行下面的代码时,正常情况下你的代码就是你的Log.d(“之后”,“值”+ newDay.toString());线。

希望这会对你有所帮助。