【问题标题】:Why do i get argument might be null error?为什么我得到参数可能是空错误?
【发布时间】:2018-10-07 19:45:01
【问题描述】:
package e.starf.project;

import android.content.Context;
import android.content.Intent;
import android.media.Image;
import android.support.annotation.NonNull;
import android.support.design.widget.NavigationView;
import android.support.v4.widget.DrawerLayout;
import android.support.v7.app.ActionBarDrawerToggle;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.Toolbar;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.support.v7.widget.RecyclerView;
import android.view.Display;
import android.view.LayoutInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.bumptech.glide.annotation.GlideModule;
import com.bumptech.glide.module.AppGlideModule;
import com.bumptech.glide.Glide;
import com.firebase.ui.database.FirebaseRecyclerAdapter;
import com.firebase.ui.database.FirebaseRecyclerOptions;
import com.google.firebase.auth.FirebaseAuth;
import com.google.firebase.auth.FirebaseUser;
import com.google.firebase.database.DataSnapshot;
import com.google.firebase.database.DatabaseError;
import com.google.firebase.database.DatabaseReference;
import com.google.firebase.database.FirebaseDatabase;
import com.google.firebase.database.ValueEventListener;
import com.google.firebase.storage.FirebaseStorage;
import com.google.firebase.storage.StorageReference;
import com.squareup.picasso.Picasso;

import de.hdodenhof.circleimageview.CircleImageView;

public class MainActivity extends AppCompatActivity {
    private NavigationView navigationView;
    private DrawerLayout drawerLayout;
    private ActionBarDrawerToggle actionBarDrawerToggle;
    private RecyclerView postList;
    private Toolbar toolbar;
    private ImageButton AddNewPostButton;
    private FirebaseAuth firebaseAuth;
    private DatabaseReference UsersRef, PostsRef, LikesRef;
    private StorageReference mStorageRef;

    String currentUserID;
    Boolean LikeChecker = false;


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



        firebaseAuth = FirebaseAuth.getInstance();
        UsersRef = FirebaseDatabase.getInstance().getReference().child("Users");
        PostsRef = FirebaseDatabase.getInstance().getReference().child("Posts");
        LikesRef = FirebaseDatabase.getInstance().getReference().child("Likes");

        UsersRef.keepSynced(true);
        PostsRef.keepSynced(true);
        LikesRef.keepSynced(true);
        mStorageRef = FirebaseStorage.getInstance().getReference();

        toolbar = (Toolbar) findViewById(R.id.main_page_toolbar);
        setSupportActionBar(toolbar);
        getSupportActionBar().setTitle("Home");

        AddNewPostButton = (ImageButton) findViewById(R.id.add_new_post);

        drawerLayout = (DrawerLayout) findViewById(R.id.drawer_layout);
        actionBarDrawerToggle = new ActionBarDrawerToggle(MainActivity.this, drawerLayout,
            R.string.drawer_open, R.string.drawer_close);
        drawerLayout.addDrawerListener(actionBarDrawerToggle);
        actionBarDrawerToggle.syncState();
        getSupportActionBar().setDisplayHomeAsUpEnabled(true);
        navigationView = (NavigationView) findViewById(R.id.navigation_view);

        postList = (RecyclerView) findViewById(R.id.all_users_post_list);
        postList.setHasFixedSize(true);
        LinearLayoutManager linearLayoutManager = new LinearLayoutManager(this);
        linearLayoutManager.setReverseLayout(true);
        linearLayoutManager.setStackFromEnd(true);
        postList.setLayoutManager(linearLayoutManager);

        View navView = navigationView.inflateHeaderView(R.layout.navigration_header);

        navigationView.setNavigationItemSelectedListener(new NavigationView.OnNavigationItemSelectedListener() {
            @Override
            public boolean onNavigationItemSelected(@NonNull MenuItem item) {
                UserMenuSelector(item);
                return false;
            }
        });

        AddNewPostButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                SendUserToPostActivity();
            }
        });
        DisplayAllUsersPosts();
    }

    private void DisplayAllUsersPosts() {
        final FirebaseRecyclerOptions < Posts options = new FirebaseRecyclerOptions.Builder < Posts().setQuery(PostsRef,
            Posts.class).build();

        FirebaseRecyclerAdapter < Posts, PostsViewHolder firebaseRecyclerAdapter = new FirebaseRecyclerAdapter < Posts,
            PostsViewHolder(options) {
                @NonNull
                @Override
                public PostsViewHolder onCreateViewHolder(@NonNull ViewGroup viewGroup, int i) {

                    View view = LayoutInflater.from(viewGroup.getContext()).inflate(R.layout.all_posts_layout,
                        viewGroup, false);
                    return new PostsViewHolder(view);
                }

                @Override
                protected void onBindViewHolder(@NonNull final PostsViewHolder holder, int position, @NonNull final Posts model) {
                    final String PostKey = getRef(position).getKey();

                    holder.setName(model.getName());
                    holder.setTime(model.getTime());
                    holder.setDate(model.getDate());
                    holder.setDescription(model.getDescription());
                    holder.setPostimage(getApplicationContext(), model.getPostimage());

                    holder.setLikeButtonStatus(PostKey);

                    holder.mView.setOnClickListener(new View.OnClickListener() {
                        @Override
                        public void onClick(View view) {
                            Intent clickPostIntent = new Intent(MainActivity.this, ClickPostActivity.class);
                            clickPostIntent.putExtra("PostKey", PostKey);
                            startActivity(clickPostIntent);
                        }
                    });

                    holder.CommentPostButton.setOnClickListener(new View.OnClickListener() {
                        @Override
                        public void onClick(View view) {
                            Intent clickPostIntent = new Intent(MainActivity.this, CommentsActivity.class);
                            clickPostIntent.putExtra("PostKey", PostKey);
                            startActivity(clickPostIntent);
                        }
                    });

                    holder.LikePostButton.setOnClickListener(new View.OnClickListener() {
                        @Override
                        public void onClick(View view) {
                            LikeChecker = true;

                            if (LikeChecker) {
                                LikesRef.addValueEventListener(new ValueEventListener() {
                                    @Override
                                    public void onDataChange(@NonNull DataSnapshot dataSnapshot) {
                                        if (LikeChecker.equals(true)) {
                                            if (dataSnapshot.child(PostKey).hasChild(currentUserID)) {
                                                LikesRef.child(PostKey).child(currentUserID).removeValue();
                                                LikeChecker = false;
                                            } else {
                                                LikesRef.child(PostKey).child(currentUserID).setValue(true);
                                                LikeChecker = false;
                                            }
                                        }

                                    }

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

                                    }
                                });


                            }

                        }
                    });

                }
            };
        postList.setAdapter(firebaseRecyclerAdapter);
        firebaseRecyclerAdapter.startListening();
    }

    public static class PostsViewHolder extends RecyclerView.ViewHolder {
        View mView;
        ImageButton LikePostButton, CommentPostButton;
        TextView DisplayNoOfLikes;
        int countLikes;
        String currentUserID;
        DatabaseReference LikesRef;

        public PostsViewHolder(@NonNull View itemView) {
            super(itemView);
            mView = itemView;

            LikePostButton = (ImageButton) mView.findViewById(R.id.like_button);
            CommentPostButton = (ImageButton) mView.findViewById(R.id.comment_button);
            DisplayNoOfLikes = (TextView) mView.findViewById(R.id.display_no_of_likes);

            LikesRef = FirebaseDatabase.getInstance().getReference().child("Likes");
            currentUserID = FirebaseAuth.getInstance().getCurrentUser().getUid();
        }

        public void setLikeButtonStatus(final String PostKey) {
            LikesRef.addValueEventListener(new ValueEventListener() {
                @Override
                public void onDataChange(@NonNull DataSnapshot dataSnapshot) {
                    if (dataSnapshot.child(PostKey).hasChild(currentUserID)) {
                        countLikes = (int) dataSnapshot.child(PostKey).getChildrenCount();
                        LikePostButton.setImageResource(R.drawable.like);
                        DisplayNoOfLikes.setText(Integer.toString(countLikes) + (" Likes"));
                    } else {
                        countLikes = (int) dataSnapshot.child(PostKey).getChildrenCount();
                        LikePostButton.setImageResource(R.drawable.dislike);
                        DisplayNoOfLikes.setText(Integer.toString(countLikes) + (" Likes"));

                    }
                }


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

                }
            });

        }
        public void setName(String name) {
            TextView username = (TextView) mView.findViewById(R.id.post_user_name);
            username.setText(name);
        }
        public void setTime(String time) {
            TextView PostTime = (TextView) mView.findViewById(R.id.post_time);
            PostTime.setText(" " + time);
        }
        public void setDate(String date) {
            TextView PostDate = (TextView) mView.findViewById(R.id.post_date);
            PostDate.setText(" " + date);
        }
        public void setDescription(String description) {
            TextView PostDescription = (TextView) mView.findViewById(R.id.post_question);
            PostDescription.setText(description);
        }
        public void setPostimage(Context ctx, String postimage) {
            ImageView PostImage = (ImageView) mView.findViewById(R.id.post_image);
            Picasso.get().load(postimage).into(PostImage);
            //   Glide.with(ctx).load(postimage).into(PostImage);
        }
    }


    private void SendUserToPostActivity() {
        Intent addNewPostIntent = new Intent(MainActivity.this, PostActivity.class);
        startActivity(addNewPostIntent);
    }

    protected void onStart() {
        super.onStart();

        FirebaseUser currentUser = firebaseAuth.getCurrentUser();

        if (currentUser == null) {
            SendUserToLoginActivity();
        } else {
            CheckUserExistence();
        }
    }

    private void CheckUserExistence() {
        final String current_user_id = firebaseAuth.getCurrentUser().getUid();
        UsersRef.addValueEventListener(new ValueEventListener() {
            @Override
            public void onDataChange(@NonNull DataSnapshot dataSnapshot) {
                if (!dataSnapshot.hasChild(current_user_id)) {
                    SendUserToSetupActivity();
                }
            }

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

            }
        });
    }

    private void SendUserToSetupActivity() {
        Intent setupIntent = new Intent(MainActivity.this, SetupActivity.class);
        setupIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TASK);
        startActivity(setupIntent);
        finish();
    }

    private void SendUserToLoginActivity() {
        Intent loginIntent = new Intent(MainActivity.this, LoginActivity.class);
        loginIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TASK);
        startActivity(loginIntent);
        finish();
    }

    private void SendUserToProfileActivity() {
        Intent profileIntent = new Intent(MainActivity.this, ProfileActivity.class);
        startActivity(profileIntent);
    }

    private void SendUserToAboutUsActivity() {
        Intent AboutUsIntent = new Intent(MainActivity.this, AboutUs.class);
        startActivity(AboutUsIntent);
    }
    private void SendUserToContactUsActivity() {
        Intent AboutUsIntent = new Intent(MainActivity.this, ContactUs.class);
        startActivity(AboutUsIntent);
    }

    public boolean onOptionsItemSelected(MenuItem item) {
        if (actionBarDrawerToggle.onOptionsItemSelected(item)) {
            return true;
        }
        return super.onOptionsItemSelected(item);
    }

    private void UserMenuSelector(MenuItem item) {
        switch (item.getItemId()) {
            case R.id.nav_post:
                SendUserToPostActivity();
                break;
            case R.id.nav_menu1:
                Toast.makeText(this, "Home", Toast.LENGTH_SHORT).show();
                break;
            case R.id.nav_menu2:
                Toast.makeText(this, "Discussion FOrum", Toast.LENGTH_SHORT).show();
                break;
            case R.id.nav_menu3:
                SendUserToProfileActivity();
                break;
            case R.id.nav_menu4:
                SendUserToAboutUsActivity();
                break;
            case R.id.nav_menu5:
                Intent sendIntent = new Intent();
                sendIntent.setAction(Intent.ACTION_SEND);
                sendIntent.putExtra(Intent.EXTRA_TEXT, "PICT Placement.\n Forum to create awareness...\nLink:
                    https: //github.com/pragyagupta1898");
                    sendIntent.setType("text/plain"); startActivity(sendIntent); Toast.makeText(this, "Share", Toast.LENGTH_SHORT).show();
                    break;
                    case R.id.nav_contact:
                        SendUserToContactUsActivity();
                        break;
                    case R.id.nav_logout:
                        firebaseAuth.signOut(); SendUserToLoginActivity();
                        break;

                }
        }
    }

错误在这里:

if(dataSnapshot.child(PostKey).hasChild(currentUserID)) 

上面写着:

参数 'PostKey' 可能为 null ... (Ctrl+F1) 此检查分析方法控制和数据流,以报告始终为真或假的可能条件、其值被静态证明为常数的表达式以及可能导致可空性合同违规的情况。 标记为@Nullable 或@NotNull 的变量、方法参数和返回值被视为可空(或分别为非空),并在分析期间用于检查可空性合同,例如报告可能产生的 NullPointerException (NPE) 错误。 更复杂的合约可以使用@Contract 注解来定义,例如: @Contract(", null - null") — 如果方法的第二个参数为 null,则方法返回 null @Contract(", null - null; _, !null - !null") — 如果方法返回 null它的第二个参数是 null 并且不是 null 否则 @Contract("true - fail") — 一个典型的 assertFalse 方法,如果将 true 传递给它则抛出异常 可以将检查配置为使用自定义 @Nullable @NotNull 注解(默认使用 annotations.jar 中的注解)

如何解决?

【问题讨论】:

    标签: android firebase


    【解决方案1】:

    这不是错误,而是警告。

    由于您似乎没有阅读您引用的警告,我将解释一下:

    DataSnapshot.child() 方法有一个@Nullable 标志,这意味着它可能会返回null。由于您直接在该方法的结果上调用某些内容,Android Studio 只是告诉您,由于 child() 可以为 null,因此在其上运行 hasChild() 可能会导致 NullPointerException。

    要么检查 null 状态,要么忽略它。

    【讨论】:

    • 很抱歉应用程序崩溃了,因此我们不能忽略它。
    • @PragyaGupta 所以你需要在调用它的方法之前检查它是否为空。
    【解决方案2】:

    试试这样的。

    if((PostKey != null) && dataSnapshot.child(PostKey).hasChild(currentUserID)) 
    

    您也可以编写它以便处理 null 情况

    if (PostKey == null)  //do somthing
    else if (dataSnapshot.child(PostKey).hasChild(currentUserID)) //do something
    else //do something
    

    【讨论】:

      【解决方案3】:

      如果您在出现此警告时调试您的应用程序,您会发现 mUserID = null, 所以你只需要初始化它:

      mUserID = mAuth.getCurrentUser().getUid();
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2021-04-02
        • 1970-01-01
        • 1970-01-01
        • 2021-07-03
        • 2014-01-22
        • 1970-01-01
        相关资源
        最近更新 更多