android-fragments 如何从Firebase实时数据库中分段检索数据?

kmynzznz  于 2022-11-14  发布在  Android
关注(0)|答案(1)|浏览(140)

这是我的数据库的外观:

我已经在fragment中编写了代码,并有了这样一个error
java.lang.NullPointerException:尝试对空对象引用调用接口方法“int java.lang.CharSequence.length()”
这是我Fragment.xml

<ImageView
        android:layout_width="match_parent"
        android:layout_height="150dp"
        android:background="@drawable/gradient_hijau_kuning_kotak"
        app:layout_constraintTop_toTopOf="parent" />

    <de.hdodenhof.circleimageview.CircleImageView
        android:id="@+id/tampilanFoto"
        android:layout_width="120dp"
        android:layout_height="120dp"
        android:layout_marginTop="88dp"
        android:src="@drawable/fotorumahsakit"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintHorizontal_bias="0.5"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toTopOf="parent" />

    <TextView
        android:id="@+id/tampilanNamaUser"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_marginTop="10dp"
        android:fontFamily="@font/swansea_bold"
        android:gravity="center"
        android:text="Nama User"
        android:textColor="@color/black"
        android:textSize="30sp"
        android:textStyle="bold"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toBottomOf="@id/tampilanFoto" />

    <TextView
        android:id="@+id/tampilanLokasiUser"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_marginTop="10dp"
        android:fontFamily="@font/twentycenth"
        android:gravity="center"
        android:text="Lokasi"
        android:textColor="@color/black"
        android:textSize="20sp"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toBottomOf="@id/tampilanNamaUser" />

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="0dp"
        android:orientation="vertical"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintTop_toBottomOf="@id/tampilanLokasiUser">

        <TextView
            android:id="@+id/infoAkunText"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:layout_marginStart="30dp"
            android:layout_marginTop="20dp"
            android:fontFamily="@font/swansea_bold"
            android:text="Info Akun"
            android:textColor="@color/black"
            android:textSize="30sp"
            android:textStyle="bold"/>

        <LinearLayout
            android:layout_width="match_parent"
            android:padding="20dp"
            android:layout_height="wrap_content"
            android:orientation="horizontal">

            <ImageView
                android:id="@+id/iconProfile"
                android:layout_width="80dp"
                android:layout_marginStart="20dp"
                android:layout_height="80dp"
                android:src="@drawable/man"/>

            <LinearLayout
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:layout_gravity="center"
                android:orientation="vertical">

                <TextView
                    android:id="@+id/textStatus"
                    android:layout_width="wrap_content"
                    android:layout_height="wrap_content"
                    android:layout_marginStart="16dp"
                    android:fontFamily="@font/swansea_bold"
                    android:text="Status :"
                    android:textColor="@color/black"
                    android:textSize="18sp"/>

                <TextView
                    android:id="@+id/showStatus"
                    android:layout_width="wrap_content"
                    android:layout_height="wrap_content"
                    android:layout_marginStart="16dp"
                    android:fontFamily="@font/swansea_thin"
                    android:text="status"
                    android:textColor="@color/black"
                    android:textSize="18sp"/>

            </LinearLayout>

        </LinearLayout>

        <TextView
            android:id="@+id/gantiPassword"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:fontFamily="@font/twentycenth"
            android:layout_gravity="center"
            android:gravity="center"
            android:text="GANTI PASSWORD"
            android:textColor="@color/hijau_cerah"
            android:textSize="18sp"/>
    </LinearLayout>

</androidx.constraintlayout.widget.ConstraintLayout>

这是我的Fragment.java

public class ProfileFragment extends Fragment {

    TextView tampilanNamaUser, tampilanLokasi, statusUser, gantiPassword;
    FirebaseAuth mAuth;
    SessionManager sessionManager;
    DatabaseReference databaseReference = FirebaseDatabase.getInstance().getReferenceFromUrl("https://simande-4f3e2-default-rtdb.firebaseio.com/");

    private static final String ARG_PARAM1 = "param1";
    private static final String ARG_PARAM2 = "param2";
    
    private String mParam1;
    private String mParam2;

    public ProfileFragment() {    
    }
    
    public static ProfileFragment newInstance(String param1, String param2) {
        ProfileFragment fragment = new ProfileFragment();
        Bundle args = new Bundle();
        args.putString(ARG_PARAM1, param1);
        args.putString(ARG_PARAM2, param2);
        fragment.setArguments(args);
        return fragment;
    }

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        if (getArguments() != null) {
            mParam1 = getArguments().getString(ARG_PARAM1);
            mParam2 = getArguments().getString(ARG_PARAM2);
        }
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        // Inflate the layout for this fragment
        View v =  inflater.inflate(R.layout.fragment_profile, container, false);

        //Hook
        tampilanNamaUser = v.findViewById(R.id.tampilanNamaUser);
        tampilanLokasi = v.findViewById(R.id.tampilanLokasiUser);
        statusUser = v.findViewById(R.id.showStatus);
        gantiPassword = v.findViewById(R.id.gantiPassword);

        sessionManager = new SessionManager(getContext(), SessionManager.SESSION_USERSESSION);
        HashMap<String, String> usersDetails = sessionManager.getUsersDetailFromSession();
        String getName = usersDetails.get(SessionManager.KEY_USERNAME);

        getUserInfo(getName);

        return v;
    }

    private void getUserInfo(String getName) {
        databaseReference.child("Users").addValueEventListener(new ValueEventListener() {
            @Override
            public void onDataChange(@NonNull DataSnapshot snapshot) {
                if (snapshot.exists()){
                    if (snapshot.hasChild(getName)){
                        String nama = snapshot.child("Nama").getValue().toString();

                        tampilanNamaUser.setText(nama);
                    }
                }
            }

            @Override
            public void onCancelled(@NonNull DatabaseError error) {
            }
        });
    }    
}

**P.s:**这是我的CreateAccountActivity我把getName字符串放在这个Activity上,但我不知道如何在另一个Fragment中调用它。

public class BuatAkunActv extends AppCompatActivity {

    private EditText userInput, passInput;
    private Button buttonRegist;
    DatabaseReference databaseReference = FirebaseDatabase.getInstance().getReferenceFromUrl("https://simande-4f3e2-default-rtdb.firebaseio.com/");

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

        //Hook
        userInput = findViewById(R.id.daftarUser);
        passInput = findViewById(R.id.daftarPassword);
        buttonRegist = findViewById(R.id.buttonDaftar);

        buttonRegist.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                String getName = userInput.getText().toString();
                String getPassword = passInput.getText().toString();

                databaseReference.child("Users").addListenerForSingleValueEvent(new ValueEventListener() {
                    @Override
                    public void onDataChange(@NonNull DataSnapshot snapshot) {

                        if (snapshot.hasChild(getName)){
                            Toast.makeText(BuatAkunActv.this, "User sudah terdaftar", Toast.LENGTH_SHORT).show();
                        }
                        else {
                            databaseReference.child("Users").child(getName).child("nama").setValue(getName);
                            databaseReference.child("Users").child(getName).child("password").setValue(getPassword);

                            Toast.makeText(BuatAkunActv.this, "User berhasil dibuat", Toast.LENGTH_SHORT).show();
                        }
                    }

                    @Override
                    public void onCancelled(@NonNull DatabaseError error) {    
                    }
                });
            }
        });
    }
}
s8vozzvw

s8vozzvw1#

您的getUserInfo中有很多问题。我不确定是否是这些问题导致了错误,但我会将其更改为以下内容:

private void getUserInfo(String getName) {
    databaseReference.child("Users").child(getName).addValueEventListener(new ValueEventListener() {
        @Override
        public void onDataChange(@NonNull DataSnapshot snapshot) {
            if (snapshot.exists()){
                String nama = snapshot.child("Nama").getValue().toString();

                tampilanNamaUser.setText(nama);
            }
        }

        @Override
        public void onCancelled(@NonNull DatabaseError error) {
            throw error.toException();
        }
    });
}

显著变化:

  • 不要加载整个Users节点来检查其中是否存在一个子节点,而是只加载该子节点。
  • 不要忽略onCancelled中的错误,因为它会使调试更加困难。

相关问题