我从其他站点复制了以下代码,因为我认为这可以节省一些时间。但是我有3个问题。
它们是红色的。希望您能提供帮助。
package com.mz4466.photowar;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.appcompat.app.AppCompatActivity;
import android.content.Intent;
import android.nfc.Tag;
import android.os.Bundle;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.TextView;
import android.widget.Toast;
import com.google.firebase.auth.FirebaseAuth;
import com.google.firebase.auth.FirebaseUser;
import java.util.zip.Inflater;
public class HomeActivity extends AppCompatActivity {
private static final String TAG = "HomeActivity";
//firebase
private FirebaseAuth.AuthStateListener mAuthStateListener;
//widgets
private Button mSignOut;
@Nullable
@Override
public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.activity_home, container, false);
mSignOut = (Button) view.findViewById(R.id.logout_button);
setupFirebaseListener();
mSignOut.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Log.d(TAG, "onClick: attempting to sign out the user.");
FirebaseAuth.getInstance().signOut();
}
});
return view;
}
private void setupFirebaseListener(){
Log.d(TAG, "setupFirebaseListener: setting up the auth state listener.");
mAuthStateListener = new FirebaseAuth.AuthStateListener() {
@Override
public void onAuthStateChanged(@NonNull FirebaseAuth firebaseAuth) {
FirebaseUser user = firebaseAuth.getCurrentUser();
if(user != null){
Log.d(TAG, "onAuthStateChanged: signed_in: " + user.getUid());
}else{
Log.d(TAG, "onAuthStateChanged: signed_out");
Toast.makeText(getActivity(), "Signed out", Toast.LENGTH_SHORT).show();
Intent intent = new Intent(getActivity(), LoginActivity.class);
intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TASK);
startActivity(intent);
}
}
};
}
@Override
public void onStart() {
super.onStart();
FirebaseAuth.getInstance().addAuthStateListener(mAuthStateListener);
}
@Override
public void onStop() {
super.onStop();
if(mAuthStateListener != null){
FirebaseAuth.getInstance().removeAuthStateListener(mAuthStateListener);
}
}
}
答案 0 :(得分:1)
您复制的代码是片段代码,不是活动,因此您需要进行一些更改
首先将任何getActivity()
更改为HomeActivity.this
第二,您需要覆盖onCreate()
而不是onCreateView()
方法,因此请更改这些行
@Nullable
@Override
public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.activity_home, container, false);
到
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_home);
最后从此行view.
中删除mSignOut = (Button) view.findViewById(R.id.logout_button);
,并完全删除此行return view;