android-fragments 在“活动”中出现片段和显示数据问题

5anewei6  于 2022-11-13  发布在  Android
关注(0)|答案(1)|浏览(205)

我正在尝试为餐馆和自己的餐厅创建应用程序,以完成一项任务。我的想法是,基本上在我的主要活动中(当我以普通用户身份登录时)所有的餐厅都显示了他的营地。当我按下个人资料时,我会被重定向到我的个人资料,当我点击搜索栏时,我也会显示所有的餐厅。我的问题是我的函数从数据库中获取数据(firestorm cloud)但是当我去尝试把它放在一个收藏(在我的情况下是一个Map)上时,它显示为空。所以沈我试着显示一个resturant的所有数据,但什么也没有显示。
活动main是这样的

它在我的MainActivity类中

package com.example.progpmobile;
import android.content.Context;
import android.content.Intent;
import android.graphics.Color;
import android.graphics.drawable.ColorDrawable;
import android.os.Bundle;
import android.util.Log;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.Window;
import android.widget.Toast;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.appcompat.app.ActionBar;
import androidx.appcompat.app.AppCompatActivity;
import androidx.appcompat.widget.Toolbar;
import androidx.fragment.app.Fragment;

import com.example.progpmobile.fragments.FragmentEmployee;
import com.example.progpmobile.fragments.FragmentRestaurateur;
import com.example.progpmobile.fragments.FragmentShowResturants;
import com.example.progpmobile.fragments.FragmentUser;
import com.google.android.gms.tasks.OnCompleteListener;
import com.google.android.gms.tasks.OnSuccessListener;
import com.google.android.gms.tasks.Task;
import com.google.android.material.bottomappbar.BottomAppBar;
import com.google.android.material.bottomnavigation.BottomNavigationView;
import com.google.firebase.auth.FirebaseAuth;
import com.google.firebase.database.DataSnapshot;
import com.google.firebase.database.DatabaseReference;
import com.google.firebase.database.FirebaseDatabase;
import com.google.firebase.firestore.CollectionReference;
import com.google.firebase.firestore.DocumentReference;
import com.google.firebase.firestore.DocumentSnapshot;
import com.google.firebase.firestore.EventListener;
import com.google.firebase.firestore.FirebaseFirestore;
import com.google.firebase.firestore.FirebaseFirestoreException;
import com.google.firebase.firestore.QueryDocumentSnapshot;
import com.google.firebase.firestore.QuerySnapshot;
import com.google.firebase.storage.StorageReference;

import java.util.HashMap;
import java.util.Map;

public class MainActivity extends AppCompatActivity {

    Window window;

    private FragmentUser fragmentUser;
    private FragmentEmployee fragmentEmployee;
    private FragmentRestaurateur fragmentRestaurateur;
    private FragmentShowResturants fragmentShowResturants;

    private Context context;

    private FirebaseAuth fAuth;
    private String userId, resturantId;
    private FirebaseFirestore fStore;
    private StorageReference storageReference;
    private DatabaseReference mUser, mResturant;

    //private BottomNavigationView bottomNav;
    private BottomAppBar mBottomappbar;
    private ActionBar actionBar;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        //DEFINIZIONE FRAGMENTS
        fragmentUser = new FragmentUser();
        fragmentEmployee = new FragmentEmployee();
        fragmentRestaurateur = new FragmentRestaurateur();
        fragmentShowResturants = new FragmentShowResturants();
        //CONNESIONI DB
        fAuth = FirebaseAuth.getInstance();
        fStore = FirebaseFirestore.getInstance();
        mUser = FirebaseDatabase.getInstance().getReference("Users");
        mResturant = FirebaseDatabase.getInstance().getReference("Resturant");

        userId = fAuth.getCurrentUser().getUid();

        //ACTION BAR
        actionBar = getSupportActionBar();
        //BOTTM APP BAR
        mBottomappbar = findViewById(R.id.bottomAppBar);

        //ANIMAZIONE FAB
        mBottomappbar.setNavigationOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                mBottomappbar.setFabAlignmentMode(BottomAppBar.FAB_ALIGNMENT_MODE_END);
            }
        });

        final Map<String, Object> user_data = new HashMap<>();
        final Map<String, Object> resturant_data = new HashMap<>();
        mUser.child(userId).get().addOnCompleteListener(new OnCompleteListener<DataSnapshot>() {
            @Override
            public void onComplete(@NonNull Task<DataSnapshot> task) {
                if (task.isSuccessful()) {
                    if (task.getResult().exists()) {

                        DataSnapshot dataSnapshot = task.getResult();
                        String cognome = String.valueOf(dataSnapshot.child("Cognome").getValue());
                        String nome = String.valueOf(dataSnapshot.child("Nome").getValue());
                        String num_tel = String.valueOf(dataSnapshot.child("Numero telefono").getValue());
                        String Uid = String.valueOf(dataSnapshot.child("Uid").getValue());
                        String email = String.valueOf(dataSnapshot.child("email").getValue());
                        String uri = String.valueOf(dataSnapshot.child("uri").getValue());
                        String user_lvl = String.valueOf(dataSnapshot.child("user_lvl").getValue());
                        //manca password

                        if (user_lvl.equals("1")) {
                            //QUI FRAGMENT CHE MOSTRA TUTTI I RISTORANTI
                            //getSupportFragmentManager().beginTransaction().replace(R.id.empty_main_activity, fragmentShowResturants).commitAllowingStateLoss();

                            Bundle args = new Bundle();
                            args.putString("cognome", cognome);
                            args.putString("nome", nome);
                            args.putString("uri", uri);
                            args.putString("phone", num_tel);
                            args.putString("email", email);
                            args.putString("user_lvl", user_lvl);
                            fragmentUser.setArguments(args);

                            Bundle args2 = new Bundle();

                            args2.putString("Nome", (String) resturant_data.get("Nome"));
                            args2.putString("Indirizzo", (String) resturant_data.get("Indirizzo"));
                            args2.putString("Telefono", (String) resturant_data.get("Telefono"));

                            fragmentShowResturants.setArguments(args2);

                            mBottomappbar.setOnMenuItemClickListener(new Toolbar.OnMenuItemClickListener() {
                                @Override
                                public boolean onMenuItemClick(MenuItem item) {
                                    Fragment selectedFragment = null;
                                    switch (item.getItemId()) {
                                        case R.id.profile:
                                            selectedFragment = fragmentUser;
                                            break;
                                        case R.id.search:
                                            retriveResturantData();
                                            selectedFragment = fragmentShowResturants;
                                            break;
                                        case R.id.navbar_logout:
                                            logOut();
                                            break;
                                    }
                                    if (selectedFragment != null) {
                                        getSupportFragmentManager().beginTransaction().replace(R.id.empty_main_activity, selectedFragment).addToBackStack(null).commit();
                                    }
                                    return true;
                                }
                            });

                        } else if (user_data.get("user_lvl").equals("2")) {
                            getSupportFragmentManager().beginTransaction().replace(R.id.empty_main_activity, fragmentEmployee).commit();
                            mBottomappbar.setOnMenuItemClickListener(new Toolbar.OnMenuItemClickListener() {
                                @Override
                                public boolean onMenuItemClick(MenuItem item) {
                                    Fragment selectedFragment = null;
                                    switch (item.getItemId()) {
                                        case R.id.profile:
                                            selectedFragment = fragmentEmployee;
                                            break;
                                    }
                                    if (selectedFragment != null) {
                                        getSupportFragmentManager().beginTransaction().replace(R.id.empty_main_activity, selectedFragment).addToBackStack(null).commit();
                                    }
                                    return true;
                                }
                            });

                        } else if (user_data.get("user_lvl").equals("3")) {
                            getSupportFragmentManager().beginTransaction().replace(R.id.empty_main_activity, fragmentRestaurateur).commit();

                            mBottomappbar.setOnMenuItemClickListener(new Toolbar.OnMenuItemClickListener() {
                                @Override
                                public boolean onMenuItemClick(MenuItem item) {
                                    Fragment selectedFragment = null;
                                    switch (item.getItemId()) {
                                        case R.id.profile:
                                            selectedFragment = fragmentRestaurateur;
                                            break;
                                    }
                                    if (selectedFragment != null) {
                                        getSupportFragmentManager().beginTransaction().replace(R.id.empty_main_activity, selectedFragment).addToBackStack(null).commit();
                                    }
                                    return true;
                                }
                            });

                        }
                    }
                }
            }
        });
    }

    public Map retriveResturantData() {
        final Map<String, Object> resturant_data = new HashMap<>();
        fStore.collection("Resturant")
                .get()
                .addOnCompleteListener(new OnCompleteListener<QuerySnapshot>() {
                    @Override
                    public void onComplete(@NonNull Task<QuerySnapshot> task) {
                        if (task.isSuccessful()) {
                            for (QueryDocumentSnapshot document : task.getResult()) {
                                String r_Nome = String.valueOf(document.get("Nome"));
                                String r_tel = String.valueOf(document.get("Telefono"));
                                String r_indirizzo = String.valueOf(document.get("Indirizzo"));

                                resturant_data.put("Nome",r_Nome);
                                resturant_data.put("Telefono",r_tel);
                                resturant_data.put("Indirizzo",r_indirizzo);

                                //Log.d("tag", document.getId() + " => " + document.getData());
                            }
                        } else {
                            Log.d("tag", "Error getting documents: ", task.getException());
                        }
                    }
                });
        return resturant_data;
    }

    public void logOut() {
        try {
            FirebaseAuth.getInstance().signOut();
            startActivity(new Intent(getApplicationContext(), LogIn.class));
            finish();
        } catch (Exception e) {
            Toast.makeText(MainActivity.this, "Errore! " + e.getMessage(), Toast.LENGTH_SHORT).show();
        }
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        MenuInflater inflater = getMenuInflater();
        inflater.inflate(R.menu.bottom_app_bar, menu);
        return true;
    }

    @Override
    public void onPause() {
        super.onPause();
    }

    public Context getCtx() {
        return getApplicationContext();
    }

}

这是我的FragmentShowRestuant类

package com.example.progpmobile.fragments;

import static com.example.progpmobile.fragments.FragmentAll.isDoubleOrInt;

import android.app.AlertDialog;
import android.content.DialogInterface;
import android.net.Uri;
import android.os.Bundle;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.fragment.app.Fragment;

import com.example.progpmobile.MainActivity;
import com.example.progpmobile.R;
import com.example.progpmobile.firebase.DatabaseReferences;
import com.google.android.gms.tasks.OnCompleteListener;
import com.google.android.gms.tasks.OnSuccessListener;
import com.google.android.gms.tasks.Task;
import com.google.firebase.auth.FirebaseAuth;
import com.google.firebase.firestore.DocumentReference;
import com.google.firebase.firestore.DocumentSnapshot;
import com.google.firebase.firestore.EventListener;
import com.google.firebase.firestore.FirebaseFirestore;
import com.google.firebase.firestore.FirebaseFirestoreException;
import com.google.firebase.storage.FirebaseStorage;
import com.google.firebase.storage.StorageReference;
import com.squareup.picasso.Picasso;

import java.util.HashMap;
import java.util.Map;

public class FragmentShowResturants extends Fragment {

    private FirebaseAuth fAuth;
    private FirebaseFirestore fStore;
    private StorageReference storageReference;
    private String resturantId;
    //IMMAGINI
    private ImageView resturantImage;
    public Uri r_imageUri;

    //STRINGHE
    private TextView Nome, Address, r_phone, r_desc, wrk_hours, food_type, buisness_email, r_photos;
    private String mod_r_name;
    private String mod_r_address;
    private String mod_resturant_desc;
    private String mod_wrk_hours;
    private String mod_food_type;
    private String mod_r_photos;
    private String mod_buisness_email;
    private String mod_r_phone;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        Bundle arguments = getArguments();
    }

    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.fragment_resturant, container, false);

        Nome = view.findViewById(R.id.resturant_mname);
        Address = view.findViewById(R.id.resturant_maddres);
        r_phone = view.findViewById(R.id.resturant_mphone);

        /*
        wrk_hours =view.findViewById(R.id.resturant_wrc_hours);
        r_desc=  view.findViewById(R.id.resturant_description);
        //food_type=view.findViewById(R.id.resturant_f_type);
        buisness_email=view.findViewById(R.id.resturant_b_email);
        r_photos = view.findViewById(R.id.resturant_photos);
        */
        mod_r_phone = getArguments().getString("Telefono");
        mod_r_name = getArguments().getString("Nome");
        mod_r_address = getArguments().getString("Indirizzo");

        /*
        mod_r_phone = this.getArguments().getString("Telefono");
        mod_r_name = this.getArguments().getString("Nome");
        mod_r_address = this.getArguments().getString("Indirizzo");
        mod_resturant_desc=this.getArguments().getString("cognome");
        mod_wrk_hours=this.getArguments().getString("OrarioLavorativo");
        mod_food_type=this.getArguments().getString("TipoCibo");
        mod_r_photos=this.getArguments().getString("cognome");
        mod_buisness_email=this.getArguments().getString("cognome");
        */

        fAuth = FirebaseAuth.getInstance();
        fStore = FirebaseFirestore.getInstance();
        storageReference = FirebaseStorage.getInstance().getReference();
        //resturantId = fAuth.getCurrentUser().getUid();

       /*CARICA IMMAGINE QUESTA VA SPOSTATA SU RISTORATORE
        StorageReference profileRef = storageReference.child("Resturant-images/" + fAuth.getCurrentUser().getUid());
        try {
            profileRef.getDownloadUrl().addOnSuccessListener(new OnSuccessListener<Uri>() {
                @Override
                public void onSuccess(Uri uri) {
                    Picasso.get().load(uri).into(resturantImage);
                    fStore.collection("Resturant")
                            .document(resturantId)
                            .update("uri", uri.toString());
                }
            });
        } catch (Exception e) {
            Log.d("Do nothing", "");
        }
        */

        //MOSTRA INFO RISTORANTE
        DocumentReference r_docref= fStore.collection("Resturant").document();
        r_docref.get().addOnCompleteListener(new OnCompleteListener<DocumentSnapshot>() {
            @Override
            public void onComplete(@NonNull Task<DocumentSnapshot> task) {
                if (task.isSuccessful()) {
                    DocumentSnapshot document = task.getResult();
                    if (document.exists()) {
                        Nome.setText(mod_r_name);
                        Address.setText(mod_r_address);
                        r_phone.setText(mod_r_phone);
                    //document.getData());
                    } else {
                        Log.d("tag", "Non esiste questo documento");
                    }
                } else {
                    Log.d("tag", "Errore ", task.getException());
                }
            }
        });
             /*
        try {
            docRef.addSnapshotListener(new EventListener<DocumentSnapshot>() {
                @Override
                public void onEvent(@Nullable DocumentSnapshot documentSnapshot, @Nullable FirebaseFirestoreException e) {
                    if (documentSnapshot != null ? documentSnapshot.exists() : false) {
                        Nome.setText(mod_r_name);
                        Address.setText(mod_r_address);
                        r_phone.setText(mod_r_phone);
                    } else {
                        Log.d("tag", "onEvent: Document do not exists");
                    }
                }
            });
        }

    catch (Exception e) {
            Log.d("Do nothing", "");
        }*/

        return view;
    }
}

我指的功能是

public Map retriveResturantData() {
    final Map<String, Object> resturant_data = new HashMap<>();
    fStore.collection("Resturant")
            .get()
            .addOnCompleteListener(new OnCompleteListener<QuerySnapshot>() {
                @Override
                public void onComplete(@NonNull Task<QuerySnapshot> task) {
                    if (task.isSuccessful()) {
                        for (QueryDocumentSnapshot document : task.getResult()) {
                            String r_Nome = String.valueOf(document.get("Nome"));
                            String r_tel = String.valueOf(document.get("Telefono"));
                            String r_indirizzo = String.valueOf(document.get("Indirizzo"));

                            resturant_data.put("Nome",r_Nome);
                            resturant_data.put("Telefono",r_tel);
                            resturant_data.put("Indirizzo",r_indirizzo);

                            //Log.d("tag", document.getId() + " => " + document.getData());
                        }
                    } else {
                        Log.d("tag", "Error getting documents: ", task.getException());
                    }
                }
            });
    return resturant_data;
}

我认为问题出在最后一个返回语句上。
这是我的观点FragmentResturants.xml

<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout 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:layout_width="match_parent"
    android:layout_height="match_parent"
    android:background="@drawable/backgruond_splash">

    <TextView
        android:id="@+id/resturant_phone"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_marginTop="30dp"
        android:gravity="center"
        android:text="@string/r_phone"
        android:textColor="@color/white"
        android:textSize="25sp"
        android:textStyle="bold"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toBottomOf="@+id/resturant_maddres" />

    <TextView
        android:id="@+id/resturant_mphone"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_marginTop="15dp"
        android:gravity="center"
        android:text="Telefono ristorante"
        android:textColor="@color/white"
        android:textSize="25sp"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toBottomOf="@+id/resturant_phone" />

    <TextView
        android:id="@+id/resturant_name"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_marginTop="25dp"
        android:gravity="center"
        android:text="@string/fullname"
        android:textColor="@color/white"
        android:textSize="25sp"
        android:textStyle="bold"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toTopOf="parent" />

    <TextView
        android:id="@+id/resturant_mname"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_marginTop="15dp"
        android:gravity="center"
        android:text="Your name"
        android:textColor="@color/white"
        android:textSize="25sp"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toBottomOf="@+id/resturant_name" />

    <TextView
        android:id="@+id/resturant_addres"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_marginTop="30dp"
        android:gravity="center"
        android:text="@string/r_address"
        android:textColor="@color/white"
        android:textSize="25sp"
        android:textStyle="bold"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toBottomOf="@+id/resturant_mname" />

    <TextView
        android:id="@+id/resturant_maddres"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_marginTop="15dp"
        android:gravity="center"
        android:text="Indirizzo ristorante"
        android:textColor="@color/white"
        android:textSize="25sp"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toBottomOf="@+id/resturant_addres" />

    <ImageView
        android:id="@+id/user_image"
        android:layout_width="184dp"
        android:layout_height="148dp"
        android:layout_marginBottom="64dp"
        android:clickable="true"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintHorizontal_bias="0.498"
        app:layout_constraintStart_toStartOf="parent"
        app:srcCompat="@drawable/ic_account"
        tools:ignore="SpeakableTextPresentCheck" />

</androidx.constraintlayout.widget.ConstraintLayout>

基本上,当我点击seatch按钮,我得到显示没有数据的fragmentResturant视图一样,对你的名字应该有显示我的resturant名称,但我得到显示什么。我试图debbuging和对我的breack点225的数据检索的权利,但然后没有显示。

mod_r_phone = getArguments().getString("Telefono");
        mod_r_name = getArguments().getString("Nome");
        mod_r_address = getArguments().getString("Indirizzo");

基本上,这些变量将变为空

enyaitl3

enyaitl31#

MainActivity中,调用retriveResturantData(),但不将返回的数据赋给任何对象:

case R.id.search:
    retriveResturantData();

您的Fragment仍然有一个空的Bundle作为参数。

相关问题