在下面的代码中,问题在于无法从Firebase检索数据,并且一旦我运行它,它将自动崩溃。在这里,我想将Firebase中的数据与图像日期,时间和描述一起检索到XML活动中。但是当我在不获取数据的情况下运行代码时,当我添加获取的数据代码时,它就可以正常工作。
package com.example.user.carapplication;
import android.content.Context;
import android.content.Intent;
import android.support.annotation.NonNull;
import android.support.design.widget.FloatingActionButton;
import android.support.design.widget.NavigationView;
import android.support.design.widget.Snackbar;
import android.support.v4.view.GravityCompat;
import android.support.v4.widget.DrawerLayout;
import android.support.v7.app.ActionBarDrawerToggle;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.support.v7.widget.Toolbar;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;
import com.firebase.ui.database.FirebaseRecyclerAdapter;
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.squareup.picasso.Picasso;
import de.hdodenhof.circleimageview.CircleImageView;
public class OwnerDrawer extends AppCompatActivity
implements NavigationView.OnNavigationItemSelectedListener {
private FirebaseAuth OwnerAuth;
private DatabaseReference OwnerRef, PostsRef;
private CircleImageView OwnNavProfileImge;
private TextView OwnNavProfileName;
String currentUserID;
private NavigationView navigationView;
private RecyclerView postList;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_owner_drawer);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
OwnerAuth = FirebaseAuth.getInstance();
OwnerRef = FirebaseDatabase.getInstance().getReference().child("Users").child("Owners");
currentUserID = OwnerAuth.getCurrentUser().getUid();
PostsRef = FirebaseDatabase.getInstance().getReference().child("Posts");
FloatingActionButton fab = (FloatingActionButton) findViewById(R.id.fab);
fab.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
Snackbar.make(view, "Replace with your own action", Snackbar.LENGTH_LONG)
.setAction("Action", null).show();
}
});
//for the navigation drawer button to open and close
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();
navigationView = (NavigationView) findViewById(R.id.nav_view);
navigationView.setNavigationItemSelectedListener(this);
postList = (RecyclerView)findViewById(R.id.OwnerPostCars);
postList.setHasFixedSize(true);
LinearLayoutManager linearLayoutManager = new LinearLayoutManager(this);
linearLayoutManager.setReverseLayout(true);
linearLayoutManager.setStackFromEnd(true);
postList.setLayoutManager(linearLayoutManager);
View navView = navigationView.inflateHeaderView(R.layout.nav_header_owner_drawer);
OwnNavProfileName = (TextView)navView.findViewById(R.id.NavOwnerUserName);
OwnNavProfileImge = (CircleImageView)navView.findViewById(R.id.NavOwnerProfileImage);
OwnerRef.child(currentUserID).addValueEventListener(new ValueEventListener() {
@Override
public void onDataChange(DataSnapshot dataSnapshot)
{
if(dataSnapshot.exists()) {
if(dataSnapshot.hasChild("fullname"))
{
String fullname = dataSnapshot.child("fullname").getValue().toString();
OwnNavProfileName.setText(fullname);
}
if(dataSnapshot.hasChild("profileimage"))
{
String image = dataSnapshot.child("profileimage").getValue().toString();
Picasso.with(OwnerDrawer.this).load(image).placeholder(R.drawable.profile).into(OwnNavProfileImge);
}
else
{
Toast.makeText(OwnerDrawer.this, "Profile name does not exist...", Toast.LENGTH_SHORT).show();
}
}
}
@Override
public void onCancelled(@NonNull DatabaseError databaseError) {
}
});
DisplayAllCarsPost();
}
public void DisplayAllCarsPost()
{
FirebaseRecyclerAdapter<Posts, PostsViewHolder> firebaseRecyclerAdapter =
new FirebaseRecyclerAdapter<Posts, PostsViewHolder>
(
Posts.class,
R.layout.posted_cars,
PostsViewHolder.class,
PostsRef
)
{
@Override
protected void populateViewHolder(PostsViewHolder viewHolder, Posts model, int position)
{
viewHolder.setFullname(model.getFullname());
viewHolder.setTime(model.getTime());
viewHolder.setDate(model.getDate());
viewHolder.setDescription(model.getDescription());
viewHolder.setProfileimage(getApplicationContext(), model.getProfileimage());
viewHolder.setPostimage(getApplicationContext(), model.getPostimage());
}
};
postList.setAdapter(firebaseRecyclerAdapter);
}
public static class PostsViewHolder extends RecyclerView.ViewHolder
{
View mView;
public PostsViewHolder(View itemView) {
super(itemView);
mView = itemView;
}
public void setFullname(String fullname)
{
TextView username = (TextView) mView.findViewById(R.id.post_profile_username);
username.setText(fullname);
}
public void setProfileimage(Context ctx, String profileimage)
{
CircleImageView image = (CircleImageView) mView.findViewById(R.id.PostCircularImageView);
Picasso.with(ctx).load(profileimage).into(image);
}
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.car_description);
PostDescription.setText(description);
}
public void setPostimage(Context ctx1, String postimage)
{
ImageView PostImage = (ImageView) mView.findViewById(R.id.car_post_image);
Picasso.with(ctx1).load(postimage).into(PostImage);
}
}
@Override
protected void onStart() {
super.onStart();
FirebaseUser currentUser = OwnerAuth.getCurrentUser();
if(currentUser == null)
{
SendUserTologinActivity();
}
else
{
CheckUserExistence();
}
}
// to see if the user validation and his authenticated so if not, the user will be send to the setup activity.
private void CheckUserExistence()
{
final String current_user_id = OwnerAuth.getCurrentUser().getUid();
OwnerRef.addValueEventListener(new ValueEventListener() {
@Override
public void onDataChange(DataSnapshot dataSnapshot)
{
if(!dataSnapshot.hasChild(current_user_id))
{
SendUserToSetupActivity();
}
}
@Override
public void onCancelled(DatabaseError databaseError) {
}
});
}
private void SendUserToSetupActivity()
{
Intent setupIntent = new Intent(OwnerDrawer.this, OwnerSetup.class);
setupIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TASK);
startActivity(setupIntent);
finish();
}
private void SendUserToSettingsActivity()
{
Intent settingsIntent = new Intent(OwnerDrawer.this, OwnerSettings.class);
settingsIntent .addFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TASK);
startActivity(settingsIntent );
finish();
}
private void SendUserTologinActivity() {
Intent loginIntent = new Intent(OwnerDrawer.this,OwnerLogin.class);
loginIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TASK);
startActivity(loginIntent);
finish();
}
private void SendUserToOwnerPost() {
Intent PostIntent = new Intent(OwnerDrawer.this,OwnerPost.class);
PostIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TASK);
startActivity(PostIntent);
finish();
}
private void SendUserToOwnerHome() {
Intent HomeIntent = new Intent(OwnerDrawer.this,OwnerDrawer.class);
HomeIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TASK);
startActivity(HomeIntent);
finish();
}
@Override
public void onBackPressed() {
DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
if (drawer.isDrawerOpen(GravityCompat.START)) {
drawer.closeDrawer(GravityCompat.START);
} else {
super.onBackPressed();
}
}
@SuppressWarnings("StatementWithEmptyBody")
@Override
public boolean onNavigationItemSelected(MenuItem item) {
// Handle navigation view item clicks here.
int id = item.getItemId();
if (id == R.id.nav_Home) {
SendUserToOwnerHome();
} else if (id == R.id.nav_Profile) {
Toast.makeText(this, "Profile", Toast.LENGTH_SHORT).show();
} else if (id == R.id.nav_Posting_Cars) {
SendUserToOwnerPost();
} else if (id == R.id.nav_Chat) {
Toast.makeText(this, "Chat", Toast.LENGTH_SHORT).show();
} else if (id == R.id.nav_Edit_profile) {
SendUserToSettingsActivity();
Toast.makeText(this, "Edit Profile", Toast.LENGTH_SHORT).show();
}
else if (id == R.id.nav_Logout) {
OwnerAuth.signOut();
SendUserTologinActivity();
Toast.makeText(OwnerDrawer.this, "Logged Out Successfull...", Toast.LENGTH_SHORT).show();
}
DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
drawer.closeDrawer(GravityCompat.START);
return true;
}
}
**The Post Class where the getters and setters methods**
package com.example.user.carapplication;
public class Posts
{
public String uid, time, date, postimage, description, profileimage, fullname;
public Posts(String uid, String time, String date, String postimage, String description, String profileimage, String fullname) {
this.uid = uid;
this.time = time;
this.date = date;
this.postimage = postimage;
this.description = description;
this.profileimage = profileimage;
this.fullname = fullname;
}
public String getUid() {
return uid;
}
public void setUid(String uid) {
this.uid = uid;
}
public String getTime() {
return time;
}
public void setTime(String time) {
this.time = time;
}
public String getDate() {
return date;
}
public void setDate(String date) {
this.date = date;
}
public String getPostimage() {
return postimage;
}
public void setPostimage(String postimage) {
this.postimage = postimage;
}
public String getDescription() {
return description;
}
public void setDescription(String description) {
this.description = description;
}
public String getProfileimage() {
return profileimage;
}
public void setProfileimage(String profileimage) {
this.profileimage = profileimage;
}
public String getFullname() {
return fullname;
}
public void setFullname(String fullname) {
this.fullname = fullname;
}
}
<?xml version="1.0" encoding="utf-8"?>
<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:id="@+id/post_profile_image"
android:layout_width="match_parent"
android:layout_height="wrap_content">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginBottom="4dp"
android:layout_marginLeft="10dp"
android:layout_marginRight="10dp"
android:layout_marginTop="10dp"
android:orientation="vertical">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginTop="1dp"
android:orientation="horizontal"
android:padding="5dp">
<de.hdodenhof.circleimageview.CircleImageView
android:id="@+id/PostCircularImageView"
android:layout_width="60dp"
android:layout_height="60dp"
android:layout_marginEnd="8dp"
android:layout_marginLeft="8dp"
android:layout_marginRight="8dp"
android:layout_marginStart="8dp"
android:layout_marginTop="8dp"
android:scaleType="centerCrop"
android:src="@drawable/profile"
app:layout_constraintEnd_toStartOf="@+id/linearLayout2"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent" />
<LinearLayout
android:layout_width="240dp"
android:layout_height="63dp"
android:layout_marginBottom="8dp"
android:layout_marginTop="8dp"
android:orientation="vertical"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintTop_toTopOf="parent"
app:layout_constraintVertical_bias="0.0">
<TextView
android:id="@+id/post_profile_username"
android:layout_width="214dp"
android:layout_height="wrap_content"
android:layout_gravity="start"
android:layout_marginLeft="5dp"
android:layout_marginTop="8dp"
android:text="user name"
android:textAlignment="textStart"
android:textSize="16sp"
android:textStyle="bold" />
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginLeft="5dp"
android:orientation="horizontal"
android:padding="2dp">
<TextView
android:id="@+id/Post_text"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Has Posted A new Car"
android:textColor="@android:color/darker_gray"
android:textSize="13sp"
android:textStyle="bold" />
<TextView
android:id="@+id/Post_date"
android:layout_width="30dp"
android:layout_height="wrap_content"
android:text="Date"
android:textColor="@android:color/black"
android:textSize="13sp" />
<TextView
android:id="@+id/Post_time"
android:layout_width="30dp"
android:layout_height="wrap_content"
android:text="Time"
android:textColor="@android:color/black"
android:textSize="13sp" />
</LinearLayout>
</LinearLayout>
</LinearLayout>
<TextView
android:id="@+id/car_description"
android:layout_width="match_parent"
android:layout_height="50dp"
android:layout_marginLeft="3dp"
android:layout_marginRight="3dp"
android:padding="3dp"
android:text="Car Description"
android:textColor="@android:color/black"
android:textSize="14sp" />
<ImageView
android:id="@+id/car_post_image"
android:layout_width="match_parent"
android:layout_height="200dp"
android:layout_margin="3dp"
android:adjustViewBounds="true"
android:scaleType="centerCrop"/>
</LinearLayout>
</RelativeLayout>
My Logcat
---------
08-19 17:36:56.265 9271-9271/? E/Zygote: isWhitelistProcess - Process is Whitelisted
08-19 17:36:56.269 9271-9271/? W/SELinux: SELinux selinux_android_compute_policy_index : Policy Index[2], Con:u:r:zygote:s0 RAM:SEPF_SM-G955F_8.0.0_0013, [-1 -1 -1 -1 0 1]
08-19 17:36:56.271 9271-9271/? I/SELinux: SELinux: seapp_context_lookup: seinfo=untrusted, level=s0:c512,c768, pkgname=com.example.user.carapplication
08-19 17:36:56.350 9271-9271/? I/zygote64: Late-enabling -Xcheck:jni
08-19 17:36:56.610 9271-9271/? D/ActivityThread: Added TimaKeyStore provider
08-19 17:36:56.915 9271-9332/? I/vndksupport: sphal namespace is not configured for this process. Loading /vendor/lib64/egl/libGLES_mali.so from the current namespace instead.
08-19 17:36:56.971 9271-9332/? D/libEGL: loaded /vendor/lib64/egl/libGLES_mali.so
08-19 17:36:57.177 9271-9271/? D/FirebaseApp: com.google.firebase.crash.FirebaseCrash is not linked. Skipping initialization.
08-19 17:36:57.241 9271-9271/? I/FirebaseInitProvider: FirebaseApp initialization successful
08-19 17:36:57.244 9271-9271/? I/InstantRun: starting instant run server: is main process
08-19 17:36:57.270 9271-9368/? I/FA: App measurement is starting up, version: 12451
To enable debug logging run: adb shell setprop log.tag.FA VERBOSE
08-19 17:36:57.271 9271-9368/? I/FA: To enable faster debug mode event logging run:
adb shell setprop debug.firebase.analytics.app com.example.user.carapplication
08-19 17:36:57.271 9271-9368/? D/FA: Debug-level message logging enabled
08-19 17:36:58.057 9271-9271/? D/AndroidRuntime: Shutting down VM
08-19 17:36:58.063 9271-9271/? E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.example.user.carapplication, PID: 9271
java.lang.RuntimeException: Unable to start activity ComponentInfo{com.example.user.carapplication/com.example.user.carapplication.OwnerDrawer}: java.lang.NullPointerException: Attempt to invoke virtual method 'void android.support.design.widget.FloatingActionButton.setOnClickListener(android.view.View$OnClickListener)' on a null object reference
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2955)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:3030)
at android.app.ActivityThread.-wrap11(Unknown Source:0)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1696)
at android.os.Handler.dispatchMessage(Handler.java:105)
at android.os.Looper.loop(Looper.java:164)
at android.app.ActivityThread.main(ActivityThread.java:6938)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.Zygote$MethodAndArgsCaller.run(Zygote.java:327)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1374)
Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'void android.support.design.widget.FloatingActionButton.setOnClickListener(android.view.View$OnClickListener)' on a null object reference
at com.example.user.carapplication.OwnerDrawer.onCreate(OwnerDrawer.java:64)
at android.app.Activity.performCreate(Activity.java:7183)
at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1220)
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2908)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:3030)
at android.app.ActivityThread.-wrap11(Unknown Source:0)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1696)
at android.os.Handler.dispatchMessage(Handler.java:105)
at android.os.Looper.loop(Looper.java:164)
at android.app.ActivityThread.main(ActivityThread.java:6938)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.Zygote$MethodAndArgsCaller.run(Zygote.java:327)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1374)
08-19 17:36:58.106 9271-9271/? I/Process: Sending signal. PID: 9271 SIG: 9
答案 0 :(得分:0)
您的.rodata1
XML是否有ID为activity_owner_drawer
的{{1}}?
好像下面一行返回FloatingActionButton
。
fab
依次将null
投向下面一行。
FloatingActionButton fab = (FloatingActionButton) findViewById(R.id.fab);