Warning: file_get_contents(/data/phpspider/zhask/data//catemap/3/android/207.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Java 图像上的NullPointerException按钮_Java_Android_Xml_Nullreferenceexception - Fatal编程技术网

Java 图像上的NullPointerException按钮

Java 图像上的NullPointerException按钮,java,android,xml,nullreferenceexception,Java,Android,Xml,Nullreferenceexception,每当我点击AddPost按钮时,它都会给出 java.lang.NullPointerException:尝试对空对象引用调用虚拟方法“void android.widget.ImageButton.setOnClickListener(android.view.view$OnClickListener)” 我不知道为什么;我一遍又一遍地检查代码,但没有发现任何错误 public class PostActivity extends AppCompatActivity { private

每当我点击AddPost按钮时,它都会给出

java.lang.NullPointerException:尝试对空对象引用调用虚拟方法“void android.widget.ImageButton.setOnClickListener(android.view.view$OnClickListener)”

我不知道为什么;我一遍又一遍地检查代码,但没有发现任何错误

public class PostActivity extends AppCompatActivity {
    private Toolbar mToolbar;
    private ImageButton SelectPostImage;
    private Button UpdatePostBtn;
    private ProgressDialog loadingBar;
    private EditText postDescription;
    private static int Gallery_Pick = 1;
    private Uri imageUri;
    private String description;
    private FirebaseAuth mAuth;
    private DatabaseReference userRef, postRef;
    private StorageReference postImagesRef;
    private String saveCurrentDate;
    private String saveCurrentTime;
    private String postRandomName;
    private String downloadUrl, currentUserId;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        mAuth = FirebaseAuth.getInstance();
        currentUserId = mAuth.getCurrentUser().getUid();
        SelectPostImage = (ImageButton) findViewById(R.id.select_post_image);
        UpdatePostBtn = (Button) findViewById(R.id.update_post_button);
        postDescription = (EditText)  findViewById(R.id.post_description);
        postImagesRef = FirebaseStorage.getInstance().getReference();
        userRef = FirebaseDatabase.getInstance().getReference().child("Users");
        postRef = FirebaseDatabase.getInstance().getReference().child("Posts");
        loadingBar = new ProgressDialog(this);

        setContentView(R.layout.activity_post);
        mToolbar = (Toolbar) findViewById(R.id.update_post_page_toolbar);
        setSupportActionBar(mToolbar);
        getSupportActionBar().setDisplayHomeAsUpEnabled(true);
        getSupportActionBar().setDisplayShowHomeEnabled(true);
        getSupportActionBar().setTitle("Update Post");

        SelectPostImage.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                OpenGallery();
            }
        });

        UpdatePostBtn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                ValidatePostInfo();
            }
        });
    }

    private void ValidatePostInfo() {


        description = postDescription.getText().toString();
        if (imageUri == null)
        {
            Toast.makeText(this, "Please First Select The Picture By Clicking On The Above Picture", Toast.LENGTH_SHORT).show();
        }
        else if (TextUtils.isEmpty(description))
        {
            Toast.makeText(this, "Please Say Something About Picture", Toast.LENGTH_SHORT).show();
        }
        else
        {
            loadingBar.setTitle("Updating Post");
            loadingBar.setMessage("Please Wait While We Are Updating Your Post");
            loadingBar.show();
            loadingBar.setCanceledOnTouchOutside(true);

            StoringImageToFirebase();
        }
    }

    private void StoringImageToFirebase() {
        Calendar calForDATE = Calendar.getInstance();
        SimpleDateFormat currentDate = new SimpleDateFormat("dd-MMMM-yyyy");
        saveCurrentDate = currentDate.format(calForDATE.getTime());


        Calendar callForTime = Calendar.getInstance();
        SimpleDateFormat currentTime = new SimpleDateFormat("HH:mm");
        saveCurrentTime = currentTime.format(callForTime.getTime());

        postRandomName = saveCurrentDate+saveCurrentTime;
        StorageReference filePath = postImagesRef.child("PostImages").child(imageUri.getLastPathSegment() + postRandomName + ".jpg");
        filePath.putFile(imageUri).addOnCompleteListener(new OnCompleteListener<UploadTask.TaskSnapshot>() {
            @Override
            public void onComplete(@NonNull Task<UploadTask.TaskSnapshot> task) {
                if (task.isSuccessful())
                {
                    downloadUrl = task.getResult().getDownloadUrl().toString();
                    Toast.makeText(PostActivity.this, "Image Uploaded Successfully", Toast.LENGTH_SHORT).show();
                    SavingPostInformationToDatabase();
                }
                else
                {
                    String message = task.getException().getMessage();
                    Toast.makeText(PostActivity.this, "Error Occured" + message, Toast.LENGTH_SHORT).show();
                }
            }
        });
    }

    private void SavingPostInformationToDatabase() {
        userRef.child(currentUserId).addValueEventListener(new ValueEventListener() {
            @Override
            public void onDataChange(DataSnapshot dataSnapshot)
            {

                if (dataSnapshot.exists()){
                    String fullName = dataSnapshot.child("fullname").getValue().toString();
                    String userProfileImage = dataSnapshot.child("profileimage").getValue().toString();

                    HashMap postMap = new HashMap();
                    postMap.put("uid", currentUserId);
                    postMap.put("date", saveCurrentDate);
                    postMap.put("time", saveCurrentTime);
                    postMap.put("description", description);
                    postMap.put("postimage", downloadUrl);
                    postMap.put("profileimage", userProfileImage);
                    postMap.put("fullname", fullName);

                    postRef.child(currentUserId + postRandomName).updateChildren(postMap).addOnCompleteListener(new OnCompleteListener() {
                        @Override
                        public void onComplete(@NonNull Task task) {
                            if (task.isSuccessful())
                            {
                                Toast.makeText(PostActivity.this, "Post Updated Successfully", Toast.LENGTH_SHORT).show();
                                loadingBar.dismiss();
                            }
                            else
                            {
                                String message = task.getException().getMessage();
                                Toast.makeText(PostActivity.this, "Error Occurred" + message, Toast.LENGTH_SHORT).show();
                                loadingBar.dismiss();
                            }
                        }
                    });

                }

            }

            @Override
            public void onCancelled(DatabaseError databaseError) {

            }
        });
    }

    private void OpenGallery() {
        Intent galleryIntent = new Intent();
        galleryIntent.setAction(Intent.ACTION_GET_CONTENT);
        galleryIntent.setType("image/*");
        startActivityForResult(galleryIntent, Gallery_Pick);
    }

    @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)
        {
            imageUri = data.getData();
            SelectPostImage.setImageURI(imageUri);
        }
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {

        int id = item.getItemId();
        if (id == android.R.id.home)
        {
            sendUserToMainActivity();
        }
        return super.onOptionsItemSelected(item);
    }

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

}
公共类PostActivity扩展了AppCompative活动{
私有工具栏mToolbar;
私人图像按钮选择PostImage;
专用按钮更新机顶盒;
私有进程对话框加载栏;
私人编辑文字描述;
专用静态int库_Pick=1;
私有Uri-imageUri;
私有字符串描述;
私人消防队;
私有数据库引用userRef,postRef;
私有存储参考positmagesref;
私有字符串saveCurrentDate;
私有字符串saveCurrentTime;
私有字符串名称;
私有字符串下载URL,currentUserId;
@凌驾
创建时受保护的void(Bundle savedInstanceState){
super.onCreate(savedInstanceState);
mAuth=FirebaseAuth.getInstance();
currentUserId=mAuth.getCurrentUser().getUid();
选择PostImage=(图像按钮)findViewById(R.id.select\u post\u image);
UpdatePostBtn=(按钮)findViewById(R.id.update\u post\u按钮);
postDescription=(EditText)findViewById(R.id.post\u description);
postImagesRef=FirebaseStorage.getInstance().getReference();
userRef=FirebaseDatabase.getInstance().getReference().child(“用户”);
postRef=FirebaseDatabase.getInstance().getReference().child(“Posts”);
loadingBar=新建进度对话框(此对话框);
setContentView(R.layout.activity_post);
mToolbar=(工具栏)findViewById(R.id.update\u post\u page\u工具栏);
设置支持操作栏(mToolbar);
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
getSupportActionBar().setDisplayShowHomeEnabled(true);
getSupportActionBar().setTitle(“更新帖子”);
选择PostImage.setOnClickListener(新建视图.OnClickListener(){
@凌驾
公共void onClick(视图){
OpenGallery();
}
});
UpdatePostBtn.setOnClickListener(新视图.OnClickListener(){
@凌驾
公共void onClick(视图){
ValidatePostInfo();
}
});
}
私有void ValidatePostInfo(){
description=postDescription.getText().toString();
如果(imageUri==null)
{
Toast.makeText(这是“请首先通过单击上面的图片来选择图片”,Toast.LENGTH_SHORT.show();
}
else if(TextUtils.isEmpty(description))
{
Toast.makeText(这是“请谈谈图片”,Toast.LENGTH_SHORT.show();
}
其他的
{
loadingBar.setTitle(“更新帖子”);
loadingBar.setMessage(“请稍候,我们正在更新您的帖子”);
loadingBar.show();
loadingBar.SetCanceledOnTouchOut(真);
存储ImageToFirebase();
}
}
私有void存储ImageToFirebase(){
Calendar calForDATE=Calendar.getInstance();
SimpleDataFormat currentDate=新的SimpleDataFormat(“dd MMMM yyyy”);
saveCurrentDate=currentDate.format(calForDATE.getTime());
Calendar callForTime=Calendar.getInstance();
SimpleDataFormat currentTime=新的SimpleDataFormat(“HH:mm”);
saveCurrentTime=currentTime.format(callForTime.getTime());
postRandomName=saveCurrentDate+saveCurrentTime;
StorageReference文件路径=postImagesRef.child(“PostImages”).child(imageUri.getLastPathSegment()+postRandomName+“.jpg”);
filePath.putFile(imageUri).addOnCompleteListener(新的OnCompleteListener(){
@凌驾
未完成的公共void(@NonNull任务){
if(task.issusccessful())
{
downloadUrl=task.getResult().getDownloadUrl().toString();
Toast.makeText(PostActivity.this,“图像上传成功”,Toast.LENGTH_SHORT.show();
将PostInformation保存到数据库();
}
其他的
{
字符串消息=task.getException().getMessage();
Toast.makeText(PostActivity.this,“出错”+消息,Toast.LENGTH\u SHORT.show();
}
}
});
}
私有void保存PostInformation到数据库(){
userRef.child(currentUserId).addValueEventListener(新的ValueEventListener(){
@凌驾
公共void onDataChange(DataSnapshot DataSnapshot)
{
if(dataSnapshot.exists()){
字符串fullName=dataSnapshot.child(“fullName”).getValue().toString();
字符串userProfileImage=dataSnapshot.child(“profileimage”).getValue().toString();
HashMap postMap=新的HashMap();
postMap.put(“uid”,currentUserId);
邮戳放置(“日期”,保存当前日期);
邮戳放置(“时间”,saveCurrentTime);
邮戳投入(“说明”,说明);
postMap.put(“postmage”,下载URL);
postMap.put(“profileimage”,userProfileImage);
邮戳放置(“全名”,全名);
postRef.child(currentUserId+postRandomName).updateChildren(postMap).addOnCompleteListener(新的OnCompleteListener(){
@凌驾
未完成的公共void(@NonNull任务){
if(task.issusccessful())
{
Toast.makeText(PostActivity.this,“Post更新成功”,Toast.LENGTH_SHORT.show();
<RelativeLayout 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:layout_width="match_parent"
    android:padding="2dp"
    android:background="@color/colorPrimaryDark"
    android:layout_height="match_parent"
    tools:context=".PostActivity">

    <include layout="@layout/app_bar_layout"
        android:id="@+id/update_post_page_toolbar"/>

    <ImageButton
        android:id="@id/select_post_image"
        android:layout_width="match_parent"
        android:layout_height="300dp"
        android:layout_below="@id/update_post_page_toolbar"
        android:layout_alignParentTop="true"
        android:layout_centerHorizontal="true"
        android:layout_marginTop="50dp"
        app:srcCompat="@drawable/add_post_high" />

    <EditText
        android:id="@+id/post_description"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_below="@id/select_post_image"
        android:layout_marginTop="20dp"
        android:background="@drawable/inputa"
        android:ems="10"
        android:hint="Write Description Here"
        android:inputType="textMultiLine"
        android:padding="8dp"
        android:textColor="#000"
        android:textColorLink="#000"
        android:textStyle="bold|italic"
        android:typeface="serif" />

    <Button
        android:id="@+id/update_post_button"
        android:layout_width="wrap_content"
        android:layout_marginBottom="100dp"
        android:layout_marginTop="8dp"
        android:layout_alignParentBottom="true"
        android:layout_height="wrap_content"
        android:textColor="#000"
        android:textColorLink="#000"
        android:textStyle="bold|italic"
        android:typeface="serif"
        android:layout_below="@id/post_description"
        android:layout_centerHorizontal="true"
        android:text="Update Post" />
</RelativeLayout>
<RelativeLayout 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:layout_width="match_parent"
android:padding="2dp"
android:background="@color/colorPrimaryDark"
android:layout_height="match_parent"
tools:context=".PostActivity">
<include layout="@layout/app_bar_layout"
    android:id="@+id/update_post_page_toolbar"/>

<ImageButton
    android:id="@+id/select_post_image"
    android:layout_width="match_parent"
    android:layout_height="300dp"
    android:layout_below="@id/update_post_page_toolbar"
    android:layout_alignParentTop="true"
    android:layout_centerHorizontal="true"
    android:layout_marginTop="50dp"
    app:srcCompat="@drawable/add_post_high" />

<EditText
    android:id="@+id/post_description"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:layout_below="@id/select_post_image"
    android:layout_marginTop="20dp"
    android:background="@drawable/inputa"
    android:ems="10"
    android:hint="Write Description Here"
    android:inputType="textMultiLine"
    android:padding="8dp"
    android:textColor="#000"
    android:textColorLink="#000"
    android:textStyle="bold|italic"
    android:typeface="serif" />

<Button
    android:id="@+id/update_post_button"
    android:layout_width="wrap_content"
    android:layout_marginBottom="100dp"
    android:layout_marginTop="8dp"
    android:layout_alignParentBottom="true"
    android:layout_height="wrap_content"
    android:textColor="#000"
    android:textColorLink="#000"
    android:textStyle="bold|italic"
    android:typeface="serif"
    android:layout_below="@id/post_description"
    android:layout_centerHorizontal="true"
    android:text="Update Post" />