我无法将firebase数据库检索到主活动中的导航栏

时间:2017-11-24 10:34:31

标签: android firebase firebase-realtime-database gallery

我正在创建一个博客应用,但是当我从安装帐户活动转到主要活动时,如果我以普通用户身份注册,该应用就会被强制关闭,但如果我使用Google帐户登录,这不是本质!下面是我的设置帐户和mainactivity java文件。

**Here is my setup activity**

                            mCurrentUser = FirebaseAuth.getInstance().getCurrentUser();
                            String current_uid = mCurrentUser.getUid();
                            mAuth = FirebaseAuth.getInstance();
                            mStorageImage = FirebaseStorage.getInstance().getReference().child("profile_images");
                            mDatabseUsers = FirebaseDatabase.getInstance().getReference().child("Users").child(current_uid);
                            mSetupImageBtn = (CircleImageView) findViewById(R.id.setupImageBtn);
                            mNameField = (EditText) findViewById(R.id.setupNameField);
                            mSubmitBtn = (Button) findViewById(R.id.setupSubmitBtn);
                            mProgress = new ProgressDialog(this);

                //CLiking on submit button
                            mSubmitBtn.setOnClickListener(new View.OnClickListener() {
                                @Override
                                public void onClick(View view) {
                                    startSetupAccount();
                                }
                            });
        //TO setup image in the circular image view and firing the gallrey intent
                            mSetupImageBtn.setOnClickListener(new View.OnClickListener() {
                                @Override
                                public void onClick(View view) {
                                    Intent galleryIntent = new Intent();
                                    galleryIntent.setAction(Intent.ACTION_GET_CONTENT);
                                    galleryIntent.setType("image/*");
                                    startActivityForResult(galleryIntent, GALLERY_REQUEST);

                                }
                            });

                        }



               //Getting the firebase databse to setup the account 
                    private void startSetupAccount() {
                        final String name = mNameField.getText().toString().trim();
                        final String user_id = mAuth.getCurrentUser().getUid();
                        if(!TextUtils.isEmpty(name)&& mImageUri != null)
                        mProgress.setMessage("Finishing setup...");
                        mProgress.show();
                        {

                            StorageReference filepath = mStorageImage.child((mImageUri.getLastPathSegment()));
                            filepath.putFile(mImageUri).addOnSuccessListener(new OnSuccessListener<UploadTask.TaskSnapshot>() {
                                @Override
                                public void onSuccess(UploadTask.TaskSnapshot taskSnapshot) {
                                    String downloadUri = taskSnapshot.getDownloadUrl().toString();
                                    mDatabseUsers.child(user_id).child("name").setValue(name);
                                    mDatabseUsers.child(user_id).child("image").setValue(downloadUri);

                                    mProgress.dismiss();
                                    Intent mainIntent = new Intent(SetupActivity.this,MainActivity.class);
                                   mainIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TASK);
                                    startActivity(mainIntent);
                                    finish();
                                }
                            });


                        }
                    }
@Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);

  if(requestCode==GALLERY_REQUEST && resultCode==RESULT_OK)
  {

      Uri imageUri = data.getData();
      CropImage.activity(imageUri)
              .setGuidelines(CropImageView.Guidelines.ON)
              .setAspectRatio(1,1)
              .start(this);
  }
        if (requestCode == CropImage.CROP_IMAGE_ACTIVITY_REQUEST_CODE) {
            CropImage.ActivityResult result = CropImage.getActivityResult(data);
            if (resultCode == RESULT_OK) {
                mImageUri= result.getUri();
                mSetupImageBtn.setImageURI(mImageUri);
            } else if (resultCode == CropImage.CROP_IMAGE_ACTIVITY_RESULT_ERROR_CODE) {
                Exception error = result.getError();
            }
        }
    }
    }
               ## Main activity ##

这是我的主要活动,我希望我的导航抽屉能够检索我从设置活动中存储的数据,该活动是要在字符串文本和导航抽屉的图像视图中设置的名称和图像。

public class MainActivity extends AppCompatActivity implements NavigationView.OnNavigationItemSelectedListener {
    private RecyclerView mBlogList;

//       <!--Initializing firebase variables-->
    private DatabaseReference mDatabase;
    private FirebaseAuth mAuth;
    private DatabaseReference mDatabseUsers;
    private DatabaseReference mDatabaseLike;
    private FirebaseAuth.AuthStateListener mAuthListener;
    public static final String EXTRA_NAME = "Coverphoto";
    private Context context;
    private boolean mProcessLike = false;

//       <!--Initalizing Drawable variables-->
    private NavigationView mNavigationView;
    private TextView mName;
    private String name;
    private String image;
    private Uri photoUrl;
    private ImageView mPic;
    private Toolbar toolbar;

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

// <!--Collasping toolbar fetch Id's and display menu_items-->
        toolbar = (Toolbar) findViewById(R.id.main_toolbar);
        setSupportActionBar(toolbar);
        getSupportActionBar().setDisplayHomeAsUpEnabled(true);
        toolbar.inflateMenu(R.menu.main_menu);
        CollapsingToolbarLayout collapsingToolbar =
                (CollapsingToolbarLayout) findViewById(R.id.collapsing_toolbar);
        collapsingToolbar.setTitle("Heapooh");
//       <!--Firebase Authenticationat-- >
        mAuth = FirebaseAuth.getInstance();
        mAuthListener = new FirebaseAuth.AuthStateListener() {
            @Override
            public void onAuthStateChanged(@NonNull FirebaseAuth firebaseAuth) {

                if (firebaseAuth.getCurrentUser() == null) {
                    Intent loginIntent = new Intent(MainActivity.this, LoginActivity.class);
                    loginIntent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
                    startActivity(loginIntent);
                }
            }
        };

//       <!--Putting variables to the databse and keeping them synced -- >
        mDatabase = FirebaseDatabase.getInstance().getReferenceFromUrl("https://heapooh-9d5e2.firebaseio.com/").child("Blog");
        mDatabseUsers = FirebaseDatabase.getInstance().getReference().child("Users");
        mDatabaseLike = FirebaseDatabase.getInstance().getReference().child("Likes");
        mDatabseUsers.keepSynced(true);
        mDatabaseLike.keepSynced(true);
        mDatabase.keepSynced(true);

//       <!--Setting up the recyclerView-- >
        mBlogList = (RecyclerView) findViewById(R.id.blog_list);
        LinearLayoutManager layoutManager = new LinearLayoutManager(MainActivity.this);
        layoutManager.setReverseLayout(true);
        layoutManager.setStackFromEnd(true);
        mBlogList.setHasFixedSize(false);
        mBlogList.setLayoutManager(layoutManager);
        mBlogList.setNestedScrollingEnabled(false);

//       <!--Method to check if the user already exist defined below -- >
        checkUserExist();
//       <!--Adding the toggle to drawable -- >
        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();
        mNavigationView = (NavigationView) findViewById(R.id.nav_view);
        mNavigationView.setNavigationItemSelectedListener(this);
        mName = (TextView) mNavigationView.getHeaderView(0).findViewById(R.id.textView);
        mPic = (ImageView) mNavigationView.getHeaderView(0).findViewById(R.id.setupImage);

        mDatabase.addValueEventListener(new ValueEventListener() {
            @Override
            public void onDataChange(DataSnapshot dataSnapshot) {
                getCurrentinfo();
            }

            @Override
            public void onCancelled(DatabaseError databaseError) {

            }
        });
    }
    private void getCurrentinfo() {
        FirebaseUser user = FirebaseAuth.getInstance().getCurrentUser();
        if (user != null) {
            for (UserInfo profile : user.getProviderData()) {
                // Id of the provider (ex: google.com)
                String providerId = profile.getProviderId();

                // UID specific to the provider
                String uid = profile.getUid();

                // Name, email address, and profile photo Url
                name = profile.getDisplayName();
                photoUrl = profile.getPhotoUrl();
                mName.setText(name);

                Picasso.with(getApplicationContext())
                        .load(photoUrl.toString())
                        .placeholder(R.drawable.ic_menu_send)
                        .resize(120, 120)
                        .transform(new CircleTransform())
                        .centerCrop()
                        .into(mPic);


            }
            ;
        }
    }


    @Override
    public void onBackPressed() {
        DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
        if (drawer.isDrawerOpen(GravityCompat.START)) {
            drawer.closeDrawer(GravityCompat.START);
        }
        super.onBackPressed();
    }
//                            <!--On start method after authentication populated the Cardviews in the recycler views-->

    @Override
    protected void onStart() {
        super.onStart();
        mAuth.addAuthStateListener(mAuthListener);

        FirebaseRecyclerAdapter<Blog, BlogViewHolder> firebaseRecyclerAdapter = new FirebaseRecyclerAdapter<Blog, BlogViewHolder>(
                Blog.class,
                R.layout.blog_row,
                BlogViewHolder.class,
                mDatabase
        )


        {
            @Override
            protected void populateViewHolder(BlogViewHolder viewHolder, Blog model, int position) {
                final String post_key = getRef(position).getKey();
//                           <!--Hold 's the title,description,username,uid,key for the cardviews-->
                viewHolder.setTitle(model.getTitle());
                viewHolder.setDesc(model.getDesc());
                viewHolder.setImage(getApplicationContext(), model.getImage());
                viewHolder.setUsername(model.getUsername());
                viewHolder.setmLikebtn(post_key);

                viewHolder.mView.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
//                                 <!--Once the key is fetched it takes u to the blogsingle activity to read the full description over here -- >
                        Intent singleBlogIntent = new Intent(MainActivity.this, BlogSingleActivity.class);
                        singleBlogIntent.putExtra("blog_id", post_key);
                        startActivity(singleBlogIntent);

                    }
                });
//                            <!--To add or remove the liked value database once the like button is pressed and vice versa -- >
                        viewHolder.mLikebtn.setOnClickListener(new View.OnClickListener() {
                            @Override
                            public void onClick(View v) {

                                mProcessLike = true;
                                {
                                    mDatabaseLike.addValueEventListener(new ValueEventListener() {
                                        @Override
                                        public void onDataChange(DataSnapshot dataSnapshot) {
                                            if (mProcessLike) {
                                                if (dataSnapshot.child(post_key).hasChild(mAuth.getCurrentUser().getUid())) {
                                                    mDatabaseLike.child(post_key).child(mAuth.getCurrentUser().getUid()).removeValue();
                                                    mProcessLike = false;
                                                } else {
                                                    mDatabaseLike.child(post_key).child(mAuth.getCurrentUser().getUid()).setValue("RandomValue");
                                                    mProcessLike = false;

                                                }
                                            }
                                        }

                                        @Override
                                        public void onCancelled(DatabaseError databaseError) {

                                        }

                                    });
                                }
                            }
                        });
            }
        };
        mBlogList.setAdapter(firebaseRecyclerAdapter);
    }
//                   <!--Method to check if user exist is called over here-->

    private void checkUserExist() {
        if (mAuth.getCurrentUser() != null) {
            final String user_id = mAuth.getCurrentUser().getUid();
            mDatabseUsers.addValueEventListener(new ValueEventListener() {
                @Override
                public void onDataChange(DataSnapshot dataSnapshot) {



                    if (!dataSnapshot.hasChild(user_id)) {

                        Intent setupIntent = new Intent(MainActivity.this, SetupActivity.class);
                        setupIntent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
                        startActivity(setupIntent);
                    }
                }

                @Override
                public void onCancelled(DatabaseError databaseError) {

                }
            });
        }
    }
//                            <!--Retriving key to post to new page -->

    public static class BlogViewHolder extends RecyclerView.ViewHolder {
        View mView;
        ImageButton mLikebtn;
        DatabaseReference mDatabaseLike;
        FirebaseAuth mAuth;

        public BlogViewHolder(View itemView) {
            super(itemView);
            mView = itemView;
            mLikebtn = (ImageButton) mView.findViewById(R.id.like_btn);
            mDatabaseLike = FirebaseDatabase.getInstance().getReference().child("Likes");
            mAuth = FirebaseAuth.getInstance();
            mDatabaseLike.keepSynced(true);
        }

        public void setmLikebtn(final String post_key) {
            mDatabaseLike.addValueEventListener(new ValueEventListener() {
                @Override
                public void onDataChange(DataSnapshot dataSnapshot) {
//                                <!--Like button adds to database and disliking it removes from database -- >
                    if (dataSnapshot.child(post_key).hasChild(mAuth.getCurrentUser().getUid())) {
                        mLikebtn.setImageResource(R.drawable.ic_favorite);


                    } else {
                        mLikebtn.setImageResource(R.drawable.ic_favorite_border);
                    }
                }

                @Override
                public void onCancelled(DatabaseError databaseError) {

                }
            });
        }

//               <!--Fetching thetitle,desc, username andto set them>

        public void setTitle(String title) {
            TextView post_title = (TextView) mView.findViewById(R.id.post_title);
            post_title.setText(title);
        }

        public void setDesc(String desc) {
//            TextView post_desc = (TextView) mView.findViewById(R.id.post_desc);
//            post_desc.setText(desc);
        }

        public void setUsername(String username) {

            TextView post_username = (TextView) mView.findViewById(R.id.post_username);
            post_username.setText(username);

        }

//               <!--Use picassolibrary to load images-->

        public void setImage(final Context context, final String image) {
            final ImageView post_image = (ImageView) mView.findViewById(R.id.post_Image);
            Picasso.with(context).load(image).networkPolicy(NetworkPolicy.OFFLINE).into(post_image, new Callback() {
                @Override
                public void onSuccess() {

                }

                @Override
                public void onError() {
                    Picasso.with(context).load(image).into(post_image);
                }
            });
        }

    }

//    <!-- Drawer and menu items-->


    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        getMenuInflater().inflate(R.menu.main_menu, menu);
        getMenuInflater().inflate(R.menu.navigation_menu, menu);
        return super.onCreateOptionsMenu(menu);

    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        if (item.getItemId() == R.id.action_add) {
            startActivity(new Intent(MainActivity.this, PostActivity.class));
        }

        if (item.getItemId() == R.id.action_logout) {
            logout();
        }

        return super.onOptionsItemSelected(item);
    }

    @Override
    public boolean onNavigationItemSelected(@NonNull MenuItem item) {
        int id = item.getItemId();
        if (id == R.id.nav_home) {

        } else if (id == R.id.nav_videos) {
        } else if (id == R.id.nav_bookmarks) {
        }
        DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
        drawer.closeDrawer(GravityCompat.START);
        return true;
    }

    private void logout() {

        mAuth.signOut();

    }

0 个答案:

没有答案