Firebase getKey返回long,无法将java.lang.String类型的值转换为long

时间:2018-04-09 12:52:47

标签: java android firebase firebase-realtime-database

我试图从数据库中检索值以显示在视图上,但我现在正在崩溃

  

致命的例外:主要                                                                                过程:com.example.ahmad.carrental,PID:15975                                                                                com.google.firebase.database.DatabaseException:无法将java.lang.String类型的值转换为long                                                                                    在com.google.android.gms.internal.zzear.zzb(未知来源)                                                                                    在com.google.android.gms.internal.zzear.zza(未知来源)                                                                                    在com.google.android.gms.internal.zzear.zzb(未知来源)                                                                                    在com.google.android.gms.internal.zzeas.zze(未知来源)                                                                                    在com.google.android.gms.internal.zzear.zzb(未知来源)                                                                                    在com.google.android.gms.internal.zzear.zza(未知来源)                                                                                    在com.google.firebase.database.DataSnapshot.getValue(未知来源)                                                                                    在com.example.ahmad.carrental.Utilities.FirebaseUtilities.getCarData(FirebaseUtilities.java:178)                                                                                    at com.example.ahmad.carrental.CarPost.CreatePostActivity $ 1 $ 1.onDataChange(CreatePostActivity.java:100)                                                                                    在com.google.android.gms.internal.zzduz.zza(未知来源)                                                                                    在com.google.android.gms.internal.zzdwu.zzbvb(未知来源)                                                                                    在com.google.android.gms.internal.zzdxa.run(未知来源)                                                                                    在android.os.Handler.handleCallback(Handler.java:761)                                                                                    在android.os.Handler.dispatchMessage(Handler.java:98)                                                                                    在android.os.Looper.loop(Looper.java:156)                                                                                    在android.app.ActivityThread.main(ActivityThread.java:6605)                                                                                    at java.lang.reflect.Method.invoke(Native Method)                                                                                    在com.android.internal.os.ZygoteInit $ MethodAndArgsCaller.run(ZygoteInit.java:999)                                                                                    在com.android.internal.os.ZygoteInit.main(ZygoteInit.java:889)

课程如下

汽车模型

public class Car {

    private String brand;
    private String id;
    private int price;
    private String model;
    private long distance;
    private String status;
    private String picture;
    private String location;
    private String description;

    public Car() {
    }

    public Car(String brand, String id, int price, String model, long distance, String status, String picture, String location, String description) {
        this.brand = brand;
        this.id = id;
        this.price = price;
        this.model = model;
        this.distance = distance;
        this.status = status;
        this.picture = picture;
        this.location = location;
        this.description = description;
    }

    public String getBrand() {
        return brand;
    }

    public void setBrand(String brand) {
        this.brand = brand;
    }

    public String getId() {
        return id;
    }

    public void setId(String id) {
        this.id = id;
    }

    public int getPrice() {
        return price;
    }

    public void setPrice(int price) {
        this.price = price;
    }

    public String getModel() {
        return model;
    }

    public void setModel(String model) {
        this.model = model;
    }

    public long getDistance() {
        return distance;
    }

    public void setDistance(long distance) {
        this.distance = distance;
    }

    public String getStatus() {
        return status;
    }

    public void setStatus(String status) {
        this.status = status;
    }

    public String getPicture() {
        return picture;
    }

    public void setPicture(String picture) {
        this.picture = picture;
    }

    public String getLocation() {
        return location;
    }

    public void setLocation(String location) {
        this.location = location;
    }

    public String getDescription() {
        return description;
    }

    public void setDescription(String description) {
        this.description = description;
    }
}

用户模型

  public class User {
        private String email;
        private String id;
        private String name;
        private int phonenumber;

        public User(String email, String id, String name,int phonenumber) {
            this.email = email;
            this.id = id;
            this.name = name;
            this.phonenumber = phonenumber;
        }
        public User(){

        }

        public int getPhonenumber() {
            return phonenumber;
        }

        public void setPhonenumber(int phonenumber) {
            this.phonenumber = phonenumber;
        }

        public String getEmail() {
            return email;
        }

        public void setEmail(String email) {
            this.email = email;
        }

        public String getId() {
            return id;
        }

        public void setId(String id) {
            this.id = id;
        }

        public String getName() {
            return name;
        }

        public void setName(String name) {
            this.name = name;
        }
    }

数据库查询功能

public Car getCarData(DataSnapshot dataSnapshot) {
        Log.i(TAG,"getCardData: Getting car data from database");

        Car data = new Car();
        for(DataSnapshot ds :dataSnapshot.getChildren()){
            if(ds.getKey().equals(context.getString(R.string.dbname_car_post))){
                try{
                    data.setId(ds.child(userID).getValue(Car.class).getId());
                    data.setBrand(ds.child(userID).getValue(Car.class).getBrand());
                    data.setDescription(ds.child(userID).getValue(Car.class).getDescription());
                    data.setModel(ds.child(userID).getValue(Car.class).getModel());
                    data.setDistance(ds.child(userID).getValue(Car.class).getDistance());
                    data.setPicture(ds.child(userID).getValue(Car.class).getPicture());
                    data.setStatus(ds.child(userID).getValue(Car.class).getStatus());
                    data.setLocation(ds.child(userID).getValue(Car.class).getLocation());
                    data.setPrice(ds.child(userID).getValue(Car.class).getPrice());
                }catch (NullPointerException e){
                    Log.d(TAG, "getCarData: NullPointerException : " + e.getMessage());
                }
            }
        }
        return data;
    }

我从

中检索数据的活动

CreateCarPost活动

public class CreatePostActivity extends AppCompatActivity implements CreatePostView,AdapterView.OnItemSelectedListener{

    //Activity Tag
    private static final String TAG ="CreateCarPost";
    //Spinners
    Spinner statusSpinner;
    Spinner brandSpinner;
    //Adapter of spinners
    ArrayAdapter mArrayAdapter;
    ArrayAdapter mArrayAdapter2;

    //views
    private TextView tvDistance;
    private EditText etDistance;
    private AutoCompleteTextView etCarLocation;
    private CircleImageView civPicture;
    private EditText etPrice;
    private EditText etDescription;
    private EditText etModel;
    private ImageView checkButton;

    //Strings
    private String carLoactionStr;
    private String carBrandStr;
    private String carStatusStr;

    //layout containg the views
    private LinearLayout layoutContainer;
    //To adjust dynamic views margins
    LinearLayout.LayoutParams layoutParamsTv,layoutParamsEt;

    //Firebase
    private FirebaseAuth mAuth;
    private FirebaseAuth.AuthStateListener mAuthStateListener;
    private FirebaseDatabase mFirebaseDatabase;
    private DatabaseReference mDatabaseReference;
    private ValueEventListener singleValueEventListener;
    private FirebaseUtilities mFirebaseUtilities;

    Context mContext;
    CreatePostPresenter createPostPresenter;
    private Car car;

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

        initialization();
        setupFirebaseAuth();
        setUpLocationSpinner();


        //Assigning Car object with its data from database.
        io.reactivex.Observable.create(new ObservableOnSubscribe() {
            @Override
            public void subscribe(ObservableEmitter emitter) throws Exception {
                singleValueEventListener = new ValueEventListener() {
                    @Override
                    public void onDataChange(DataSnapshot dataSnapshot) {
                        car = mFirebaseUtilities.getCarData(dataSnapshot);
                    }

                    @Override
                    public void onCancelled(DatabaseError databaseError) {
                        Log.e(TAG, "CANCELLED.");
                    }
                };
                mDatabaseReference.addValueEventListener(singleValueEventListener);
            }
        }).unsubscribeOn(Schedulers.io()).observeOn(AndroidSchedulers.mainThread()).subscribe();


        checkButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                createPostPresenter.onSaveChanges(car);
            }
        });

    }

    //initalizing everything necessary here
    public void initialization(){

        mContext = getApplicationContext();
        createPostPresenter = new CreatePostPresenter(this,this);

        //Adapter set up for spinners
        mArrayAdapter2 = ArrayAdapter.createFromResource(this,R.array.car_brands,android.R.layout.simple_spinner_item);
        mArrayAdapter = ArrayAdapter.createFromResource(this,R.array.car_status_array,android.R.layout.simple_spinner_item);

        //Status spinner set up
        statusSpinner = findViewById(R.id.createPostCarStatusSpinner_ID);
        statusSpinner.setAdapter(mArrayAdapter);
        statusSpinner.setOnItemSelectedListener(this);
        //Brand spinner set up
        brandSpinner = findViewById(R.id.createPostCarBrandSpinner_ID);
        brandSpinner.setAdapter(mArrayAdapter2);
        brandSpinner.setOnItemSelectedListener(this);

        layoutContainer = findViewById(R.id.createPostLinearLayout_ID);
        tvDistance = new TextView(this);
        tvDistance.setLayoutParams(new LinearLayout.LayoutParams(ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT));
        tvDistance.setText("Distance Travelled");
        etDistance = new EditText(this);
        etDistance.setLayoutParams(new LinearLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT));

        //margin settings editText
        layoutParamsEt = (LinearLayout.LayoutParams)etDistance.getLayoutParams();
        layoutParamsEt.setMargins(0,10,0,0);
        etDistance.setLayoutParams(layoutParamsEt);

        //margin settings textView
        layoutParamsTv = (LinearLayout.LayoutParams)tvDistance.getLayoutParams();
        layoutParamsTv.setMargins(0,10,0,0);
        tvDistance.setLayoutParams(layoutParamsTv);

        etCarLocation = findViewById(R.id.createPostCarLocation_ID);
        etDescription = findViewById(R.id.createPostCarDes_ID);
        etPrice = findViewById(R.id.createPostCarPrice_ID);
        etModel = findViewById(R.id.createPostCarModel_ID);
        checkButton = findViewById(R.id.check_ID);
        mFirebaseUtilities = new FirebaseUtilities(this);
    }

    private void setUpLocationSpinner() {

        ArrayAdapter<String> listOfCities = new ArrayAdapter<>(getBaseContext(),
                android.R.layout.simple_list_item_1, getResources().getStringArray(R.array.TR_cities));

        //--- to ensure user is restricted to selections from drop-down menu
        etCarLocation.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                carLoactionStr = etCarLocation.getAdapter().getItem(position).toString();
            }
        });

        etCarLocation.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {
            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {
                for (int i = 0; i < etCarLocation.getAdapter().getCount(); i++) {
                    if (etCarLocation.getText().toString().equals(etCarLocation.getAdapter().getItem(i))) {
                        carLoactionStr = etCarLocation.getAdapter().getItem(i).toString();
                    } else
                        carLoactionStr = null;
                }
            }

            @Override
            public void afterTextChanged(Editable s) {
            }
        });


        //start autocomplete after 1 letter
        etCarLocation.setThreshold(1);
        etCarLocation.performCompletion();
        etCarLocation.setAdapter(listOfCities);
    }

    /**
     * Listener for car status spinner
     * @param parent
     * @param view
     * @param position
     * @param id
     */
    @Override
    public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
        Spinner spinner = (Spinner)parent;

        if(spinner.getId() == R.id.createPostCarStatusSpinner_ID){
            TextView textView = (TextView) view;
            carStatusStr = textView.getText().toString();
            addDynamicViews(position);
        }
        else if(spinner.getId() == R.id.createPostCarBrandSpinner_ID){
            TextView textView = (TextView) view;
            carBrandStr = textView.getText().toString();
        }

    }

    @Override
    public void onNothingSelected(AdapterView<?> parent) {

    }

    /**
     * Dynamic views creation done by handling user spinner selection for first hand or second hand car status.
     *@param position: position of selected value from spinner
     */
    public void addDynamicViews(int position){
        if(position == 1){
            layoutContainer.addView(tvDistance);
            layoutContainer.addView(etDistance);
        }
        else if(position == 0){
            mFirebaseUtilities.removeNodeDynamically();
            layoutContainer.removeView(tvDistance);
            layoutContainer.removeView(etDistance);
        }
    }

    @Override
    public void setBrand(String brand) {

    }

    @Override
    public void setPrice(int price) {

    }

    @Override
    public void setLocation(String location) {

    }

    @Override
    public void setDescription(String description) {

    }

    @Override
    public void setModel(String model) {

    }

    @Override
    public void setDistance(long distance) {

    }

    @Override
    public void setStatus(String status) {

    }

    @Override
    public void setPicture(String picture) {

    }

    @Override
    public String getBrand() {
        return carBrandStr;
    }

    @Override
    public String getDescription() {
        return etDescription.getText().toString();
    }

    @Override
    public String getLocation() {
        return carLoactionStr;
    }

    @Override
    public String getModel() {
        return etModel.getText().toString();
    }

    @Override
    public String getStatus() {
        return carStatusStr;
    }

    @Override
    public String getPicture() {
        return null;
    }

    @Override
    public int getPrice() {
        String priceViewTemp = etPrice.getText().toString();
        if (priceViewTemp.equals("")) {
            return 0;
        } else {
            return Integer.valueOf(etPrice.getText().toString());
        }
    }

    @Override
    public long getDistance() {
        String distanceViewTemp = etDistance.getText().toString();
        if (distanceViewTemp.equals("")) {
            return 0;
        } else {
            return Integer.valueOf(etDistance.getText().toString());
        }
    }

    /*************************************** Firebase *******************************************/
    private void setupFirebaseAuth() {
        mAuth = FirebaseAuth.getInstance();

        mFirebaseDatabase = FirebaseDatabase.getInstance();
        mDatabaseReference = mFirebaseDatabase.getReference();

        mAuthStateListener = new FirebaseAuth.AuthStateListener() {
            @Override
            public void onAuthStateChanged(@NonNull FirebaseAuth firebaseAuth) {
                FirebaseUser user = firebaseAuth.getCurrentUser();

                if (user != null) {
                    //User is signed in
                    Log.d(TAG, "onAuthStateChanged: user signed in : " + user.getUid());
                } else {
                    //User is signed out
                    Log.d(TAG, "onAuthStateChanged: user signed out");
                }
            }
        };

        mDatabaseReference.addValueEventListener(new ValueEventListener() {
            @Override
            public void onDataChange(DataSnapshot dataSnapshot) {


            }

            @Override
            public void onCancelled(DatabaseError databaseError) {

            }
        });
    }
    @Override
    public void onPause() {
        super.onPause();
        if (singleValueEventListener != null) {
            mDatabaseReference.removeEventListener(singleValueEventListener);
        }
    }
    @Override
    public void onResume(){
        super.onResume();
        mDatabaseReference.addListenerForSingleValueEvent(singleValueEventListener);
    }

}

Firebase结构

Firebase Structure

1 个答案:

答案 0 :(得分:0)

Haven没有读过多少,但我第一次注意到了这里。

for(DataSnapshot ds :dataSnapshot.getChildren()){
        if(ds.getKey().equals(context.getString(R.string.dbname_car_post))){
            try{ }

您尝试检索的密钥是对象。所以我建议我们首先将它转换为字符串,然后在此处进行采样。

for(DataSnapshot ds :dataSnapshot.getChildren()){
    Object myKey=ds.getKey;
        if(myKey.toString().equals(context.getString(R.string.dbname_car_post))){
            try{ }

}}

让我知道接下来会发生什么!