2017-10-09 101 views
0

如何使用restrist用戶號碼。 「1」從導航欄訪問1選項卡。我有兩種類型的用戶:用戶1(Tutee)和用戶2(Tutor)。如果用戶1登錄,他們將在導航欄中看到「申請導師」選項卡,而不是「導師個人資料」。只有用戶2才能看到這個「導師個人資料標籤」,並有權訪問它。任何建議?Android Firebase獲取檢索用戶信息以限制訪問

所以我有這個數據結構在我的數據庫:

{ 
     "users" : { 
      "tua3IbbJ2APuLI1z1SesBQlAGCF2" : { 
      "birthday" : "02/07/1995", 
      "country" : "Zimbabwe", 
      "email" : "[email protected]", 
      "hobby" : "Rugby", 
      "name" : "Ainul ", 
      "phone" : "646446", 
      "uId" : "tua3IbbJ2APuLI1z1SesBQlAGCF2", 
      "userType" : "2" 
     } 
     } 
    } 

從我HomeActivity.java:

private void setUpNavigationView() { 
    //Setting Navigation View Item Selected Listener to handle the item click of the navigation menu 
    navigationView.setNavigationItemSelectedListener(new NavigationView.OnNavigationItemSelectedListener() { 

     // This method will trigger on item Click of navigation menu 
     @Override 
     public boolean onNavigationItemSelected(MenuItem menuItem) { 

      //Check to see which item was being clicked and perform appropriate action 
      switch (menuItem.getItemId()) { 
       //Replacing the main content with ContentFragment Which is our Inbox View; 
       case R.id.home: 
        navItemIndex = 0; 
        CURRENT_TAG = TAG_HOME; 
        break; 
       case R.id.nav_inbox: 
        navItemIndex = 1; 
        CURRENT_TAG = TAG_INBOX; 
        break; 
       case R.id.nav_notifications: 
        navItemIndex = 2; 
        CURRENT_TAG = TAG_NOTIFICATIONS; 
        break; 
       case R.id.nav_settings: 
        navItemIndex = 3; 
        CURRENT_TAG = TAG_SETTINGS; 
        break; 
       case R.id.nav_profile: 
        // launch new intent instead of loading fragment 
        startActivity(new Intent(HomeActivity.this, ProfileActivity.class)); 
        drawer.closeDrawers(); 
        return true; 
       case R.id.nav_about_us: 
        // launch new intent instead of loading fragment 
        startActivity(new Intent(HomeActivity.this, AboutUsActivity.class)); 
        drawer.closeDrawers(); 
        return true; 
       case R.id.nav_privacy_policy: 
        // launch new intent instead of loading fragment 
        startActivity(new Intent(HomeActivity.this, PrivacyPolicyActivity.class)); 
        drawer.closeDrawers(); 
        return true; 
       default: 
        navItemIndex = 0; 
      } 

      //Checking if the item is in checked state or not, if not make it in checked state 
      if (menuItem.isChecked()) { 
       menuItem.setChecked(false); 
      } else { 
       menuItem.setChecked(true); 
      } 
      menuItem.setChecked(true); 

      loadHomeFragment(); 

      return true; 
     } 
    }); 


    ActionBarDrawerToggle actionBarDrawerToggle = new ActionBarDrawerToggle(this, drawer, toolbar, R.string.openDrawer, R.string.closeDrawer) { 

     @Override 
     public void onDrawerClosed(View drawerView) { 
      // Code here will be triggered once the drawer closes as we dont want anything to happen so we leave this blank 
      super.onDrawerClosed(drawerView); 
     } 

     @Override 
     public void onDrawerOpened(View drawerView) { 
      // Code here will be triggered once the drawer open as we dont want anything to happen so we leave this blank 
      super.onDrawerOpened(drawerView); 
     } 
    }; 

    //Setting the actionbarToggle to drawer layout 
    drawer.setDrawerListener(actionBarDrawerToggle); 

    //calling sync state is necessary or else your hamburger icon wont show up 
    actionBarDrawerToggle.syncState(); 
} 

下面是HomeActivity.java的全部編碼以防萬一我在想念的東西:

package com.example.cqaai.tutorpal.activity; 
    import android.content.Intent; 
    import android.os.Bundle; 
    import android.os.Handler; 
    import android.support.design.widget.FloatingActionButton; 
    import android.support.design.widget.NavigationView; 
    import android.support.design.widget.Snackbar; 
    import android.support.v4.app.Fragment; 
    import android.support.v4.app.FragmentTransaction; 
    import android.support.v4.view.GravityCompat; 
    import android.support.v4.widget.DrawerLayout; 
    import android.support.v7.app.ActionBarDrawerToggle; 
    import android.support.v7.app.AppCompatActivity; 
    import android.support.v7.widget.Toolbar; 
    import android.view.Menu; 
    import android.view.MenuItem; 
    import android.view.View; 
    import android.widget.ImageView; 
    import android.widget.TextView; 
    import android.widget.Toast; 
    import android.support.annotation.NonNull; 
    import android.widget.Button; 

    import com.bumptech.glide.Glide; 
    import com.bumptech.glide.load.engine.DiskCacheStrategy; 

    import com.example.cqaai.tutorpal.R; 
    import com.example.cqaai.tutorpal.fragment.HomeFragment; 
    import com.example.cqaai.tutorpal.fragment.ProfileFragment; 
    import com.example.cqaai.tutorpal.fragment.NotificationsFragment; 
    import com.example.cqaai.tutorpal.fragment.InboxFragment; 
    import com.example.cqaai.tutorpal.fragment.SettingsFragment; 
    import com.example.cqaai.tutorpal.other.CircleTransform; 

    import com.google.firebase.auth.FirebaseAuth; 
    import com.google.firebase.auth.FirebaseUser; 

    public class HomeActivity extends AppCompatActivity { 

private NavigationView navigationView; 
private DrawerLayout drawer; 
private View navHeader; 
private ImageView imgNavHeaderBg, imgProfile; 
private TextView txtName, txtWebsite; 
private Toolbar toolbar; 
private FloatingActionButton fab; 

private Button btnSettings; 
private FirebaseAuth.AuthStateListener authListener; 
private FirebaseAuth auth; 

// urls to load navigation header background image 
// and profile image 
private static final String urlNavHeaderBg = "http://api.androidhive.info/images/nav-menu-header-bg.jpg"; 
private static final String urlProfileImg = "private static final String urlProfileImg = \"https://lh3.googleusercontent.com/eCtE_G34M9ygdkmOpYvCag1vBARCmZwnVS6rS5t4JLzJ6QgQSBquM0nuTsCpLhYbKljoyS-txg\";\n"; 

// index to identify current nav menu item 
public static int navItemIndex = 0; 

// tags used to attach the fragments 
private static final String TAG_HOME = "home"; 
private static final String TAG_PROFILE = "profile"; 
private static final String TAG_INBOX = "inbox"; 
private static final String TAG_NOTIFICATIONS = "notifications"; 
private static final String TAG_SETTINGS = "settings"; 
public static String CURRENT_TAG = TAG_HOME; 

// toolbar titles respected to selected nav menu item 
private String[] activityTitles; 

// flag to load home fragment when user presses back key 
private boolean shouldLoadHomeFragOnBackPress = true; 
private Handler mHandler; 


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

    //get firebase auth instance 
    auth = FirebaseAuth.getInstance(); 

    //get current user 
    final FirebaseUser user = FirebaseAuth.getInstance().getCurrentUser(); 

    authListener = new FirebaseAuth.AuthStateListener() { 
     @Override 
     public void onAuthStateChanged(@NonNull FirebaseAuth firebaseAuth) { 
      FirebaseUser user = firebaseAuth.getCurrentUser(); 
      if (user == null) { 
       // user auth state is changed - user is null 
       // launch login activity 
       startActivity(new Intent(HomeActivity.this, LoginActivity.class)); 
       finish(); 
      } 
     } 
    }; 



    toolbar = (Toolbar) findViewById(R.id.toolbar); 
    setSupportActionBar(toolbar); 

    mHandler = new Handler(); 

    drawer = (DrawerLayout) findViewById(R.id.drawer_layout); 
    navigationView = (NavigationView) findViewById(R.id.nav_view); 
    fab = (FloatingActionButton) findViewById(R.id.fab); 

    // Navigation view header 
    navHeader = navigationView.getHeaderView(0); 
    txtName = (TextView) navHeader.findViewById(R.id.name); 
    txtWebsite = (TextView) navHeader.findViewById(R.id.website); 
    imgNavHeaderBg = (ImageView) navHeader.findViewById(R.id.img_header_bg); 
    imgProfile = (ImageView) navHeader.findViewById(R.id.img_profile); 

    // load toolbar titles from string resources 
    activityTitles = getResources().getStringArray(R.array.nav_item_activity_titles); 

    fab.setOnClickListener(new View.OnClickListener() { 
     @Override 
     public void onClick(View view) { 
      Snackbar.make(view, "Replace with your own action", Snackbar.LENGTH_LONG) 
        .setAction("Action", null).show(); 
     } 
    }); 

    // load nav menu header data 
    loadNavHeader(); 

    // initializing navigation menu 
    setUpNavigationView(); 

    if (savedInstanceState == null) { 
     navItemIndex = 0; 
     CURRENT_TAG = TAG_HOME; 
     loadHomeFragment(); 
    } 
} 

/*** 
* Load navigation menu header information 
* like background image, profile image 
* name, website, notifications action view (dot) 
*/ 



private void loadNavHeader() { 
    // name, website 
    txtName.setText("Ainul Fitiri"); 
    txtWebsite.setText("@ainulfi3"); 

    // loading header background image 
    Glide.with(this).load(urlNavHeaderBg) 
      .crossFade() 
      .diskCacheStrategy(DiskCacheStrategy.ALL) 
      .into(imgNavHeaderBg); 

    // Loading profile image 
    Glide.with(this).load(urlProfileImg) 
      .crossFade() 
      .thumbnail(0.5f) 
      .bitmapTransform(new CircleTransform(this)) 
      .diskCacheStrategy(DiskCacheStrategy.ALL) 
      .into(imgProfile); 

    // showing dot next to notifications label 
    navigationView.getMenu().getItem(3).setActionView(R.layout.menu_dot); 
} 

/*** 
* Returns respected fragment that user 
* selected from navigation menu 
*/ 
private void loadHomeFragment() { 
    // selecting appropriate nav menu item 
    selectNavMenu(); 

    // set toolbar title 
    setToolbarTitle(); 

    // if user select the current navigation menu again, don't do anything 
    // just close the navigation drawer 
    if (getSupportFragmentManager().findFragmentByTag(CURRENT_TAG) != null) { 
     drawer.closeDrawers(); 

     // show or hide the fab button 
     toggleFab(); 
     return; 
    } 

    // Sometimes, when fragment has huge data, screen seems hanging 
    // when switching between navigation menus 
    // So using runnable, the fragment is loaded with cross fade effect 
    // This effect can be seen in GMail app 
    Runnable mPendingRunnable = new Runnable() { 
     @Override 
     public void run() { 
      // update the main content by replacing fragments 
      Fragment fragment = getHomeFragment(); 
      FragmentTransaction fragmentTransaction = getSupportFragmentManager().beginTransaction(); 
      fragmentTransaction.setCustomAnimations(android.R.anim.fade_in, 
        android.R.anim.fade_out); 
      fragmentTransaction.replace(R.id.frame, fragment, CURRENT_TAG); 
      fragmentTransaction.commitAllowingStateLoss(); 
     } 
    }; 

    // If mPendingRunnable is not null, then add to the message queue 
    if (mPendingRunnable != null) { 
     mHandler.post(mPendingRunnable); 
    } 

    // show or hide the fab button 
    toggleFab(); 

    //Closing drawer on item click 
    drawer.closeDrawers(); 

    // refresh toolbar menu 
    invalidateOptionsMenu(); 
} 

private Fragment getHomeFragment() { 
    switch (navItemIndex) { 
     case 0: 
      // home 
      HomeFragment homeFragment = new HomeFragment(); 
      return homeFragment; 
     case 1: 
      // Inbox fragment 
      InboxFragment inboxFragment = new InboxFragment(); 
      return inboxFragment; 
     case 2: 
      // notifications fragment 
      NotificationsFragment notificationsFragment = new NotificationsFragment(); 
      return notificationsFragment; 

     case 3: 
      // settings fragment 
      SettingsFragment settingsFragment = new SettingsFragment(); 
      return settingsFragment; 
     default: 
      return new HomeFragment(); 
    } 
} 

private void setToolbarTitle() { 
    getSupportActionBar().setTitle(activityTitles[navItemIndex]); 
} 

private void selectNavMenu() { 
    navigationView.getMenu().getItem(navItemIndex).setChecked(true); 
} 

private void setUpNavigationView() { 
    //Setting Navigation View Item Selected Listener to handle the item click of the navigation menu 
    navigationView.setNavigationItemSelectedListener(new NavigationView.OnNavigationItemSelectedListener() { 

     // This method will trigger on item Click of navigation menu 
     @Override 
     public boolean onNavigationItemSelected(MenuItem menuItem) { 

      //Check to see which item was being clicked and perform appropriate action 
      switch (menuItem.getItemId()) { 
       //Replacing the main content with ContentFragment Which is our Inbox View; 
       case R.id.home: 
        navItemIndex = 0; 
        CURRENT_TAG = TAG_HOME; 
        break; 
       case R.id.nav_profile: 
        navItemIndex = 1; 
        CURRENT_TAG = TAG_PROFILE; 
        break; 
       case R.id.nav_inbox: 
        navItemIndex = 1; 
        CURRENT_TAG = TAG_INBOX; 
        break; 
       case R.id.nav_notifications: 
        navItemIndex = 2; 
        CURRENT_TAG = TAG_NOTIFICATIONS; 
        break; 
       case R.id.nav_settings: 
        navItemIndex = 3; 
        CURRENT_TAG = TAG_SETTINGS; 
        break; 
       case R.id.nav_profile: 
        // launch new intent instead of loading fragment 
        startActivity(new Intent(HomeActivity.this, ProfileActivity.class)); 
        drawer.closeDrawers(); 
        return true; 
       case R.id.nav_about_us: 
        // launch new intent instead of loading fragment 
        startActivity(new Intent(HomeActivity.this, AboutUsActivity.class)); 
        drawer.closeDrawers(); 
        return true; 
       case R.id.nav_privacy_policy: 
        // launch new intent instead of loading fragment 
        startActivity(new Intent(HomeActivity.this, PrivacyPolicyActivity.class)); 
        drawer.closeDrawers(); 
        return true; 
       default: 
        navItemIndex = 0; 
      } 

      //Checking if the item is in checked state or not, if not make it in checked state 
      if (menuItem.isChecked()) { 
       menuItem.setChecked(false); 
      } else { 
       menuItem.setChecked(true); 
      } 
      menuItem.setChecked(true); 

      loadHomeFragment(); 

      return true; 
     } 
    }); 


    ActionBarDrawerToggle actionBarDrawerToggle = new ActionBarDrawerToggle(this, drawer, toolbar, R.string.openDrawer, R.string.closeDrawer) { 

     @Override 
     public void onDrawerClosed(View drawerView) { 
      // Code here will be triggered once the drawer closes as we dont want anything to happen so we leave this blank 
      super.onDrawerClosed(drawerView); 
     } 

     @Override 
     public void onDrawerOpened(View drawerView) { 
      // Code here will be triggered once the drawer open as we dont want anything to happen so we leave this blank 
      super.onDrawerOpened(drawerView); 
     } 
    }; 

    //Setting the actionbarToggle to drawer layout 
    drawer.setDrawerListener(actionBarDrawerToggle); 

    //calling sync state is necessary or else your hamburger icon wont show up 
    actionBarDrawerToggle.syncState(); 
} 

@Override 
public void onBackPressed() { 
    if (drawer.isDrawerOpen(GravityCompat.START)) { 
     drawer.closeDrawers(); 
     return; 
    } 

    // This code loads home fragment when back key is pressed 
    // when user is in other fragment than home 
    if (shouldLoadHomeFragOnBackPress) { 
     // checking if user is on other navigation menu 
     // rather than home 
     if (navItemIndex != 0) { 
      navItemIndex = 0; 
      CURRENT_TAG = TAG_HOME; 
      loadHomeFragment(); 
      return; 
     } 


    } 

    super.onBackPressed(); 
} 

@Override 
public boolean onCreateOptionsMenu(Menu menu) { 
    // Inflate the menu; this adds items to the action bar if it is present. 

    // show menu only when home fragment is selected 
    if (navItemIndex == 0) { 
     getMenuInflater().inflate(R.menu.main, menu); 

    } 

    // when fragment is notifications, load the menu created for notifications 
    if (navItemIndex == 3) { 
     getMenuInflater().inflate(R.menu.notifications, menu); 
    } 
    return true; 
} 



@Override 
public boolean onOptionsItemSelected(MenuItem item) { 
    // Handle action bar item clicks here. The action bar will 
    // automatically handle clicks on the Home/Up button, so long 
    // as you specify a parent activity in AndroidManifest.xml. 
    int id = item.getItemId(); 

    //noinspection SimplifiableIfStatement 
    if (id == R.id.action_logout) { 
     //signing out user 
     auth.signOut(); 
     Intent intent = new Intent(HomeActivity.this, LoginActivity.class); 
     startActivity(intent); 

     Toast.makeText(getApplicationContext(), "Logout user!", Toast.LENGTH_LONG).show(); 
     return true; 
    } 

    // user is in notifications fragment 
    // and selected 'Mark all as Read' 
    if (id == R.id.action_mark_all_read) { 
     Toast.makeText(getApplicationContext(), "All notifications marked as read!", Toast.LENGTH_LONG).show(); 
    } 

    // user is in notifications fragment 
    // and selected 'Clear All' 
    if (id == R.id.action_clear_notifications) { 
     Toast.makeText(getApplicationContext(), "Clear all notifications!", Toast.LENGTH_LONG).show(); 
    } 

    return super.onOptionsItemSelected(item); 
} 

// show or hide the fab 
private void toggleFab() { 
    if (navItemIndex == 0) 
     fab.show(); 
    else 
     fab.hide(); 
} 

}

回答

0

實現此目的的一種方法是使用SharedPreferences,因此您可以簡單地存儲userType並檢查它是類型1(Tutee)還是類型2(Tutor)。

首先,你需要獲得登錄用戶的用戶類型,所以在你的登錄界面,這可能去:

databaseReference.addValueEventListener(new ValueEventListener() { 
    @Override 
    public void onDataChange(DataSnapshot dataSnapshot) { 

     String userType = dataSnapshot.child("users").child(task.getResult().getUser().getUid()).getValue(User.class).getUId(); 

     SharedPreferences sharedPreferences = getSharedPreferences("prefs", MODE_PRIVATE); 
     SharedPreferences.Editor editor = sharedPreferences.edit(); 
     editor.putString("userType", userType); 
     editor.commit();     

    } 

    @Override 
    public void onCancelled(DatabaseError databaseError) { 
     // NO-OP 
    } 
}); 

User類應該是你的用戶POJO或任何類,你在你的模型用戶。

現在你可以從你的SharedPreferences檢索用戶類型,並設定一個條件,隱藏或顯示在您的NavigationView的菜單中的項目:

​​

上面的代碼應該在你的setUpNavigationView()方法中去。如果你想,清除預置設定在用戶與註銷:

editor.clear(); 
editor.commit(); 

希望這有助於;)