Не удалось преобразовать значение типа java.lang.String в значение double в приложении Marathon - PullRequest
1 голос
/ 04 апреля 2019

Я нахожусь в процессе завершения проекта приложения для Android, над которым я работаю.Приложение представляет собой «распределенный марафон», означающий, что люди могут соревноваться друг с другом, находясь в разных местах.Однако у меня возникла проблема с некоторым кодом, из-за которой я получаю сообщение об ошибке:

com.google.firebase.database.DatabaseException: Failed to convert a value of type java.lang.String to double

Я пытался решить эту проблему с прошлой ночи, но, к сожалению, безуспешно.

Ниже я покажу весь код, который мне кажется уместным. Пожалуйста, дайте мне знать, если потребуется дополнительный код.

Logcat:

2019-04-04 16:41:15.230 29421-29421/? E/AndroidRuntime: FATAL EXCEPTION: main
    Process: com.aladdin.FitHub2019Project, PID: 29421
    com.google.firebase.database.DatabaseException: Failed to convert a value of type java.lang.String to double
        at com.google.firebase.database.core.utilities.encoding.CustomClassMapper.convertDouble(com.google.firebase:firebase-database@@16.1.0:395)
        at com.google.firebase.database.core.utilities.encoding.CustomClassMapper.deserializeToPrimitive(com.google.firebase:firebase-database@@16.1.0:276)
        at com.google.firebase.database.core.utilities.encoding.CustomClassMapper.deserializeToClass(com.google.firebase:firebase-database@@16.1.0:197)
        at com.google.firebase.database.core.utilities.encoding.CustomClassMapper.deserializeToType(com.google.firebase:firebase-database@@16.1.0:178)
        at com.google.firebase.database.core.utilities.encoding.CustomClassMapper.access$100(com.google.firebase:firebase-database@@16.1.0:47)
        at com.google.firebase.database.core.utilities.encoding.CustomClassMapper$BeanMapper.deserialize(com.google.firebase:firebase-database@@16.1.0:591)
        at com.google.firebase.database.core.utilities.encoding.CustomClassMapper$BeanMapper.deserialize(com.google.firebase:firebase-database@@16.1.0:550)
        at com.google.firebase.database.core.utilities.encoding.CustomClassMapper.convertBean(com.google.firebase:firebase-database@@16.1.0:420)
        at com.google.firebase.database.core.utilities.encoding.CustomClassMapper.deserializeToClass(com.google.firebase:firebase-database@@16.1.0:214)
        at com.google.firebase.database.core.utilities.encoding.CustomClassMapper.convertToCustomClass(com.google.firebase:firebase-database@@16.1.0:79)
        at com.google.firebase.database.DataSnapshot.getValue(com.google.firebase:firebase-database@@16.1.0:212)
        at com.aladdin.FitHub2019Project.userRacePage.UserRaceActivity$1.onDataChange(UserRaceActivity.java:116)
        at com.google.firebase.database.core.ValueEventRegistration.fireEvent(com.google.firebase:firebase-database@@16.1.0:75)
        at com.google.firebase.database.core.view.DataEvent.fire(com.google.firebase:firebase-database@@16.1.0:63)
        at com.google.firebase.database.core.view.EventRaiser$1.run(com.google.firebase:firebase-database@@16.1.0:55)
        at android.os.Handler.handleCallback(Handler.java:873)
        at android.os.Handler.dispatchMessage(Handler.java:99)
        at android.os.Looper.loop(Looper.java:214)
        at android.app.ActivityThread.main(ActivityThread.java:7045)
        at java.lang.reflect.Method.invoke(Native Method)
        at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:493)
        at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:964)

в Logcat, Iполучите эту ошибку, направляющую меня к заданию:

at com.aladdin.FitHub2019Project.userRacePage.UserRaceActivity$1.onDataChange(UserRaceActivity.java:116)

Класс, на который я нацелен, - это то, что пользователи будут участвовать в гонках друг против друга.Этот класс содержит около 600+ строк кода, но полученная ошибка находится в OnCreate - поэтому я буду публиковать только этот раздел кода.Комментарий "// ОШИБКА" - это строка, в которую я попал:

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

        timer = new Stopwatch();

        name=findViewById(R.id.nameTV);
        timerTV=findViewById(R.id.timerTV);
        distanceTV=findViewById(R.id.distanceTV);
        hourET=findViewById(R.id.hourET);
        minET=findViewById(R.id.minET);
        startBtn=findViewById(R.id.startBtn);
        pauseBtn =findViewById(R.id.pauseBtn);
        resetBtn=findViewById(R.id.resetBtn);
        logoutBtn=findViewById(R.id.logoutBtn);
        setTimeBtn=findViewById(R.id.setTimeBtn);
        databaseReference= FirebaseDatabase.getInstance().getReference("RunningUsers");
        startBtn.setOnClickListener(this);
        pauseBtn.setOnClickListener(this);
        logoutBtn.setOnClickListener(this);
        resetBtn.setOnClickListener(this);
        setTimeBtn.setOnClickListener(this);

        locationManager = (LocationManager) getApplicationContext().getSystemService(Context.LOCATION_SERVICE);


        listView=findViewById(R.id.RunningListView);

        Query dr=FirebaseDatabase.getInstance().getReference("RunningUsers").orderByChild("totalSec");
        dr.addValueEventListener(new ValueEventListener() {
            @Override
            public void onDataChange(@NonNull DataSnapshot dataSnapshot) {
                userNameArrayList.clear();userStatusArrayList.clear();userTimerArrayList.clear();userDistanceArrayList.clear();
                for (DataSnapshot s:dataSnapshot.getChildren())
                {

                    RunningUserModel rUM=s.getValue(RunningUserModel.class); //ERROR
                    userNameArrayList.add(rUM.getUserName());
                    userStatusArrayList.add(rUM.getUserStatus());
                    userTimerArrayList.add(rUM.getUserTimer());
                    userDistanceArrayList.add(rUM.getUserDistance());


                }
                Collections.reverse(userNameArrayList);Collections.reverse(userStatusArrayList);Collections.reverse(userTimerArrayList);
                Collections.reverse(userDistanceArrayList);
                customAdapter.notifyDataSetChanged();

            }

            @Override
            public void onCancelled(@NonNull DatabaseError databaseError) {
                Toast.makeText(getApplicationContext(),"error while reading",Toast.LENGTH_SHORT).show();

            }
        });

Код для RunningUserModel приведен ниже:

public class RunningUserModel {
    String userName,userStatus,userTimer;
    double totalSec;
    double userDistance;

    public RunningUserModel()
    {

    }



    public RunningUserModel(String userName, String userStatus, String userTimer, double userDistance, double totalSec) {
        this.userName = userName;
        this.userStatus = userStatus;
        this.userTimer = userTimer;
        this.userDistance = userDistance;
        this.totalSec=totalSec;
    }

    public String getUserName() {
        return userName;
    }

    public String getUserStatus() {
        return userStatus;
    }

    public String getUserTimer() {
        return userTimer;
    }

    public double getUserDistance() {
        return userDistance;
    }
    public double getTotalSec() {return totalSec; }
}

А вот CustomAdapter:

import android.app.Activity;
import android.support.annotation.NonNull;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.TextView;

import com.aladdin.FitHub2019Project.R;

import java.util.ArrayList;

public class CustomAdapterUserRace  extends ArrayAdapter{
    LayoutInflater layoutInflater;
    TextView userNameTV, userStatusTV, userTimerTV, userDistanceTV;

    Activity activity;
    ArrayList<String> userName =new ArrayList<String>();
    ArrayList<String> userStatus =new ArrayList<String>();
    ArrayList<String> userTimer =new ArrayList<String>();;
    ArrayList<Double> userDistance =new ArrayList<Double>();

    public CustomAdapterUserRace(@NonNull Activity activity, ArrayList<String> userName, ArrayList<String>userStatus, ArrayList<String> userTimer, ArrayList<Double> userDistance)
    {
        super(activity, R.layout.runninglistener, userName);

        this.activity=activity;
        this.userName =userName;
        this.userStatus =userStatus;
        this.userTimer =userTimer;
        this.userDistance =userDistance;

        layoutInflater=activity.getLayoutInflater();
    }

    @Override
    public View getView(int position, View convertView, ViewGroup parent)
    {
        convertView=layoutInflater.inflate(R.layout.runninglistener,null);
        userNameTV =convertView.findViewById(R.id.userName);
        userStatusTV =convertView.findViewById(R.id.userStatus);
        userTimerTV =convertView.findViewById(R.id.usertimer);
        userDistanceTV =convertView.findViewById(R.id.userDistance);


        userNameTV.setText(userName.get(position));
        userStatusTV.setText(userStatus.get(position));
        userTimerTV.setText(userTimer.get(position));
        userDistanceTV.setText(String.valueOf(userDistance.get(position)));





        return convertView;
    }


}

Структура базы данных Firebase:

Firebase Database Structure

1 Ответ

0 голосов
/ 04 апреля 2019

Чтобы устранить ошибку, используйте следующее:

    Query dr=FirebaseDatabase.getInstance().getReference("RunningUsers").orderByChild("totalSec");
    dr.addValueEventListener(new ValueEventListener() {
        @Override
        public void onDataChange(@NonNull DataSnapshot dataSnapshot) {
            userNameArrayList.clear();userStatusArrayList.clear();userTimerArrayList.clear();userDistanceArrayList.clear();

            RunningUserModel rUM = dataSnapshot.getValue(RunningUserModel.class); //ERROR
            userNameArrayList.add(rUM.getUserName());
            userStatusArrayList.add(rUM.getUserStatus());
            userTimerArrayList.add(rUM.getUserTimer());
            userDistanceArrayList.add(rUM.getUserDistance());
            Collections.reverse(userNameArrayList);Collections.reverse(userStatusArrayList);Collections.reverse(userTimerArrayList);
            Collections.reverse(userDistanceArrayList);
            customAdapter.notifyDataSetChanged();

        }

        @Override
        public void onCancelled(@NonNull DatabaseError databaseError) {
            Toast.makeText(getApplicationContext(),"error while reading",Toast.LENGTH_SHORT).show();

        }
    });

Удалите цикл for, поскольку при выполнении итерации поля извлекаются как тип String, а не как тип RunningUserModel.

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...