将列表添加到Cloud Firebase - Android
Posted
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了将列表添加到Cloud Firebase - Android相关的知识,希望对你有一定的参考价值。
我根据Youtube的优秀导游做了一切。 https://www.youtube.com/watch?v=W-L6Cr2WP18 - 我推荐。不幸的是,我使用片段而不是活动,但我有一个错误。
主要内容:
public class MainActivity extends AppCompatActivity
implements NavigationView.OnNavigationItemSelectedListener{
private String userEmail, userName;
private GoogleApiClient googleApiClient;
private FirebaseAuth firebaseAuth;
private FirebaseFirestore rootRef;
private FirebaseAuth.AuthStateListener authStateListener;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main_activity);
GoogleSignInAccount googleSignInAccount = GoogleSignIn.getLastSignedInAccount(this);
if(googleSignInAccount != null){
String userEmail = googleSignInAccount.getEmail();
String userName = googleSignInAccount.getDisplayName();
Toast.makeText(this, "Witaj " + userName, Toast.LENGTH_LONG).show();
}
GoogleApiClient googleApiClient = new GoogleApiClient.Builder(this)
.addApi(Auth.GOOGLE_SIGN_IN_API)
.build();
firebaseAuth = FirebaseAuth.getInstance();
rootRef = FirebaseFirestore.getInstance();
authStateListener = new FirebaseAuth.AuthStateListener() {
@Override
public void onAuthStateChanged(@NonNull FirebaseAuth firebaseAuth) {
FirebaseUser firebaseUser = firebaseAuth.getCurrentUser();
if(firebaseUser == null){
Intent intent = new Intent(MainActivity.this, LoginActivity.class);
startActivity(intent);
}
}
};
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
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.setDrawerListener(toggle);
toggle.syncState();
NavigationView navigationView = (NavigationView) findViewById(R.id.nav_view);
navigationView.setNavigationItemSelectedListener(this);
//add this line to display menu1 when the activity is loaded
displaySelectedScreen(R.id.nav_menu1);
}
private void signOut(){
Map<String, Object> map = new HashMap<>();
map.put("tokenId", FieldValue.delete());
rootRef.collection("users").document(userEmail).update(map).addOnSuccessListener(new OnSuccessListener<Void>(){
@Override
public void onSuccess(Void aVoid){
firebaseAuth.signOut();
if(googleApiClient.isConnected()){
Auth.GoogleSignInApi.signOut(googleApiClient);
}
}
});
}
@Override
protected void onStart() {
super.onStart();
googleApiClient.connect();
firebaseAuth.addAuthStateListener(authStateListener);
}
@Override
protected void onStop() {
super.onStop();
if(googleApiClient.isConnected()){
googleApiClient.disconnect();
}
}
@Override
public void onBackPressed() {
DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
if (drawer.isDrawerOpen(GravityCompat.START)) {
drawer.closeDrawer(GravityCompat.START);
} else {
super.onBackPressed();
}
}
//wybieranie fragmentu
private void displaySelectedScreen(int itemId) {
//creating fragment object
Fragment fragment = null;
//initializing the fragment object which is selected
switch (itemId) {
case R.id.nav_menu1:
fragment = new Menu1Goals();
break;
case R.id.nav_menu2:
fragment = new Menu2();
break;
case R.id.nav_menu3:
fragment = new Menu3();
break;
}
//replacing the fragment - zmienianie fragmentów
//Transakcja fragmentu to seria zmian dotyczących fragmentu, które chcemy wykonać w tym samym momencie
if (fragment != null) {
FragmentTransaction ft = getSupportFragmentManager().beginTransaction();
ft.replace(R.id.content_frame, fragment);
ft.setTransition(FragmentTransaction.TRANSIT_FRAGMENT_FADE);
ft.commit();
}
DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
drawer.closeDrawer(GravityCompat.START);
}
//przekazywanie wybranego fragmentu do interfejsu
@SuppressWarnings("StatementWithEmptyBody")
@Override
public boolean onNavigationItemSelected(MenuItem item) {
//calling the method displayselectedscreen and passing the id of selected menu
displaySelectedScreen(item.getItemId());
//make this method blank
return true;
}
//------------------------------------Top Menu----------------------------------------------
@Override
public boolean onCreateOptionsMenu(Menu menu) {
MenuInflater menuInflater = getMenuInflater();
menuInflater.inflate(R.menu.main, menu);
//getting the search view from the menu
MenuItem searchViewItem = menu.findItem(R.id.menuSearch);
//getting search manager from systemservice
SearchManager searchManager = (SearchManager) getSystemService(Context.SEARCH_SERVICE);
//getting the search view
final SearchView searchView = (SearchView) searchViewItem.getActionView();
//you can put a hint for the search input field
searchView.setQueryHint("Czego wspólnie poszukamy?");
searchView.setSearchableInfo(searchManager.getSearchableInfo(getComponentName()));
//by setting it true we are making it iconified
//so the search input will show up after taping the search iconified
//if you want to make it visible all the time make it false
searchView.setIconifiedByDefault(true);
//here we will get the search query
searchView.setOnQueryTextListener(new SearchView.OnQueryTextListener() {
@Override
public boolean onQueryTextSubmit(String query) {
//do the search here
return false;
}
@Override
public boolean onQueryTextChange(String newText) {
return false;
}
});
return true;
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()){
case R.id.sign_out_button:
signOut();
return true;
case R.id.action_settings:
//settings();
return true;
default:
return super.onOptionsItemSelected(item);
}
}
//------------------------------------------------------------------------------------------
分段:
public class DailyFragment extends Fragment{
Toast toast;
private FirebaseFirestore rootRef;
private CollectionReference dailyGoalsRef;
private String userEmail, userName;
@Nullable
@Override
public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
View layout = inflater.inflate(R.layout.fragment_daily, container, false);
FloatingActionButton fab2 = layout.findViewById(R.id.fab2);
fab2.setOnClickListener(new View.OnClickListener(){
@Override
public void onClick(View view){
AlertDialog.Builder builder = new AlertDialog.Builder(getContext());
builder.setTitle("Zadania na dzisiaj");
final EditText editText = new EditText(getContext());
editText.setInputType(InputType.TYPE_CLASS_TEXT | InputType.TYPE_TEXT_FLAG_CAP_WORDS);
editText.setHint("Podaj cel");
editText.setHintTextColor(Color.GRAY);
builder.setView(editText);
builder.setPositiveButton("Utwórz", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialogInterface, int i) {
String nazwa_celu = editText.getText().toString().trim();
addGoalsList(nazwa_celu);
}
});
builder.setNegativeButton("Anuluj", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialogInterface, int i) {
dialogInterface.dismiss();
}
});
AlertDialog alertDialog = builder.create();
alertDialog.show();
}
});
dailyGoalsRef = rootRef.collection("goalsData").document(userEmail).collection("dailyGoals");
return layout;
}
private void addGoalsList(String nazwa_celu){
String goalsListId = dailyGoalsRef.document().getId();
GoalsModel goalsModel = new GoalsModel(goalsListId, nazwa_celu, userName);
dailyGoalsRef.document(goalsListId).set(goalsModel).addOnSuccessListener(new OnSuccessListener<Void>() {
@Override
public void onSuccess(Void aVoid) {
Log.d("TAG", "Lista celów stworzona pomyślnie!");
}
});
}
}
答案
要解决此问题,请更改以下代码行:
if(googleSignInAccount != null){
String userEmail = googleSignInAccount.getEmail();
String userName = googleSignInAccount.getDisplayName();
Toast.makeText(this, "Witaj " + userName, Toast.LENGTH_LONG).show();
}
同
if(googleSignInAccount != null){
userEmail = googleSignInAccount.getEmail();
userName = googleSignInAccount.getDisplayName();
Toast.makeText(this, "Witaj " + userName, Toast.LENGTH_LONG).show();
}
此字段已声明为全局字段。
您在片段中使用以下代码行:
dailyGoalsRef = rootRef.collection("goalsData").document(userEmail).collection("dailyGoals");
userEmail
是null
的地方。发生这种情况是因为您没有将userEmail
从活动传递到片段。仅将其声明为全局变量并不能解决问题。
要解决此问题,请在活动中创建一个返回userEmail
的方法。
public String getUserEmail() {return userEmail;}
在你的片段中,创建一个String字段String userEmail
作为全局,并调用这样的方法:
userEmail = ((MainActivity) getActivity()).getUserEmail();
以上是关于将列表添加到Cloud Firebase - Android的主要内容,如果未能解决你的问题,请参考以下文章
如何将子集合添加到 Firebase Cloud Firestore 中的文档
将新数据添加到特定子项时如何使用 Cloud Functions 将数据写入 Firebase 实时数据库
Google FireBase - fcm 推送 (Cloud Messaging)
错误 Firebase Cloud Functions Typescript Payload contains an invalid value for the "notification.