2017-06-30 64 views
0

我正在研究Android應用程序,其中有兩種類型的用戶。我向他們展示了同一主屏幕視圖的不同組件。所以我傳遞一個名爲「userType」的意圖字符串值來過濾顯示內容。當我第一次登錄/註冊進入應用程序時,主屏幕工作正常,意圖值不爲空無法從活動傳遞意圖字符串

我也有另一個Splash活動,在那裏我檢查用戶是否已經登錄。如果用戶登錄,我將用戶直接重定向到主屏幕。這次意圖值顯示了一個空指針。我正在使用Firebase數據庫。

這是我迄今爲止努力工作的。

發佈用於相同的必要代碼。

SignUpActivity.java

private void writeUserProfile() { 

    showProgressDialog("Saving..."); 
    Intent intent = getIntent(); 

    String fullName = intent.getStringExtra("fullName"); 
    String userEmailAddress = intent.getStringExtra("emailAddress"); 
    String userType = intent.getStringExtra("userType"); 

    String phoneNumber = phoneNumberTextInputEditText.getText().toString().trim(); 
    String dateOfBirth = dateofBirthTextInputEditText.getText().toString().trim(); 
    String securityAnswer = securityAnswerTextInputEditText.getText().toString().trim(); 

    if (!validateForm(phoneNumber, dateOfBirth, securityAnswer)) { 
     hideProgressDialog(); 
     return; 
    } 

    if(userType.equalsIgnoreCase("Standard")){ 
     hideProgressDialog(); 
     Toast.makeText(this, "User details saved!",Toast.LENGTH_SHORT).show(); 
     Intent guardianIntent = new Intent(ContactDetailsActivity.this, AddGuardianActivity.class); 
//  intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP | Intent.FLAG_ACTIVITY_NEW_TASK); 
      guardianIntent.putExtra("fullName", fullName); 
      guardianIntent.putExtra("userEmailAddress", userEmailAddress); 
      guardianIntent.putExtra("phoneNumber", phoneNumber); 
      guardianIntent.putExtra("dateofBirth", dateOfBirth); 
      guardianIntent.putExtra("userType", userType); 
      guardianIntent.putExtra("securityAnswer", securityAnswer); 
      guardianIntent.putExtra("securityQuestion", securityQuestion); 
      startActivity(guardianIntent); 
//  finish(); 
     }else{ 
      databaseReference.child("fullName").setValue(fullName); 
      databaseReference.child("phoneNumber").setValue(phoneNumber); 
      databaseReference.child("dateOfBirth").setValue(dateOfBirth); 
      databaseReference.child("securityAnswer").setValue(securityAnswer); 
      databaseReference.child("securityQuestion").setValue(securityQuestion); 
      databaseReference.child("userType").setValue(userType); 

      databaseReference.addValueEventListener(new ValueEventListener() { 
       @Override 
       public void onDataChange(DataSnapshot dataSnapshot) { 
        Profile profile = dataSnapshot.getValue(Profile.class); 
        SharedPreferences preferences = PreferenceManager.getDefaultSharedPreferences(ContactDetailsActivity.this); 
        SharedPreferences.Editor editor = preferences.edit(); 
        if(profile != null) { 
         editor.putString(Preferences.NAME, profile.getFullName()); 
         editor.putString(Preferences.EMAIL, profile.getEmail()); 
        } 
        editor.putString(Preferences.USERID, getUid()); 
        editor.apply(); 
       } 

       @Override 
       public void onCancelled(DatabaseError databaseError) { 

       } 
      }); 

      hideProgressDialog(); 
      Toast.makeText(this, "Profile Created", Toast.LENGTH_SHORT).show(); 
      Intent mainMenuIntent = new Intent(ContactDetailsActivity.this, MainMenuActivity.class); 
      mainMenuIntent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP | Intent.FLAG_ACTIVITY_NEW_TASK); 
      mainMenuIntent.putExtra("userType", userType); 
      startActivity(mainMenuIntent); 
      finish(); 
     } 


    } 

,並在主菜單中,我篩選基於這樣的用戶類型的navigationDrawer組件。

MainMenuActivity.java

Intent intent = getIntent(); 
    userType = intent.getStringExtra("userType"); 


    Fragment home_fragment = new HomeFragment(); 
    FragmentTransaction transaction = getSupportFragmentManager().beginTransaction(); 
    Bundle bundle = new Bundle(); 
    bundle.putString("userType", userType); 
    home_fragment.setArguments(bundle); 
    transaction.replace(R.id.container_gaFragments, home_fragment); 
    transaction.commit(); 

    final SharedPreferences preferences = PreferenceManager.getDefaultSharedPreferences(this); 

    if (getUid() != null) { 
     String userId = getUid(); 
     firebaseAuth = FirebaseAuth.getInstance(); 
     databaseReference = FirebaseDatabase.getInstance().getReference().child("users").child(userId); 

    } else { 
     onAuthFailure(); 
    } 

    final PrimaryDrawerItem home = new PrimaryDrawerItem().withName("Home").withIdentifier(1).withIcon(GoogleMaterial.Icon.gmd_home); 
    final PrimaryDrawerItem profile = new PrimaryDrawerItem().withName("Profile").withIdentifier(2).withIcon(GoogleMaterial.Icon.gmd_account); 
    final PrimaryDrawerItem gallery = new PrimaryDrawerItem().withName("Gallery").withIdentifier(3).withIcon(R.drawable.ic_perm_media_black_24dp); 
    final PrimaryDrawerItem recognition = new PrimaryDrawerItem().withName("Recognition").withIdentifier(4).withIcon(GoogleMaterial.Icon.gmd_face); 
    final PrimaryDrawerItem maps = new PrimaryDrawerItem().withName("Maps").withIdentifier(5).withIcon(R.drawable.ic_place_black_24dp); 
    final PrimaryDrawerItem tagAndLocate = new PrimaryDrawerItem().withName("Tag & Locate").withIdentifier(6).withIcon(R.drawable.ic_remove_red_eye_black_24dp); 
    final PrimaryDrawerItem gamesAndPuzzle = new PrimaryDrawerItem().withName("Games & Puzzles").withIdentifier(7).withIcon(R.drawable.ic_casino_black_24dp); 
    final PrimaryDrawerItem backup = new PrimaryDrawerItem().withName("Backup").withIdentifier(8).withIcon(GoogleMaterial.Icon.gmd_save); 
    final PrimaryDrawerItem logout = new PrimaryDrawerItem().withName("Logout").withIdentifier(9).withIcon(FontAwesome.Icon.faw_sign_out); 

    DrawerImageLoader.init(new AbstractDrawerImageLoader() { 
     @Override 
     public void set(ImageView imageView, Uri uri, Drawable placeholder) { 
      Picasso.with(imageView.getContext()).load(uri).placeholder(placeholder).fit().centerCrop().into(imageView); 
     } 

     @Override 
     public void cancel(ImageView imageView) { 
      Picasso.with(imageView.getContext()).cancelRequest(imageView); 
     } 
    }); 

    String name = preferences.getString(Preferences.NAME, ""); 
    String email = preferences.getString(Preferences.EMAIL, ""); 
    final ProfileDrawerItem userProfile = new ProfileDrawerItem().withName(name).withEmail(email).withIcon(R.drawable.ic_account_circle_white_24dp); 

    headerResult = new AccountHeaderBuilder() 
      .withActivity(this) 
      .withHeaderBackground(R.drawable.header) 
      .withSelectionListEnabledForSingleProfile(false) 
      .addProfiles(userProfile) 
      .withOnAccountHeaderListener(new AccountHeader.OnAccountHeaderListener() { 
       @Override 
       public boolean onProfileChanged(View view, IProfile profile, boolean currentProfile) { 
        return false; 
       } 
      }) 
      .build(); 

    if(userType.equalsIgnoreCase("Standard")) { 
     result = new DrawerBuilder() 
       .withActivity(this) 
       .withAccountHeader(headerResult) 
       .withToolbar(toolbar) 
       .withDisplayBelowStatusBar(false) 
       .withTranslucentStatusBar(true) 
       .withSavedInstance(savedInstanceState) 
       .withActionBarDrawerToggle(true) 
       .withActionBarDrawerToggleAnimated(true) 
       .addDrawerItems(home) 
       .addDrawerItems(profile) 
       .addDrawerItems(gallery) 
       .addDrawerItems(recognition) 
       .addDrawerItems(maps) 
       .addDrawerItems(tagAndLocate) 
       .addDrawerItems(gamesAndPuzzle) 
       .addDrawerItems(backup) 
       .addDrawerItems(new DividerDrawerItem()) 
       .addDrawerItems(logout) 
       .buildForFragment(); 

     result.setOnDrawerItemClickListener(new Drawer.OnDrawerItemClickListener() { 
      @Override 
      public boolean onItemClick(View view, int position, IDrawerItem drawerItem) { 

       int drawItemId = (int) drawerItem.getIdentifier(); 
       Intent intent; 
       Fragment fragment; 
       switch (drawItemId) { 

        case 1: 
         fragment = new HomeFragment(); 
         Bundle bundle = new Bundle(); 
         bundle.putString("userType", userType); 
         fragment.setArguments(bundle); 
         gaFragmentStack.add(home); 
         break; 
        case 2: 
         fragment = new ProfileFragment(); 
         gaFragmentStack.add(profile); 
         break; 
        case 3: 
         fragment = new GalleryFragment(); 
         gaFragmentStack.add(gallery); 
         break; 
        case 4: 
         fragment = new RecognitionFragment(); 
         gaFragmentStack.add(recognition); 
         break; 
        case 5: 
         fragment = new MapsFragment(); 
         gaFragmentStack.add(maps); 
         break; 
        case 6: 
         fragment = new TagLocateFragment(); 
         gaFragmentStack.add(tagAndLocate); 
         break; 
        case 7: 
         fragment = new GamesPuzzlesFragment(); 
         gaFragmentStack.add(gamesAndPuzzle); 
         break; 
        case 8: 
         fragment = new BackupFragment(); 
         gaFragmentStack.add(backup); 
         break; 
        default: 
         fragment = new HomeFragment(); 
         break; 
       } 
       if (drawItemId == 9) { 
        FirebaseAuth.getInstance().signOut(); 
        SharedPreferences.Editor editor = preferences.edit(); 
        editor.clear(); 
        editor.apply(); 
        intent = new Intent(MainMenuActivity.this, SplashScreen.class); 
        intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TASK); 
        startActivity(intent); 
        finish(); 
       } 

       FragmentTransaction transaction = getSupportFragmentManager().beginTransaction(); 
       Bundle bundle = new Bundle(); 
       bundle.putString("userType", userType); 
       fragment.setArguments(bundle); 
       transaction.replace(R.id.container_gaFragments, fragment); 
       transaction.commit(); 
       return false; 
      } 
     }); 

    }else{ 
     result = new DrawerBuilder() 
       .withActivity(this) 
       .withAccountHeader(headerResult) 
       .withToolbar(toolbar) 
       .withDisplayBelowStatusBar(false) 
       .withTranslucentStatusBar(true) 
       .withSavedInstance(savedInstanceState) 
       .withActionBarDrawerToggle(true) 
       .withActionBarDrawerToggleAnimated(true) 
       .addDrawerItems(home) 
       .addDrawerItems(profile) 
       .addDrawerItems(maps) 
       .addDrawerItems(backup) 
       .addDrawerItems(new DividerDrawerItem()) 
       .addDrawerItems(logout) 
       .buildForFragment(); 

     result.setOnDrawerItemClickListener(new Drawer.OnDrawerItemClickListener() { 
      @Override 
      public boolean onItemClick(View view, int position, IDrawerItem drawerItem) { 

       int drawItemId = (int) drawerItem.getIdentifier(); 
       Intent intent; 
       Fragment fragment; 
       switch (drawItemId) { 

        case 1: 
         fragment = new HomeFragment(); 
         Bundle bundle = new Bundle(); 
         bundle.putString("userType", userType); 
         fragment.setArguments(bundle); 
         gaFragmentStack.add(home); 
         break; 
        case 2: 
         fragment = new ProfileFragment(); 
         gaFragmentStack.add(profile); 
         break; 
        case 5: 
         fragment = new MapsFragment(); 
         gaFragmentStack.add(maps); 
         break; 
        case 8: 
         fragment = new BackupFragment(); 
         gaFragmentStack.add(backup); 
         break; 
        default: 
         fragment = new HomeFragment(); 
         break; 
       } 
       if (drawItemId == 9) { 
        FirebaseAuth.getInstance().signOut(); 
        SharedPreferences.Editor editor = preferences.edit(); 
        editor.clear(); 
        editor.apply(); 
        intent = new Intent(MainMenuActivity.this, SplashScreen.class); 
        intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TASK); 
        startActivity(intent); 
        finish(); 
       } 

       FragmentTransaction transaction = getSupportFragmentManager().beginTransaction(); 
       transaction.replace(R.id.container_gaFragments, fragment); 
       Bundle bundle = new Bundle(); 
       bundle.putString("userType", userType); 
       fragment.setArguments(bundle); 
       transaction.commit(); 
       return false; 
      } 
     }); 
    } 
} 

這是閃屏我最初

談論SplashActivity.java

package com.project.group.projectga.activities; 

進口android.content.Intent; import android.os.Bundle;

import com.google.firebase.auth.FirebaseAuth; 
import com.google.firebase.database.DatabaseReference; 
import com.google.firebase.database.FirebaseDatabase; 
import com.project.group.projectga.R; 

public class SplashActivity extends CoreActivity { 

FirebaseAuth firebaseAuth; 
DatabaseReference databaseReference; 

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

    if (getUid() != null) { 
     final String userId = getUid(); 
     firebaseAuth = FirebaseAuth.getInstance(); 
     databaseReference = FirebaseDatabase.getInstance().getReference().child("users").child(userId); 

     Thread splashThread = new Thread() { 
      public void run() { 
       try { 
        sleep(3000); 
       } catch (InterruptedException e) { 
        e.printStackTrace(); 
       } finally { 
        if (firebaseAuth.getCurrentUser() != null) { 
         Intent mainMenuIntent = new Intent(SplashActivity.this, MainMenuActivity.class); 
         startActivity(mainMenuIntent); 
         finish(); 
        } else { 
         Intent splashScreenIntent = new Intent(SplashActivity.this, SplashScreen.class); 
         startActivity(splashScreenIntent); 
         finish(); 
        } 
       } 
      } 
     }; 
     splashThread.start(); 
    } 
} 

}

在這種情況下,當getCurrentUser不爲空,我將用戶重定向到MainMenuActivity。在MainMenuActivity這行代碼顯示了錯誤,當它不是第一次註冊/登錄

->>>> if(userType.equalsIgnoreCase("Standard")) { 
     result = new DrawerBuilder() 

我不知道我怎麼打發USERTYPE從SplashActivity。請幫忙!

+0

@IbrahimAli - 我知道爲什麼有空指針!我問你如何從SplashActivity傳遞userType? –

+0

然後,標題和正文並不真正匹配這個預期的問題。 – jdv

回答

0

您還沒有意向數據發送用戶類型,從SplashActivity

Intent mainMenuIntent = new Intent(SplashActivity.this, MainMenuActivity.class); 
         startActivity(mainMenuIntent); 

你應該像下面發送的用戶數據,

Intent mainMenuIntent = new Intent(SplashActivity.this, 
mainMenuIntent.putExtra("userType", [user type]); 
MainMenuActivity.class); 
          startActivity(mainMenuIntent); 
+0

我發現很難弄清楚如何獲取SplashActivity中存儲在Firebase中的userType,所以我可以將它傳遞給目標!你可以幫幫我嗎? –

+0

要從Firebase獲取數據,請參閱https://firebase.google.com/docs/database/android/read-and-write#listen_for_value_events –

+0

非常感謝!想出如何獲取數據並能夠成功傳遞userType –

0

我recomand您使用此代碼來獲取數據回到第二個活動。

String userType = (String) getIntent().getExtras().get("userType"); 

希望它有幫助。

+0

Splash Activity是我的第一個Activity,此活動的工作是檢查用戶是否已登錄。所以我不能在這個活動中獲得數據。我必須獲取數據庫引用並從那裏獲取userType! –