Java Firebase:应用程序未打开时发出通知时应用程序崩溃
我遵循这个教程 一切都进行得很顺利,只是在收到通知时我发现了一点问题,我的设备没有运行应用程序(后台模式),当我单击通知面板时,我的应用程序崩溃了 如果我的设备以前打开过应用程序,则不会发生此错误。当我单击通知面板时,应用程序正常运行并打开我的ProfileActivity 我得到了这个错误的错误日志Java Firebase:应用程序未打开时发出通知时应用程序崩溃,java,android,Java,Android,我遵循这个教程 一切都进行得很顺利,只是在收到通知时我发现了一点问题,我的设备没有运行应用程序(后台模式),当我单击通知面板时,我的应用程序崩溃了 如果我的设备以前打开过应用程序,则不会发生此错误。当我单击通知面板时,应用程序正常运行并打开我的ProfileActivity 我得到了这个错误的错误日志 07-29 16:36:54.512 16573-16573/? E/AndroidRuntime: FATAL EXCEPTION: main
07-29 16:36:54.512 16573-16573/? E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.bertho.chat, PID: 16573
java.lang.RuntimeException: Unable to start activity ComponentInfo{com.bertho.chat/com.bertho.chat.ProfileActivity}: java.lang.NullPointerException: Can't pass null for argument 'pathString' in child()
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2464)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2524)
at android.app.ActivityThread.access$900(ActivityThread.java:154)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1391)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:234)
at android.app.ActivityThread.main(ActivityThread.java:5526)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:726)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:616)
at de.robv.android.xposed.XposedBridge.main(XposedBridge.java:102)
Caused by: java.lang.NullPointerException: Can't pass null for argument 'pathString' in child()
at com.google.firebase.database.DatabaseReference.child(Unknown Source)
at com.bertho.chat.ProfileActivity.onCreate(ProfileActivity.java:56)
at android.app.Activity.performCreate(Activity.java:6285)
at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1108)
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2417)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2524)
at android.app.ActivityThread.access$900(ActivityThread.java:154)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1391)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:234)
at android.app.ActivityThread.main(ActivityThread.java:5526)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:726)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:616)
at de.robv.android.xposed.XposedBridge.main(XposedBridge.java:102)
这是我的ProfileActivity.java
public class ProfileActivity extends BaseActivity {
private ImageView mProfileImage;
private TextView mProfileName, mProfileStatus, mProfileFriendsCount;
private Toolbar mToolbar;
private Button mProfileSendReqBtn, mProfileDeclineReqBtn;
private ProgressDialog mDialog;
private FirebaseUser mCuurentUser;
private String mCuurent_state;
private DatabaseReference mUserDatabase, mFriendsReqDatabase, mFriendsDatabase, mNotificationDatabase;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate( savedInstanceState );
setContentView( R.layout.activity_profile );
final String user_id = getIntent().getStringExtra( "user_id" );
mDialog = new ProgressDialog( this );
mUserDatabase = FirebaseDatabase.getInstance().getReference().child( "Users" ).child( user_id );
mUserDatabase.keepSynced( true );
mFriendsReqDatabase = FirebaseDatabase.getInstance().getReference().child( "FriendsRequest" );
mFriendsReqDatabase.keepSynced( true );
mFriendsDatabase = FirebaseDatabase.getInstance().getReference().child( "FriendsData" );
mFriendsDatabase.keepSynced( true );
mNotificationDatabase = FirebaseDatabase.getInstance().getReference().child( "Notifications" );
mProfileImage = (ImageView) findViewById( R.id.profile_image );
mProfileName = (TextView) findViewById( R.id.profile_displayName );
mProfileStatus = (TextView) findViewById( R.id.profile_status );
mProfileFriendsCount = (TextView) findViewById( R.id.profile_totalFriends );
mProfileSendReqBtn = (Button) findViewById( R.id.profile_send_fr_btn );
mProfileDeclineReqBtn = (Button) findViewById( R.id.profile_decline_req_btn );
mCuurentUser = FirebaseAuth.getInstance().getCurrentUser();
showLoading( "Load Profile Data" );
mCuurent_state = "not_friends";
mUserDatabase.addValueEventListener( new ValueEventListener() {
@Override
public void onDataChange(DataSnapshot dataSnapshot) {
String display_name = dataSnapshot.child( "name" ).getValue().toString();
String display_status = dataSnapshot.child( "status" ).getValue().toString();
final String display_image = dataSnapshot.child( "image" ).getValue().toString();
mProfileName.setText( display_name );
mProfileStatus.setText( display_status );
if (mCuurent_state == "not_friends") {
mProfileDeclineReqBtn.setVisibility( View.INVISIBLE );
mProfileDeclineReqBtn.setEnabled( false );
} else if (mCuurent_state == "received") {
mProfileDeclineReqBtn.setVisibility( View.VISIBLE );
mProfileDeclineReqBtn.setEnabled( true );
} else {
mProfileDeclineReqBtn.setVisibility( View.INVISIBLE );
mProfileDeclineReqBtn.setEnabled( false );
}
/*Picasso.with( ProfileActivity.this )
.load( display_image )
.placeholder( R.drawable.no_profile )
.into( mProfileImage );*/
Picasso.with( ProfileActivity.this )
.load( display_image )
.networkPolicy( NetworkPolicy.OFFLINE )
.placeholder( R.drawable.no_profile )
.into( mProfileImage, new Callback() {
@Override
public void onSuccess() {
}
@Override
public void onError() {
Picasso.with( ProfileActivity.this )
.load( display_image )
.placeholder( R.drawable.no_profile )
.into( mProfileImage );
}
} );
// ========== FRIEND LIST ONLY FOR CURRENT USER LOGGED IN ==========
mFriendsReqDatabase.child( mCuurentUser.getUid() ).addListenerForSingleValueEvent( new ValueEventListener() {
@Override
public void onDataChange(DataSnapshot dataSnapshot) {
if (dataSnapshot.hasChild( user_id )) {
String req_type = dataSnapshot.child( user_id ).child( "request_type" ).getValue().toString();
if (req_type.equals( "received" )) {
mCuurent_state = "req_received";
mProfileSendReqBtn.setText( "Accept Friend Request" );
mProfileDeclineReqBtn.setVisibility( View.VISIBLE );
mProfileDeclineReqBtn.setEnabled( true );
} else if (req_type.equals( "sent" )) {
mCuurent_state = "req_sent";
mProfileSendReqBtn.setText( "Cancel Friend Request" );
mProfileSendReqBtn.setBackgroundColor( getResources().getColor( R.color.colorAccent ) );
mProfileDeclineReqBtn.setVisibility( View.INVISIBLE );
mProfileDeclineReqBtn.setEnabled( false );
}
} else {
/*Toast.makeText(getApplicationContext(), "TIDAK ADA : " + mCuurent_state, Toast.LENGTH_SHORT).show();*/
mFriendsDatabase.child( mCuurentUser.getUid() ).addListenerForSingleValueEvent( new ValueEventListener() {
@Override
public void onDataChange(DataSnapshot dataSnapshot) {
if (dataSnapshot.hasChild( user_id )) {
mCuurent_state = "friends";
mProfileSendReqBtn.setText( "Unfriend This Person" );
/*mProfileSendReqBtn.setEnabled( false );
mProfileSendReqBtn.setBackgroundColor( getResources().getColor( R.color.colorAccent ) );*/
mProfileDeclineReqBtn.setVisibility( View.INVISIBLE );
mProfileDeclineReqBtn.setEnabled( false );
}
}
@Override
public void onCancelled(DatabaseError databaseError) {
}
} );
}
mDialog.dismiss();
}
@Override
public void onCancelled(DatabaseError databaseError) {
}
} );
}
@Override
public void onCancelled(DatabaseError databaseError) {
}
} );
mProfileSendReqBtn.setOnClickListener( new View.OnClickListener() {
@Override
public void onClick(View view) {
// ========== ADD FRIEND REQUEST ==========
if (mCuurent_state.equals( "not_friends" )) {
showLoading( "Data is processing...!" );
mProfileSendReqBtn.setEnabled( false );
mFriendsReqDatabase.child( mCuurentUser.getUid() ).child( user_id ).child( "request_type" ).setValue( "sent" ).addOnCompleteListener( new OnCompleteListener<Void>() {
@Override
public void onComplete(@NonNull Task<Void> task) {
if (task.isSuccessful()) {
mFriendsReqDatabase.child( user_id ).child( mCuurentUser.getUid() ).child( "request_type" ).setValue( "received" ).addOnCompleteListener( new OnCompleteListener<Void>() {
@Override
public void onComplete(@NonNull Task<Void> task) {
if (task.isSuccessful()) {
HashMap<String, String> notificationData = new HashMap<>( );
notificationData.put( "from", mCuurentUser.getUid() );
notificationData.put( "type", "request" );
mNotificationDatabase.child( user_id ).push().setValue( notificationData ).addOnSuccessListener( new OnSuccessListener<Void>() {
@Override
public void onSuccess(Void aVoid) {
mDialog.dismiss();
mCuurent_state = "req_sent";
mProfileSendReqBtn.setText( "Cancel Friend Request" );
mProfileSendReqBtn.setBackgroundColor( getResources().getColor( R.color.colorAccent ) );
mProfileDeclineReqBtn.setVisibility( View.INVISIBLE );
mProfileDeclineReqBtn.setEnabled( false );
showSuccess( "Request Sent!" );
}
} );
} else {
mDialog.dismiss();
onError( "Request Submission Failed!" );
}
}
} );
} else {
mDialog.dismiss();
onError( "Request Submission Failed!" );
}
mProfileSendReqBtn.setEnabled( true );
}
} );
}
// ========== CANCEL REQUEST FRIEND ==========
if (mCuurent_state.equals( "req_sent" )) {
showLoading( "Data is processing...!" );
mProfileSendReqBtn.setEnabled( false );
mFriendsReqDatabase.child( mCuurentUser.getUid() ).child( user_id ).removeValue().addOnCompleteListener( new OnCompleteListener<Void>() {
@Override
public void onComplete(@NonNull Task<Void> task) {
if (task.isSuccessful()) {
mFriendsReqDatabase.child( user_id ).child( mCuurentUser.getUid() ).removeValue().addOnCompleteListener( new OnCompleteListener<Void>() {
@Override
public void onComplete(@NonNull Task<Void> task) {
if (task.isSuccessful()) {
mDialog.dismiss();
mCuurent_state = "not_friends";
mProfileSendReqBtn.setText( "Send Friend Request" );
mProfileSendReqBtn.setBackgroundColor( getResources().getColor( R.color.successAlert ) );
mProfileDeclineReqBtn.setVisibility( View.INVISIBLE );
mProfileDeclineReqBtn.setEnabled( false );
onSuccess( "Cancel Request Success!" );
} else {
mDialog.dismiss();
onError( "Cancel Request Failed!" );
}
}
} );
} else {
mDialog.dismiss();
onError( "Cancel Request Failed!" );
}
mProfileSendReqBtn.setEnabled( true );
}
} );
}
// ========== ACTION APPROVE REQUEST ==========
if (mCuurent_state.equals( "req_received" )) {
showLoading( "Data is processing...!" );
mProfileSendReqBtn.setEnabled( false );
final String currentDate = DateFormat.getDateTimeInstance().format( new Date() );
mFriendsDatabase.child( mCuurentUser.getUid() ).child( user_id ).setValue( currentDate ).addOnCompleteListener( new OnCompleteListener<Void>() {
@Override
public void onComplete(@NonNull Task<Void> task) {
if (task.isSuccessful()) {
mFriendsDatabase.child( user_id ).child( mCuurentUser.getUid() ).setValue( currentDate ).addOnSuccessListener( new OnSuccessListener<Void>() {
@Override
public void onSuccess(Void aVoid) {
mFriendsReqDatabase.child( mCuurentUser.getUid() ).child( user_id ).removeValue().addOnCompleteListener( new OnCompleteListener<Void>() {
@Override
public void onComplete(@NonNull Task<Void> task) {
if (task.isSuccessful()) {
mFriendsReqDatabase.child( user_id ).child( mCuurentUser.getUid() ).removeValue().addOnCompleteListener( new OnCompleteListener<Void>() {
@Override
public void onComplete(@NonNull Task<Void> task) {
if (task.isSuccessful()) {
mDialog.dismiss();
mCuurent_state = "friends";
mProfileSendReqBtn.setText( "Unfriend This Person" );
mProfileSendReqBtn.setBackgroundColor( getResources().getColor( R.color.colorAccent ) );
mProfileDeclineReqBtn.setVisibility( View.INVISIBLE );
mProfileDeclineReqBtn.setEnabled( false );
showSuccess( "Success approve friend request!" );
} else {
mDialog.dismiss();
onError( "Failed approve friend request!" );
}
}
} );
} else {
mDialog.dismiss();
onError( "Failed approve friend request!" );
}
mProfileSendReqBtn.setEnabled( true );
}
} );
}
} );
} else {
mDialog.dismiss();
onError( "Failed approve friend request!" );
}
mProfileSendReqBtn.setEnabled( true );
}
} );
}
// ========== ACTION REMOVE FRIENDS ==========
if (mCuurent_state.equals( "friends" )) {
showLoading( "Data is processing...!" );
mFriendsDatabase.child( mCuurentUser.getUid() ).child( user_id ).removeValue().addOnSuccessListener( new OnSuccessListener<Void>() {
@Override
public void onSuccess(Void aVoid) {
mDialog.dismiss();
mCuurent_state = "not_friends";
mProfileSendReqBtn.setText( "Send Friend Request" );
mProfileSendReqBtn.setBackgroundColor( getResources().getColor( R.color.successAlert ) );
}
} );
}
}
} );
}
private void showLoading(String s) {
mDialog.setTitle( "Please wait a moment" );
mDialog.setMessage( s );
mDialog.setCanceledOnTouchOutside( false );
mDialog.show();
}
public void showSuccess(String message) {
Alerter.create( this )
.setTitle( "Success" )
.setText( message )
.setBackgroundColorRes( R.color.successAlert )
.show();
}
}
根据描述,错误日志指的是这一行
mUserDatabase = FirebaseDatabase.getInstance().getReference().child( "Users" ).child( user_id );
在这种情况下,应用程序是否无法从Firebase数据库加载数据,从而导致崩溃
请告知第一种解决方案: 如果要防止崩溃发生,可以从ProfileActivity.java
final String user_id = getIntent().getStringExtra( "user_id" );
这是我的密码
FirebaseAuth firebaseAuth = FirebaseAuth.getInstance();
final String user_id;
if (getIntent().getStringExtra( "user_id" ).equals("") ||
getIntent().getStringExtra( "user_id" ) == null) {
user_id = getIntent().getStringExtra( "user_id" );
} else if (firebaseAuth.getCurrentUser() != null) {
user_id = firebaseAuth.getCurrentUser().getUid();
} else {
//There is no active user and the userID retrieved is null
}
如您所见,if-else语句检查您从通知中检索到的用户id
是否为null或空
如果是,它将检查登录到应用程序的当前用户,并使用由FirebaseAuth
检索的user\u id
如果两者都为空或空,请通知我。我会更新我的答案
第二种解决方案:
不要使用字符串from_user_id=remoteMessage.getData().get(“from_user_id”)代码>在您的MyFirebaseMessagingService.java中输入此代码。而是使用下面的代码
public class MyFirebaseMessagingService extends FirebaseMessagingService {
FirebaseAuth firebaseAuth;
@Override
public void onMessageReceived(RemoteMessage remoteMessage) {
super.onMessageReceived( remoteMessage );
firebaseAuth = FirebaseAuth.getInstance();
String from_user_id = firebaseAuth.getCurrentUser().getUid();
}
}
我希望有帮助。请随时询问我它是否工作。我将Firebase功能从
const payload = {
notification: {
title: "New Friend Request",
body: `${userName} has sent you Friend Request`,
icon: "default",
click_action: "com.bertho.chat_TARGET_NOTIFICATION"
},
data: {
from_user_id: from_user_id
}
};
到
感谢@UmarZaii你能告诉我们最后一个字符串user\u id=getIntent()在哪里吗代码>检索到的用户id?我指的是之前的活动。你能把它包括在问题中吗?看起来用户的id是nullHi@UmarZaii,我已经更新了上面的问题。从MyFirebaseMessagingService获得的用户id我已经发布了您问题的答案。如果不行,请通知我。我会更新我的答案。不过还有另外一种选择。谢谢@UmarZaii,我会在收到你的代码后试用你的代码home@BerthoJoris没问题:)嗨@UmarZaii,当我读到你代码的意图时,我误解了。我不能使用user\u id=firebaseAuth.getCurrentUser().getUid()因为用户id不是针对当前登录的用户,而是针对另一个用户,所以代码中存在code>user\u id
我用于从listview捕获一个用户id,然后向他发送notif<代码>用户id
在我的例子中,这可能来自两个来源。第一个是Listview单击查看配置文件(Listview活动到ProfileActivity),第二个是PushNotification直接打开ProfileActivity。根据我所看到的,您的mUserDatabase=FirebaseDatabase.getInstance().getReference().child(“用户”).child(用户id)
似乎有nullmUserDatabase=FirebaseDatabase.getInstance().getReference().child(“用户”).child(null)代码>。这样地。
const payload = {
notification: {
title: "New Friend Request",
body: `${userName} has sent you Friend Request`,
icon: "default",
click_action: "com.bertho.chat_TARGET_NOTIFICATION"
},
data: {
from_user_id: from_user_id
}
};
const payload = {
data: {
title: "New Friend Request",
body: `${userName} has sent you Friend Request`,
from_user_id: from_user_id,
click_action: "com.bertho.chat_TARGET_NOTIFICATION"
}
};