想要从设备更新导航抽屉中的用户图片

时间:2018-06-17 17:11:18

标签: android firebase firebase-storage

我想当有人看到谷歌登录时,他/她的个人资料照片,电子邮件和姓名出现在抽屉上,如下图所示,还应该有一个更新个人资料的选项,以便他/她可以从设备存储中替换该照片选择。并且当下次用户登录该设备pic将保持完整并且不应被谷歌id pic替换时。 enter image description here

这是我的MainActivity.java

import ...


public class MainActivity extends AppCompatActivity{

    private FirebaseAnalytics mFirebaseAnalytics;
    private FirebaseAuth mAuth;
    private FirebaseAuth.AuthStateListener mAuthStateListener;
    private FirebaseDatabase database = FirebaseDatabase.getInstance();
    private DatabaseReference myRef = database.getReference();
    private TextView mName;
    private TextView mEmail;
    private String name;
    private String emailname;
    private Uri photoUrl;
    private ImageView mPic;
    private NavigationView mNavigationView;
    private static final int RC_SIGN_IN = 0;
    public String TAG = "Main Activity";
    private SectionsPagerAdapter mSectionsPagerAdapter;
    private ViewPager mViewPager;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
        setSupportActionBar(toolbar);


        // Obtain the FirebaseAnalytics instance.
        mFirebaseAnalytics = FirebaseAnalytics.getInstance(this);
        mAuth = FirebaseAuth.getInstance();


        //myRef.setValue("Hello World");
        SectionsPagerAdapter mSectionPagerAdapter = new MainActivity.SectionsPagerAdapter(getSupportFragmentManager());
        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));
        if(mAuth.getCurrentUser()!=null)
        {
            Log.d("AUTH",mAuth.getCurrentUser().getEmail());
            //user already signed in
        }else {
            startActivityForResult(
                    AuthUI.getInstance()
                            .createSignInIntentBuilder()
                            .setAvailableProviders(Arrays.asList(
                                    new AuthUI.IdpConfig.EmailBuilder().build(),
                                    new AuthUI.IdpConfig.GoogleBuilder().build(),
                                    new AuthUI.IdpConfig.FacebookBuilder().build()))
                            .build(),
                    RC_SIGN_IN);
        }
        mNavigationView = (NavigationView) findViewById(R.id.nav_view);
        mName = (TextView) mNavigationView.getHeaderView(0).findViewById(R.id.username);
        mPic = (ImageView) mNavigationView.getHeaderView(0).findViewById(R.id.imageView);
        mEmail = (TextView) mNavigationView.getHeaderView(0).findViewById(R.id.email);
        getCurrentUserInfo();

        mNavigationView.setNavigationItemSelectedListener(new NavigationView.OnNavigationItemSelectedListener() {
            @Override
            public boolean onNavigationItemSelected(@NonNull MenuItem item) {
                int id = item.getItemId();
                switch (id) {
                    case R.id.nav_gallery:
                        Toast.makeText(MainActivity.this,"My Profile Selected",Toast.LENGTH_SHORT).show();
                        return true;

                    case R.id.nav_notifications:
                        Toast.makeText(MainActivity.this,"Notifications Selected",Toast.LENGTH_SHORT).show();
                        return true;

                    case R.id.nav_liked_posts:
                        Toast.makeText(MainActivity.this,"Liked Post",Toast.LENGTH_SHORT).show();
                        return true;

                    case R.id.nav_slideshow:
                        Toast.makeText(MainActivity.this,"Slideshow Selected",Toast.LENGTH_SHORT).show();
                        return true;

                    case R.id.log_out_button:
                        AuthUI.getInstance()
                                .signOut(MainActivity.this)
                                .addOnCompleteListener(new OnCompleteListener<Void>() {
                                    @Override
                                    public void onComplete(@NonNull Task<Void> task) {
                                        Log.d("AUTH","USER LOGGED OUT");
                                        finish();
                                    }
                                });
                        DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
                        drawer.closeDrawer(GravityCompat.START);
                        return true;

                    default:
                        return true;
                }
            }
        });
        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.addDrawerListener(toggle);
        toggle.syncState();
        getSupportActionBar().setDisplayHomeAsUpEnabled(true);

    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if(requestCode==RC_SIGN_IN){
            if(resultCode==RESULT_OK){
                //user logged in
                Log.d("AUTH",mAuth.getCurrentUser().getEmail());
                getCurrentUserInfo();
            }
            else {
                //user not authenticated
                Log.d("AUTH","NOT AUTHENTICATED");
            }
        }
    }
    @Override
    public void onBackPressed() {
        DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
        if (drawer.isDrawerOpen(GravityCompat.START)) {
            drawer.closeDrawer(GravityCompat.START);
        } else {
            super.onBackPressed();
        }
    }
    @Override
    public boolean onCreateOptionsMenu(Menu menu) {

        getMenuInflater().inflate(R.menu.main, menu);
        MenuItem item = menu.findItem(R.id.menuSearch);
        SearchView searchView = (SearchView)item.getActionView();

        searchView.setOnQueryTextListener(new SearchView.OnQueryTextListener() {
            @Override
            public boolean onQueryTextSubmit(String query) {
                // TODO: Do something when the user submits the search query.
                Log.d(TAG, "onQueryTextSubmit: Text Submitted");
                return false;
            }

            @Override
            public boolean onQueryTextChange(String newText) {
                Log.d(TAG, "onQueryTextChange: Text Changed");
                return false;
            }
        });
        return true;
    }
    @Override
    public boolean onOptionsItemSelected(MenuItem item) {

        int id = item.getItemId();

        /* if (id == R.id.action_search) {
            return true;
        } */

        return super.onOptionsItemSelected(item);
    }


    /*/For logout activity in navigation bar
    @SuppressWarnings("StatementWithEmptyBody")
    @Override
    public boolean onNavigationItemSelected(MenuItem item) {

        int id = item.getItemId();

        if (id == R.id.log_out_button) {
        // Handle the action
            AuthUI.getInstance()
                    .signOut(this)
                    .addOnCompleteListener(new OnCompleteListener<Void>() {
                        @Override
                        public void onComplete(@NonNull Task<Void> task) {
                            Log.d("AUTH","USER LOGGED OUT");
                            finish();
                        }
                    });
         }

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

    public class SectionsPagerAdapter extends FragmentPagerAdapter {

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

        @Override
        public Fragment getItem(int position) {
            switch (position){
                case 0:
                    Polls pollTab = new Polls();
                    return pollTab;
                case 1:
                    Facts factTab = new Facts();
                    return factTab;
                case 2:
                    News newsTab = new News();
                    return newsTab;

                default:
                    return null;
            }
        }

        @Override
        public int getCount() {
            return 3;
        }
    }

    private void getCurrentUserInfo(){
        FirebaseUser user = FirebaseAuth.getInstance().getCurrentUser();
        if(user!=null){

            for (UserInfo profile : user.getProviderData()){
                String providerId = profile.getProviderId();
                String uid = profile.getUid();
                name = profile.getDisplayName();
                photoUrl = profile.getPhotoUrl();
                emailname = profile.getEmail();
                mName.setText(name);
                mEmail.setText(emailname);
                if(name!=null && emailname!=null) {
                    myRef.child("Users").child(name).child("Email").setValue(emailname);
                    myRef.child("Users").child(name).child("UserId").setValue(uid);
                    }
                if (photoUrl == null) {
                    Picasso.get()
                            .load(R.drawable.usericon)
                            .resize(6000,2000)
                            .centerInside()
                            .into(mPic);
                }else {
                    Picasso.get()
                            .load(photoUrl.toString())
                            .resize(6000, 2000)
                            .centerInside()
                            .into(mPic);
                }
                }
        }
        }
}

我的activity_main.xml

<?xml version="1.0" encoding="utf-8"?>
<android.support.v4.widget.DrawerLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:id="@+id/drawer_layout"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:fitsSystemWindows="true"
    tools:openDrawer="start">

    <include
        layout="@layout/app_bar_main"
        android:layout_width="match_parent"
        android:layout_height="match_parent" />

    <android.support.design.widget.NavigationView
        android:id="@+id/nav_view"
        android:layout_width="wrap_content"
        android:layout_height="match_parent"
        android:layout_gravity="start"
        android:fitsSystemWindows="true"
        app:headerLayout="@layout/nav_header_main"
        app:menu="@menu/activity_main_drawer" >

    </android.support.design.widget.NavigationView>


</android.support.v4.widget.DrawerLayout>

建议我这样做的方法。我尝试了自己但失败了。谢谢:))

1 个答案:

答案 0 :(得分:1)

好的,所以我使用了一堆if-else代码实现了这一点,我在下面分享了这些代码。 最初,我将标志设置为0,并且当登录的用户尝试打开应用程序时,标志设置为1

 public void getCurrentUserInfo() {
        FirebaseUser user = FirebaseAuth.getInstance().getCurrentUser();
        if (user != null) {

            for (UserInfo profile : user.getProviderData()) {
                String providerId = profile.getProviderId();
                String uid = profile.getUid();
                name = profile.getDisplayName();
                if (flag!=1) {
                    photoUrl = profile.getPhotoUrl();
                    if (photoUrl == null) {
                        Picasso.get()
                                .load(R.drawable.usericon)
                                .resize(6000, 2000)
                                .transform(new CropCircleTransformation())
                                .centerInside()
                                .into(mPic);

                    } else {
                        Picasso.get()
                                .load(photoUrl.toString())
                                .resize(6000, 2000)
                                .transform(new CropCircleTransformation())
                                .centerInside()
                                .into(mPic);

                    }
                }else{
                    DatabaseReference valueRef = myRef.child("Users").child(name);
                    valueRef.child("ProfileUrl").addListenerForSingleValueEvent(new ValueEventListener() {
                        @Override
                        public void onDataChange(@NonNull DataSnapshot dataSnapshot) {
                            String url = dataSnapshot.getValue(String.class);
                            photoUrl=  Uri.parse( url );
                            if (photoUrl == null) {
                                Picasso.get()
                                        .load(R.drawable.usericon)
                                        .resize(6000, 2000)
                                        .transform(new CropCircleTransformation())
                                        .centerInside()
                                        .into(mPic);

                            } else {
                                Picasso.get()
                                        .load(photoUrl.toString())
                                        .resize(6000, 2000)
                                        .transform(new CropCircleTransformation())
                                        .centerInside()
                                        .into(mPic);

                            }

                        }

                        @Override
                        public void onCancelled(@NonNull DatabaseError databaseError) {

                        }
                    });
                }
                emailname = profile.getEmail();
                mName.setText(name);
                mEmail.setText(emailname);
                if (name != null && emailname != null) {
                    myRef.child("Users").child(name).child("Email").setValue(emailname);
                    myRef.child("Users").child(name).child("UserId").setValue(uid);
                }
            }
        }
    }

我在问题中张贴了完整的代码,这只是启动查询所需的编辑部分。对于任何查询,请发表评论。