使用Firebase setValue时重新创建Android活动

时间:2018-03-29 07:59:58

标签: java android firebase firebase-realtime-database

我的应用程序是在单击操作栏中的按钮时添加新字段或更新数据库中存在的字段。此按钮可更改用户的在线状态,并在Firebase数据库的Online_Log节点中添加或更新日志信息,其中包括登录和注销时间。每次我这样做,活动刷新并重新创建,我的意思是整个活动重新开始。

我该如何解决这个问题?

这是代码;

public class AdminAccount extends AppCompatActivity implements       NavigationView.OnNavigationItemSelectedListener{

private FirebaseAuth mAuth = FirebaseAuth.getInstance();

private FirebaseAuth.AuthStateListener authStateListener;

private ProgressDialog bar;

private FirebaseDatabase firebaseDatabase = FirebaseDatabase.getInstance();

private DatabaseReference databaseReference = firebaseDatabase.getReference();

private Item be_online;

private TextView online;

private boolean is_online;

private ImageView profileImage;

private static final int GALLERY_REQUEST = 1;

private Uri imageUri = null;

private FirebaseStorage firebaseStorage;

private ProgressDialog progressDialog;

private int total_work_time=0;

private int minutes =0 ;

private String last_login_time;

private String last_logout_time;

private boolean isUser = true;

private TextView fullname;

private ImageView page_header;

private static boolean runFirst = false;

private ViewPager mViewPager;

private int login_count;

private Button onlineButton;

private SectionsPagerAdapter mSectionsPagerAdapter;


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

    login_count = 0;
    Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
    setSupportActionBar(toolbar);
    getSupportActionBar().setDisplayShowTitleEnabled(false);
    getSupportActionBar().setDisplayShowHomeEnabled(true);
    getSupportActionBar().setIcon(R.drawable.binnazmenulogo);

    DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
    ActionBarDrawerToggle toggle = new ActionBarDrawerToggle(
            this, drawer, toolbar, R.string.navigation_drawer_open, R.string.navigation_drawer_close);
    drawer.setDrawerListener(toggle);
    toggle.syncState();

    NavigationView navigationView = (NavigationView) findViewById(R.id.nav_view);
    navigationView.setNavigationItemSelectedListener(this);

    mSectionsPagerAdapter = new SectionsPagerAdapter(getSupportFragmentManager());

    // Set up the ViewPager with the sections adapter.
    mViewPager = (ViewPager) findViewById(R.id.container);
    mViewPager.setAdapter(mSectionsPagerAdapter);

    TabLayout tabLayout = (TabLayout) findViewById(R.id.tabs);

    mViewPager.addOnPageChangeListener(new TabLayout.TabLayoutOnPageChangeListener(tabLayout));
    tabLayout.addOnTabSelectedListener(new TabLayout.ViewPagerOnTabSelectedListener(mViewPager));


    firebaseStorage = FirebaseStorage.getInstance();

    firebaseDatabase = FirebaseDatabase.getInstance();

    databaseReference = firebaseDatabase.getReference();

    profileImage = (ImageView) findViewById(R.id.profile_image);

    online = (TextView) findViewById(R.id.admin_online);

    be_online = (Item) findViewById(R.id.action_be_online);

    fullname = (TextView) findViewById(R.id.content_admin_name_surname);

    page_header = (ImageView) findViewById(R.id.content_admin_header_background_image);

    onlineButton = (Button) findViewById(R.id.online_Button);

    progressDialog = new ProgressDialog(this);

        mAuth = FirebaseAuth.getInstance();

        bar = new ProgressDialog(this);



        authStateListener = new FirebaseAuth.AuthStateListener() {
            @Override
            public void onAuthStateChanged(@NonNull FirebaseAuth firebaseAuth) {
                if (firebaseAuth.getCurrentUser() == null) {
                    bar.dismiss();
                    isUser =false;
                    Intent toMain = new Intent(AdminAccount.this, MainActivity.class);
                    //toMain.setFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP);
                    toMain.addCategory(Intent.CATEGORY_HOME);
                    toMain.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
                    startActivity(toMain);
                }else{
                    isUser = true;
                }
            }
        };

        onlineButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Log.v("login_counter", login_count+"");

                Date currentTime = Calendar.getInstance().getTime();
                StringTokenizer tokenizer = new StringTokenizer(currentTime.toString()," ");
                String dayName= tokenizer.nextToken();
                String mount= tokenizer.nextToken();
                String dayNumber= tokenizer.nextToken();
                String time= tokenizer.nextToken();
                String timeZone= tokenizer.nextToken();
                String year= tokenizer.nextToken();

                last_logout_time = Calendar.getInstance().getTime().toString();

                StringTokenizer tokenizer_date1 = new StringTokenizer(last_login_time," ");
                String dayName2= tokenizer_date1.nextToken();
                String mount2= tokenizer_date1.nextToken();
                String dayNumber2= tokenizer_date1.nextToken();
                String time2= tokenizer_date1.nextToken();
                String timeZone2= tokenizer_date1.nextToken();
                String year2= tokenizer_date1.nextToken();

                StringTokenizer tokenizer_date2 = new StringTokenizer(last_logout_time," ");
                String dayName3= tokenizer_date2.nextToken();
                String mount3= tokenizer_date2.nextToken();
                String dayNumber3= tokenizer_date2.nextToken();
                String time3= tokenizer_date2.nextToken();
                String timeZone3= tokenizer_date2.nextToken();
                String year3= tokenizer_date2.nextToken();

                if(!is_online) {
                    DatabaseReference ref = FirebaseDatabase.getInstance().getReference().child("users").child(mAuth.getCurrentUser().getUid()).child("online");
                    ref.setValue(true);

                    last_login_time =Calendar.getInstance().getTime().toString();
                    firebaseDatabase.getReference().child("users").child(mAuth.getCurrentUser().getUid()).child("OnlineLog").child(year+"/"+mount+"/"+dayNumber).child("Log"+login_count).child("lastlogin").setValue(time);
                    firebaseDatabase.getReference().child("users").child(mAuth.getCurrentUser().getUid()).child("lastlogin").setValue(currentTime.toString());
                }else{
                    DatabaseReference ref = FirebaseDatabase.getInstance().getReference().child("users").child(mAuth.getCurrentUser().getUid()).child("online");
                    ref.setValue(false);


                    SimpleDateFormat format = new SimpleDateFormat("HH:mm:ss");

                    Date date1 = null;
                    try {
                        date1 = format.parse(time2);
                    } catch (ParseException e) {
                        e.printStackTrace();
                    }
                    Log.v("Date1",date1.toString());
                    Date date2 = null;
                    try {
                        date2 = format.parse(time3);
                    } catch (ParseException e) {
                        e.printStackTrace();
                    }
                    Log.v("Date2",date2.toString());
                    long difference = date2.getTime() - date1.getTime();
                    Log.v("date2_time",date2.getTime()+"");
                    Log.v("date1_time",date1.getTime()+"");

                    minutes = (int) TimeUnit.MILLISECONDS.toMinutes(difference);

                    Log.v("timeDif",minutes+"");

                    if(minutes<0)minutes = -1*minutes;


                    Log.v("timeDif",minutes+"");
                    total_work_time += minutes;
                    Log.v("TotalWorkTime",total_work_time+"");



                    firebaseDatabase.getReference().child("users").child(mAuth.getCurrentUser().getUid()).child("OnlineLog").child(year+"/"+mount+"/"+dayNumber).child("Log"+login_count).child("lastlogout").setValue(time);
                    firebaseDatabase.getReference().child("users").child(mAuth.getCurrentUser().getUid()).child("lastlogout").setValue(currentTime.toString());
                    firebaseDatabase.getReference().child("users").child(mAuth.getCurrentUser().getUid()).child("OnlineLog").child(year+"/"+mount+"/"+dayNumber).child("Log"+login_count).child("totalworktime").setValue(total_work_time);
                    login_count++;
                }
            }
        });

    }


@Override
public void onBackPressed() {
    DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
    if (drawer.isDrawerOpen(GravityCompat.START)) {
        drawer.closeDrawer(GravityCompat.START);
    } else {
        finish();
        super.onBackPressed();
    }
}

@Override
protected void onStart() {
    super.onStart();
    mAuth.addAuthStateListener(authStateListener);
    authStateListener = new FirebaseAuth.AuthStateListener() {
        @Override
        public void onAuthStateChanged(@NonNull FirebaseAuth firebaseAuth) {
            if (firebaseAuth.getCurrentUser() == null) {
                bar.dismiss();
                isUser = false;
                Intent toMain = new Intent(AdminAccount.this, MainActivity.class);
                //toMain.setFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP);
                toMain.addCategory(Intent.CATEGORY_HOME);
                toMain.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
                startActivity(toMain);
            } else {
                isUser = true;
            }
        }
    };
    if (isUser) {
        firebaseDatabase.getReference().child("users").child(mAuth.getCurrentUser().getUid()).child("image").addValueEventListener(new ValueEventListener() {
            @Override
            public void onDataChange(DataSnapshot dataSnapshot) {
                String profile_image_url = dataSnapshot.getValue(String.class);
                if (profile_image_url != null) {
                    Picasso.with(AdminAccount.this).load(profile_image_url).resize(1000, 800)
                            .centerCrop().into(profileImage);
                }
            }

            @Override
            public void onCancelled(DatabaseError databaseError) {

            }
        });
        firebaseDatabase.getReference().child("users").child(mAuth.getCurrentUser().getUid()).addListenerForSingleValueEvent(new ValueEventListener() {
            @Override
            public void onDataChange(DataSnapshot dataSnapshot) {
                if (dataSnapshot.child("online").getValue(boolean.class)) {
                    online.setText("Online");
                    is_online = true;
                } else {
                    online.setText("Offline");
                    is_online = false;
                }
                String name = "";
                String surname = "";
                if(dataSnapshot.child("name").getValue(String.class) != null || dataSnapshot.child("secondname").getValue(String.class) != null) {
                    name = dataSnapshot.child("name").getValue(String.class);
                    surname = dataSnapshot.child("secondname").getValue(String.class);
                }
                String fname= name+" "+surname;
                fullname.setText(fname);
                last_login_time = dataSnapshot.child("lastlogin").getValue(String.class);
                last_logout_time = dataSnapshot.child("lastlogout").getValue(String.class);

                String background_image_url = dataSnapshot.child("background_image").getValue(String.class);

                if (background_image_url != null) {
                    Glide.with(getApplicationContext()).load(background_image_url).into(page_header);
                }
            }


            @Override
            public void onCancelled(DatabaseError databaseError) {
            }
        });

    }


}


@Override
public boolean onCreateOptionsMenu(Menu menu) {

    getMenuInflater().inflate(R.menu.second_menu, menu);

    if(!is_online) {
        menu.getItem(0).setIcon(R.mipmap.ic_offline);
    }else{
        menu.getItem(0).setIcon(R.mipmap.ic_online_round);
    }


    return true;
}

public void updateTotalWorkTime(){

}

@Override
public boolean onOptionsItemSelected(MenuItem item) {
    int id = item.getItemId();
    //noinspection SimplifiableIfStatement
    if(id == R.id.become_online){



    }

    return super.onOptionsItemSelected(item);
}

@SuppressWarnings("StatementWithEmptyBody")
@Override
public boolean onNavigationItemSelected(MenuItem item) {
    // Handle navigation view item clicks here.
    int id = item.getItemId();

    if (id == R.id.nav_logout) {
        DatabaseReference ref = FirebaseDatabase.getInstance().getReference().child("users").child(mAuth.getCurrentUser().getUid()).child("online");
        // ref.setValue(false);
        bar.setMessage("Logging out");
        bar.show();
        mAuth.signOut();
    } else if (id == R.id.nav_edit_profile) {
        Intent toEdit = new Intent(AdminAccount.this,EditProfile.class);
        //toEdit.setFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP);
        toEdit.addCategory(Intent.CATEGORY_HOME);
        toEdit.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
        startActivity(toEdit);
    }else if(id == R.id.nav_create_user){
        Intent toCreate = new Intent(AdminAccount.this,CreateUser.class);
        //toCreate.setFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP);
        toCreate.addCategory(Intent.CATEGORY_HOME);
        toCreate.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
        startActivity(toCreate);
    }else if(id == R.id.nav_list_users){
        Intent toInterface = new Intent(AdminAccount.this,AdminInterface.class);
        //toInterface.setFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP);
        toInterface.addCategory(Intent.CATEGORY_HOME);
        toInterface.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
        startActivity(toInterface);
    }

    DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
    drawer.closeDrawer(GravityCompat.START);
    return true;
}

/**
 * A placeholder fragment containing a simple view.
 */


public static class PlaceholderFragment extends Fragment {
    /**
     * The fragment argument representing the section number for this
     * fragment.
     */
    private FirebaseAuth mAuth = FirebaseAuth.getInstance();

    private FirebaseDatabase firebaseDatabase = FirebaseDatabase.getInstance();

    private DatabaseReference databaseReference = firebaseDatabase.getReference();

    private RecyclerView recyclerView;

    private Query query = databaseReference.child("users").child(mAuth.getCurrentUser().getUid()).child("OnlineLog");

    private FirebaseRecyclerAdapter<Online_Log_Card_View,AdminAccount.Online_Log_View_Holder> fireabaseRecylerAdapter;

    private static final String ARG_SECTION_NUMBER = "section_number";

    public PlaceholderFragment() {
    }

    /**
     * Returns a new instance of this fragment for the given section
     * number.
     */
    public static PlaceholderFragment newInstance(int sectionNumber) {
        PlaceholderFragment fragment = new PlaceholderFragment();
        Bundle args = new Bundle();
        args.putInt(ARG_SECTION_NUMBER, sectionNumber);
        fragment.setArguments(args);
        return fragment;
    }
    private View rootView;
    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        switch (getArguments().getInt(ARG_SECTION_NUMBER)){
            case 1:{
                rootView = inflater.inflate(R.layout.fragment_online_log, container, false);
                recyclerView = (RecyclerView) rootView.findViewById(R.id.online_log_recycler_view);
                recyclerView.setHasFixedSize(true);
                recyclerView.setLayoutManager(new LinearLayoutManager(getActivity()));



                Date currentTime = Calendar.getInstance().getTime();
                Log.v("Current date", currentTime.toString());
                final int month = currentTime.getMonth();
                StringTokenizer tokenizer = new StringTokenizer(currentTime.toString(), " ");
                final String dayName = tokenizer.nextToken();
                final String mount = tokenizer.nextToken();
                String dayNumber = tokenizer.nextToken();
                String time = tokenizer.nextToken();
                String timeZone = tokenizer.nextToken();
                final String year = tokenizer.nextToken();

                Calendar calendar = Calendar.getInstance();
                calendar.setTime(currentTime);
                String[] days = new String[] { "SUNDAY", "MONDAY", "TUESDAY", "WEDNESDAY", "THURSDAY", "FRIDAY", "SATURDAY" };
                final String day = days[calendar.get(Calendar.DAY_OF_WEEK)];

                int startDay = Integer.parseInt(dayNumber);






                    query = databaseReference.child("users").child(mAuth.getCurrentUser().getUid()).child("OnlineLog").child(year).child(mount).limitToLast(7);
                    Log.v("Online_Log_Query", year+" "+mount+" "+(startDay - 0));

                fireabaseRecylerAdapter = new FirebaseRecyclerAdapter<Online_Log_Card_View, Online_Log_View_Holder>(
                            Online_Log_Card_View.class,
                            R.layout.online_log_card,
                            Online_Log_View_Holder.class,
                            query
                    ) {
                        @Override
                        protected void populateViewHolder(final Online_Log_View_Holder viewHolder, Online_Log_Card_View model, int position) {


                            fireabaseRecylerAdapter.getRef(position).addListenerForSingleValueEvent(new ValueEventListener() {
                                @Override
                                public void onDataChange(DataSnapshot dataSnapshot) {
                                    Calendar target_Cal = Calendar.getInstance();
                                    target_Cal.set(Calendar.YEAR, Integer.parseInt(year));
                                    target_Cal.set(Calendar.MONTH, month);
                                    target_Cal.set(Calendar.DATE, Integer.parseInt(dataSnapshot.getKey().toString()));
                                    target_Cal.set(Calendar.HOUR, 5);
                                    target_Cal.set(Calendar.MINUTE,0);
                                    target_Cal.set(Calendar.SECOND,0);
                                    target_Cal.set(Calendar.MILLISECOND,0);
                                    Date target_time = target_Cal.getTime();
                                    Log.v("Target_time", target_time.toString());
                                    String[] days = new String[] { "SUNDAY", "MONDAY", "TUESDAY", "WEDNESDAY", "THURSDAY", "FRIDAY", "SATURDAY", "SUNDAY" };
                                    String target_Day = days[target_Cal.get(Calendar.DAY_OF_WEEK)];

                                    viewHolder.setDay(target_Day);
                                    viewHolder.setDate(Integer.parseInt(dataSnapshot.getKey().toString())+" "+mount);

                                }

                                @Override
                                public void onCancelled(DatabaseError databaseError) {

                                }
                            });

                            Log.v("Online Log", "Day : "+dayName);
                            viewHolder.setLastLogin(model.getLastlogin());
                            Log.v("Online Log", "Login : "+model.getLastlogin());
                            viewHolder.setLastLogout(model.getLastlogout());
                            Log.v("Online Log", "Logut : "+model.getLastlogout());
                        }
                    };
                recyclerView.setAdapter(fireabaseRecylerAdapter);
                break;

            }
            case 2:{
                rootView = inflater.inflate(R.layout.fragment_tasks, container, false);
                break;
            }
        }

        return rootView;
    }
}


/**
 * A {@link FragmentPagerAdapter} that returns a fragment corresponding to
 * one of the sections/tabs/pages.
 */
public static class SectionsPagerAdapter extends FragmentPagerAdapter {

    public SectionsPagerAdapter(FragmentManager fm) {
        super(fm);
    }

    @Override
    public Fragment getItem(int position) {
        // getItem is called to instantiate the fragment for the given page.
        // Return a PlaceholderFragment (defined as a static inner class below).
        return PlaceholderFragment.newInstance(position + 1);
    }

    @Override
    public int getCount() {
        // Show 3 total pages.
        return 2;
    }
}


public static class Online_Log_View_Holder extends RecyclerView.ViewHolder{

    public View mView;

    public Online_Log_View_Holder(View itemView) {
        super(itemView);
        mView = itemView;
    }

    public void setLastLogin(String lastLogin){
        TextView last_login = (TextView) mView.findViewById(R.id.online_log_lastLogin);
        last_login.setText(lastLogin);
    }
    public void setLastLogout(String lastLogout){
        TextView last_login = (TextView) mView.findViewById(R.id.online_log_lastLogout);
        last_login.setText(lastLogout);
    }
    public void setDay(String day){
        TextView Day = (TextView) mView.findViewById(R.id.online_log_day);
        Day.setText(day);
    }
    public void setDate(String date){
        TextView Date = (TextView) mView.findViewById(R.id.online_log_date);
        Date.setText(date);
    }
}
}

1 个答案:

答案 0 :(得分:0)

您可以使用firebase的 onDataChange()方法处理此问题。

void onDataChange(DataSnapshot snapshot)
  • 将使用快照调用此方法表示此位置的当前数据。每次数据更改时也会调用它。

将您的源代码(在其中初始化变量,定义或调用函数,设置recyclelerview适配器)放在单个函数中,例如 - intializeViewcontroller()。

然后在 onDataChange()方法中调用此函数。因此,当在firebase中完成任何更改时,您的活动将被刷新。

DatabaseReference databaseReference =
                FirebaseDatabase.getInstance().getReference("users/"+uid);

        databaseReference.addValueEventListener(new ValueEventListener() {

        @Override
        public void onDataChange(DataSnapshot dataSnapshot) {
            for (DataSnapshot locationSnapshot : dataSnapshot.getChildren()) {
                intializeViewController();
            }
        }