谁能帮我解决这个空指针代码,因为我是编程新手

时间:2018-09-17 16:46:36

标签: java android android-studio nullpointerexception

这是在我通过设置活动从Firebase调用用户个人资料图像时发生的。

public class MainActivity extends AppCompatActivity {
    private NavigationView navigationView;
    private DrawerLayout drawerLayout;
    private ActionBarDrawerToggle actionBarDrawerToggle;
    private RecyclerView postList;
    private Toolbar mToolbar;
    private FirebaseAuth mAuth;
    private CircleImageView NavProfileImage;
    private TextView NavProfileUserName;

    private DatabaseReference UsersRef;

    String currentUsersID;

    @Override
    protected void onCreate(Bundle savedInstanceState) {

        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        mAuth = FirebaseAuth.getInstance();
        currentUsersID = mAuth.getCurrentUser().getUid();
        UsersRef = FirebaseDatabase.getInstance().getReference().child("Users");

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

        drawerLayout = (DrawerLayout) findViewById(R.id.drawable_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);

        View navView = navigationView.inflateHeaderView(R.layout.navigation_header);
        NavProfileImage = (CircleImageView) navView.findViewById(R.id.nav_profile_image);
        NavProfileUserName = (TextView) navView.findViewById(R.id.nav_user_full_name);

        UsersRef.child(currentUsersID).addValueEventListener(new ValueEventListener() {
            @Override
            public void onDataChange(DataSnapshot dataSnapshot) {

                if (dataSnapshot.exists()) {
                    if (dataSnapshot.hasChild("fullname")) {
                        String fullname = dataSnapshot.child("fullname").getValue().toString();
                        NavProfileUserName.setText(fullname);
                    }
                    if (dataSnapshot.hasChild("profileimage")) {
                        String image = dataSnapshot.child("profileimage").getValue().toString();
                        Picasso.get().load(image).placeholder(R.drawable.profile).into(NavProfileImage);
                    } else {
                        Toast.makeText(MainActivity.this, "Profile name do not exists...", Toast.LENGTH_SHORT).show();
                    }
                }
            }

            @Override
            public void onCancelled(DatabaseError databaseError) {

            }
        });


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

这是我的设置活动,用户在其中输入数据。效果很好,但是当我尝试在主要活动中将此数据加载到导航抽屉中时,该应用程序在安装后将无法启动。

    private EditText UserName, FullName, CountryName;
private Button SaveInformationButton;
private CircleImageView ProfileImage;
private ProgressDialog loadingBar;
private FirebaseAuth mAuth;
private DatabaseReference UsersRef;
private StorageReference UserProfileImageRef;


String currentUserID;
final static int Gallery_Pick = 1;

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

    mAuth = FirebaseAuth.getInstance();
    currentUserID = mAuth.getCurrentUser().getUid();
    UsersRef = FirebaseDatabase.getInstance().getReference().child(currentUserID);
    UserProfileImageRef = FirebaseStorage.getInstance().getReference().child("Profile Images");



    UserName = (EditText) findViewById(R.id.setup_username);
    FullName = (EditText) findViewById(R.id.setup_full_name);
    CountryName = (EditText) findViewById(R.id.setup_country_name);
    SaveInformationButton = (Button) findViewById(R.id.setup_information_button);
    ProfileImage = (CircleImageView) findViewById(R.id.setup_profile_image);
    loadingBar = new ProgressDialog(this);

    SaveInformationButton.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v)
        {
            SaveAccountSetupInformation();

        }
    });

    ProfileImage.setOnClickListener(new View.OnClickListener()
    {
        @Override
        public void onClick(View v)
        {
            Intent galleryIntent = new Intent();
            galleryIntent.setAction(Intent.ACTION_GET_CONTENT);
            galleryIntent.setType("image/*");
            startActivityForResult(galleryIntent, Gallery_Pick);

        }
    });

    UsersRef.addValueEventListener(new ValueEventListener() {
        @Override
        public void onDataChange(DataSnapshot dataSnapshot)
        {
            if (dataSnapshot.exists())
            {
                String image = dataSnapshot.child("profileimage").getValue().toString();
                Picasso.get().load(image).placeholder(R.drawable.profile).into(ProfileImage);


            }

        }

        @Override
        public void onCancelled(DatabaseError databaseError) {

        }
    });


}

@Override
protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data)
{
    super.onActivityResult(requestCode, resultCode, data);
    if (requestCode == Gallery_Pick && resultCode==RESULT_OK && data != null)
    {
        Uri ImageUri = data.getData();

        CropImage.activity()
                .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)
        {
            loadingBar.setTitle("Profile Image");
            loadingBar.setMessage("Please Wait While We Are Updating Your Profile Image");
            loadingBar.show();
            loadingBar.setCanceledOnTouchOutside(true);

            Uri resultUri = result.getUri();

            StorageReference filePath = UserProfileImageRef.child(currentUserID + ".jpg");

            filePath.putFile(resultUri).addOnCompleteListener(new OnCompleteListener<UploadTask.TaskSnapshot>()
            {
                @Override
                public void onComplete(@NonNull Task<UploadTask.TaskSnapshot> task)
                {
                    if (task.isSuccessful())
                    {
                        Toast.makeText(SetuActivity.this, "Profile Image Is Added Successfully", Toast.LENGTH_SHORT).show();

                        final String downloadUrl = task.getResult().getDownloadUrl().toString();

                        UsersRef.child("profileimage").setValue(downloadUrl)
                                .addOnCompleteListener(new OnCompleteListener<Void>()
                                {
                                    @Override
                                    public void onComplete(@NonNull Task<Void> task)
                                    {
                                        if (task.isSuccessful())
                                        {
                                            Intent selfIntent = new Intent(SetuActivity.this, SetuActivity.class);
                                            startActivity(selfIntent);


                                            Toast.makeText(SetuActivity.this, "Profile Image Stored To Firebase Database Successfully", Toast.LENGTH_SHORT).show();
                                            loadingBar.dismiss();

                                        }
                                        else
                                        {
                                            String message = task.getException().getMessage();
                                            Toast.makeText(SetuActivity.this, "Error Occured: " + message, Toast.LENGTH_SHORT).show();
                                            loadingBar.dismiss();
                                        }

                                    }
                                });
                    }

                }
            });

        }
        else
        {
            Toast.makeText(this, "Error Occured: Image can't be cropped, Try Again.", Toast.LENGTH_SHORT).show();
            loadingBar.dismiss();
        }
    }
}

这是我每次运行程序时收到的错误消息。

W/dalvikvm: threadid=1: calling UncaughtExceptionHandler
E/AndroidRuntime: FATAL EXCEPTION: main
                  Process: com.sample, PID: 27888
                  java.lang.RuntimeException: Unable to start activity ComponentInfo{com.sample/com.sample.MainActivity}: java.lang.NullPointerException
                      at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2389)
                      at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2441)
                      at android.app.ActivityThread.access$900(ActivityThread.java:151)
                      at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1354)
                      at android.os.Handler.dispatchMessage(Handler.java:110)
                      at android.os.Looper.loop(Looper.java:193)
                      at android.app.ActivityThread.main(ActivityThread.java:5345)
                      at java.lang.reflect.Method.invokeNative(Native Method)
                      at java.lang.reflect.Method.invoke(Method.java:515)
                      at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:828)
                      at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:644)
                      at dalvik.system.NativeStart.main(Native Method)
                   Caused by: java.lang.NullPointerException
                      at com.sample..MainActivity.onCreate(MainActivity.java:55)
                      at android.app.Activity.performCreate(Activity.java:5343)
                      at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1088)
                      at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2343)
                      at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2441) 
                      at android.app.ActivityThread.access$900(ActivityThread.java:151) 
                      at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1354) 
                      at android.os.Handler.dispatchMessage(Handler.java:110) 
                      at android.os.Looper.loop(Looper.java:193) 
                      at android.app.ActivityThread.main(ActivityThread.java:5345) 
                      at java.lang.reflect.Method.invokeNative(Native Method) 
                      at java.lang.reflect.Method.invoke(Method.java:515) 
                      at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:828) 
                      at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:644) 
                      at dalvik.system.NativeStart.main(Native Method) 
Application terminated.

字符串函数是问题所在。因为每当我从代码中删除它时,该应用程序都能完美运行而不会崩溃。我不知道如何在这里问问题,所以请原谅我的错误,对于造成的延迟,我们深表歉意。

0 个答案:

没有答案