图像按钮上的 NullPointerException
NullPointerException on Image button
每当我点击添加 post 按钮时,都会出现
错误
java.lang.NullPointerException: Attempt to invoke virtual method 'void android.widget.ImageButton.setOnClickListener(android.view.View$OnClickListener)' on a null object reference
我不知道为什么;我反复检查代码,但没有发现任何错误。
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);
}
}
XML 文件:
<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>
您在 ID 属性 中缺少 +
。应该是 android:id="@+id/select_post_image"
ref :
<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" />
每当我点击添加 post 按钮时,都会出现
错误java.lang.NullPointerException: Attempt to invoke virtual method 'void android.widget.ImageButton.setOnClickListener(android.view.View$OnClickListener)' on a null object reference
我不知道为什么;我反复检查代码,但没有发现任何错误。
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);
}
}
XML 文件:
<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>
您在 ID 属性 中缺少 +
。应该是 android:id="@+id/select_post_image"
ref :
<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" />