Ошибка com.google.firebase.database.DatabaseException: Failed to convert value of type java.util.HashMap to String

Делаю приложение под андроид и заметил интересную особенность: на дебаге с подключённым телефоном оно полностью работает, но стоит только его скомпилировать в APK и установить, как начинаются чудеса. Приложение выдаёт одну и ту же ошибку как при его запуске с APK, так и при дебаг запуске с компьютера

E/AndroidRuntime: FATAL EXCEPTION: main
    Process: com.example.lic412, PID: 12988
    com.google.firebase.database.DatabaseException: Failed to convert value of type java.util.HashMap to String
        at com.google.firebase.database.core.utilities.encoding.CustomClassMapper.convertString(com.google.firebase:firebase-database@@16.0.4:413)
        at com.google.firebase.database.core.utilities.encoding.CustomClassMapper.deserializeToClass(com.google.firebase:firebase-database@@16.0.4:199)
        at com.google.firebase.database.core.utilities.encoding.CustomClassMapper.convertToCustomClass(com.google.firebase:firebase-database@@16.0.4:79)
        at com.google.firebase.database.DataSnapshot.getValue(com.google.firebase:firebase-database@@16.0.4:212)
        at com.example.lic412.ui.home.HomeFragment$1.onDataChange(HomeFragment.java:56)
        at com.google.firebase.database.core.ValueEventRegistration.fireEvent(com.google.firebase:firebase-database@@16.0.4:75)
        at com.google.firebase.database.core.view.DataEvent.fire(com.google.firebase:firebase-database@@16.0.4:63)
        at com.google.firebase.database.core.view.EventRaiser$1.run(com.google.firebase:firebase-database@@16.0.4:55)
        at android.os.Handler.handleCallback(Handler.java:883)
        at android.os.Handler.dispatchMessage(Handler.java:100)
        at android.os.Looper.loop(Looper.java:224)
        at android.app.ActivityThread.main(ActivityThread.java:7562)
        at java.lang.reflect.Method.invoke(Native Method)
        at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:539)
        at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:950)

Вот сам код этого Activity:

package com.example.lic412.ui.home;

import android.content.Context;
import android.content.SharedPreferences;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.fragment.app.Fragment;
import androidx.lifecycle.Observer;
import androidx.lifecycle.ViewModelProviders;

import com.example.lic412.R;
import com.google.firebase.analytics.FirebaseAnalytics;
import com.google.firebase.database.DataSnapshot;
import com.google.firebase.database.DatabaseError;
import com.google.firebase.database.DatabaseReference;
import com.google.firebase.database.FirebaseDatabase;
import com.google.firebase.database.ValueEventListener;

import org.w3c.dom.Text;

import java.util.Map;

public class HomeFragment extends Fragment {

    private HomeViewModel homeViewModel;
    FirebaseDatabase db = FirebaseDatabase.getInstance();
    DatabaseReference dat;
    TextView textView;
    SharedPreferences pref;

    public View onCreateView(@NonNull LayoutInflater inflater,
                             ViewGroup container, Bundle savedInstanceState) {
        homeViewModel =
                ViewModelProviders.of(this).get(HomeViewModel.class);
        View root = inflater.inflate(R.layout.fragment_home, container, false);
        textView = root.findViewById(R.id.textView2);
        //text = root.findViewById(R.id.textView);
        //text.setText(pref.getString("settings","class"));
        pref = getContext().getSharedPreferences("settings", Context.MODE_PRIVATE);
        dat = db.getReference(pref.getString("class",""));//pref.getString("class","")
        dat.addValueEventListener(new ValueEventListener() {
            @Override
            public void onDataChange(DataSnapshot dataSnapshot) {
                // Retrieve latest value
                String message = dataSnapshot.getValue(String.class);
                if(message == null){
                    if(hasConnection(getContext())){
                        DatabaseReference ref = db.getReference(pref.getString("class",""));
                        ref.setValue("100");
                    }
                    else{
                        Toast.makeText(getContext(), "Ошибка, проверьте подключение к интернету", Toast.LENGTH_SHORT).show();
                        message = "";
                    }

                }
                textView.setText("Баллы твоего класса: " + message);
            }

            @Override
            public void onCancelled(@NonNull DatabaseError databaseError) {
                Toast.makeText(getContext(), "Error", Toast.LENGTH_SHORT).show();
            }
        });
        return root;
    }

    public static boolean hasConnection(final Context context)
    {
        ConnectivityManager cm = (ConnectivityManager)context.getSystemService(Context.CONNECTIVITY_SERVICE);
        NetworkInfo wifiInfo = cm.getNetworkInfo(ConnectivityManager.TYPE_WIFI);
        if (wifiInfo != null && wifiInfo.isConnected())
        {
            return true;
        }
        wifiInfo = cm.getNetworkInfo(ConnectivityManager.TYPE_MOBILE);
        if (wifiInfo != null && wifiInfo.isConnected())
        {
            return true;
        }
        wifiInfo = cm.getActiveNetworkInfo();
        if (wifiInfo != null && wifiInfo.isConnected())
        {
            return true;
        }
        return false;
    }
}

Кто-нибудь когда-то с таким сталкивался?


Ответы (1 шт):

Автор решения: Анастасия

Ошибка в этой строке:

String message = dataSnapshot.getValue(String.class);

и заключается в том, что HashMap не может быть преобразован в String. Скорее всего, в Вашем dataSnapshot лежит не значение, а еще как минимум один уровень ключей. Проверьте путь в базе данных.

→ Ссылка