将列表添加到Cloud Firebase-Android

问题描述:

我会根据YouTube上的出色指导来做所有事情. https://www.youtube.com/watch?v=W-L6Cr2WP18-我建议.不幸的是,我没有使用活动,而是使用一个片段,但出现了错误.

I do everything according to great guides from Youtube. https://www.youtube.com/watch?v=W-L6Cr2WP18 - I recommend. Unfortunately, instead of activity, I use a fragment and I have an error.

MainActivity:

MainActivity:

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!");
             }
         });
    }
}

要解决此问题,请更改以下代码行:

To solve this, change the following lines of code:

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();
}

此字段已经被声明为全局字段.

This fields are already declared as global.

您正在片段中使用以下代码行:

You are using in your fragment the following line of code:

dailyGoalsRef = rootRef.collection("goalsData").document(userEmail).collection("dailyGoals");

userEmail null 的位置.发生这种情况是因为您没有将 userEmail 从活动传递到片段.仅将其声明为全局变量并不能解决问题.

Where the userEmail is null. This is happening because you are not passing the userEmail from the activity to the fragment. Just declaring it as a global variable does not solve the problem.

要解决此问题,请在您的活动中创建一个返回 userEmail 的方法.

To solve this, create a method in your activity that returns the userEmail.

public String getUserEmail() {return userEmail;}

然后在您的片段中,创建一个字符串字段 String userEmail 作为全局字段,并像下面这样调用该方法:

And in your fragment, create a String field String userEmail as global and call that method like this:

userEmail = ((MainActivity) getActivity()).getUserEmail();