com.google.firebase.database.DatabaseException:无法将java.lang.String类型的对象转换为Recensione

时间:2017-01-21 17:53:20

标签: android firebase firebase-realtime-database android-recyclerview

我有一个问题,很多人有,但我不明白我怎么能摆脱它。在我的情况下请帮助我,不要标记为重复。我在一个片段中有一个与firebase链接的recyclerview。 我必须检索“recensione”背后的所有项目。 所有项目都有一些文本视图,从数据库中写入一些字符串。但是当我尝试检索数据库中的项目时,我收到错误:

com.google.firebase.database.DatabaseException: Can't convert object of type java.lang.String to type com.ji.architettiadvisor.Data.Recensione
                                                                             at com.google.android.gms.internal.zzbqi.zze(Unknown Source)
                                                                             at com.google.android.gms.internal.zzbqi.zzb(Unknown Source)
                                                                             at com.google.android.gms.internal.zzbqi.zza(Unknown Source)
                                                                             at com.google.firebase.database.DataSnapshot.getValue(Unknown Source)
                                                                             at com.ji.architettiadvisor.DisplayStudio$PlaceholderFragment.getUpdates(DisplayStudio.java:337)
                                                                             at com.ji.architettiadvisor.DisplayStudio$PlaceholderFragment.access$000(DisplayStudio.java:233)
                                                                             at com.ji.architettiadvisor.DisplayStudio$PlaceholderFragment$1.onChildAdded(DisplayStudio.java:358)
                                                                             at com.google.android.gms.internal.zzblz.zza(Unknown Source)
                                                                             at com.google.android.gms.internal.zzbnz.zzYj(Unknown Source)
                                                                             at com.google.android.gms.internal.zzboc$1.run(Unknown Source)
                                                                             at android.os.Handler.handleCallback(Handler.java:739)
                                                                             at android.os.Handler.dispatchMessage(Handler.java:95)
                                                                             at android.os.Looper.loop(Looper.java:148)
                                                                             at android.app.ActivityThread.main(ActivityThread.java:5461)
                                                                             at java.lang.reflect.Method.invoke(Native Method)
                                                                             at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:726)
                                                                             at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:616)

这是我的Recensione.class:

public class Recensione {
private String Commento;
private String Rating;
private String Username;
private String Data;

public String getData() {
    return Data;
}

public void setData(String data) {
    Data = data;
}

public String getUsername() {
    return Username;
}

public void setUsername(String username) {
    Username = username;
}

public String getRating() {
    return Rating;
}

public void setRating(String rating) {
    Rating = rating;
}


public String getCommento() {
    return Commento;
}

public void setCommento(String commento) {
    Commento = commento;
}}

这里是我的PlaceholderFragment / DisplayStudio.class:

public static class PlaceholderFragment extends Fragment implements OnMapReadyCallback {

    private GoogleMap googleMapa;

    /**
     * The fragment argument representing the section number for this
     * fragment.
     */
    private static final String ARG_SECTION_NUMBER = "section_number";

    public PlaceholderFragment() {
    }

    /**
     * Returns a new instance of this fragment for the given section
     * number.
     */
    public static DisplayStudio.PlaceholderFragment newInstance(int sectionNumber) {
        DisplayStudio.PlaceholderFragment fragment = new DisplayStudio.PlaceholderFragment();
        Bundle args = new Bundle();
        args.putInt(ARG_SECTION_NUMBER, sectionNumber);
        fragment.setArguments(args);
        return fragment;
    }

    RecyclerView rv;
    MyCommentsAdapter adapter;
    ArrayList<Recensione> recensioni = new ArrayList<>();
    DatabaseReference mDatabase;
    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        Bundle bl = getArguments();
        if (getArguments().getInt(ARG_SECTION_NUMBER)==1)
        {

            View rootView = inflater.inflate(R.layout.fragment_profilo, container, false);

            Intent intent = getActivity().getIntent();

            String desc = intent.getStringExtra("Desc");
            final String names = intent.getStringExtra("Nome");

            TextView test = (TextView) rootView.findViewById(R.id.nome);
            TextView descr = (TextView) rootView.findViewById(R.id.desc);
            TextView key = (TextView) rootView.findViewById(R.id.key);

            test.setText(names);
            descr.setText(desc);

            String MyKey = bl.getString(MY_STUDIO_KEY);
            key.setText(MyKey);

        return rootView;
        }
        else if(getArguments().getInt(ARG_SECTION_NUMBER)==2)
        {


            Intent intent = getActivity().getIntent();
            final String names = intent.getStringExtra("Nome");

            //INITIALIZE FIREBASE
            mDatabase = FirebaseDatabase.getInstance().getReference().child("Studi").child(names).child("valutazioni").child("recensioni");
            mDatabase.keepSynced(true);
            /* Ricarica tutte le opinioni */
            refreshData();
            View rootView = inflater.inflate(R.layout.fragment_opinioni, container, false);
            rv = (RecyclerView) rootView.findViewById(R.id.MyRecView2s);

            Recensione rc = new Recensione();
            rc.setUsername("Luca");
            rc.setCommento("Non male, da app");
            rc.setRating("10");
            rc.setData("oggi");
            //ci vuole il push prima del setvalue
            mDatabase.child(names).setValue(rc);
            rv.setLayoutManager(new LinearLayoutManager(getActivity()));

            return rootView;
        }
        else
        {
            View rootView = inflater.inflate(R.layout.fragment_maps, container, false);
            SupportMapFragment mapFragment = SupportMapFragment.newInstance();
            getChildFragmentManager().beginTransaction().replace(R.id.map , mapFragment).commit();
            mapFragment.getMapAsync(this);


            if (mapFragment == null) {
                getChildFragmentManager().beginTransaction().replace(R.id.map , mapFragment).commit();
                mapFragment.getMapAsync(this);
            }


            return rootView;
        }
    }
    private void getUpdates(DataSnapshot dataSnapshot){

        recensioni.clear();

        for (DataSnapshot ds : dataSnapshot.getChildren()){
            Recensione s=new Recensione();
            s.setUsername(ds.getValue(Recensione.class).getUsername());
            s.setCommento(ds.getValue(Recensione.class).getCommento());
            s.setRating(ds.getValue(Recensione.class).getRating());
            s.setData(ds.getValue(Recensione.class).getData());
            recensioni.add(s);
        }

        if(recensioni.size()>0){
            adapter=new MyCommentsAdapter(getActivity(), recensioni);
            rv.setAdapter(adapter);
        }else {
            Toast.makeText(getActivity(),"NON CI SONO ANCORA OPINIONI.", Toast.LENGTH_LONG).show();

        }
    }
    //RETRIEVE
    private void refreshData(){

        mDatabase.addChildEventListener(new ChildEventListener() {
            @Override
            public void onChildAdded(DataSnapshot dataSnapshot, String s) {
                getUpdates(dataSnapshot);
            }

            @Override
            public void onChildChanged(DataSnapshot dataSnapshot, String s) {
                getUpdates(dataSnapshot);
            }

            @Override
            public void onChildRemoved(DataSnapshot dataSnapshot) {

            }

            @Override
            public void onChildMoved(DataSnapshot dataSnapshot, String s) {

            }

            @Override
            public void onCancelled(DatabaseError databaseError) {

            }
        });

    }

    @Override
    public void onMapReady(GoogleMap googleMap) {
        googleMapa = googleMap;
        Intent intent = getActivity().getIntent();

        final String names = intent.getStringExtra("Nome");

        String posizione1 = intent.getStringExtra("Posizione1");
        String posizione2 = intent.getStringExtra("Posizione2");

        try
        {
            //Toast.makeText(MapsActivity.this,posizione1 + " " + posizione2 , Toast.LENGTH_LONG).show();   //not a double
            Double protein = Double.parseDouble(posizione1);
            Double protein2 = Double.parseDouble(posizione2);
             LatLng sydney = new LatLng(protein,protein2);                                                                           //custom icon in drawable
            googleMap.addMarker(new MarkerOptions().position(sydney).title(names)/*.icon(BitmapDescriptorFactory.fromResource(R.drawable.cast_abc_scrubber_control_off_mtrl_alpha))*/);
            googleMap.moveCamera(CameraUpdateFactory.newLatLngZoom(sydney, 12.0f));

        }
        catch(NumberFormatException e)
        {
            //  Toast.makeText(DisplayStudio.this, e.toString() , Toast.LENGTH_LONG).show();   //not a double
        }



    }
}

/**
 * A {@link FragmentPagerAdapter} that returns a fragment corresponding to
 * one of the sections/tabs/pages.
 */
public class SectionsPagerAdapter extends FragmentPagerAdapter {

    public SectionsPagerAdapter(FragmentManager fm) {
        super(fm);
    }

    @Override
    public Fragment getItem(int position) {
        // getItem is called to instantiate the fragment for the given page.
        // Return a PlaceholderFragment (defined as a static inner class below).
        return DisplayStudio.PlaceholderFragment.newInstance(position + 1);
    }

    @Override
    public int getCount() {
        // Show 3 total pages.
        return 3;
    }

    @Override
    public CharSequence getPageTitle(int position) {
        switch (position) {
            case 0:
                return "PROFILO";
            case 1:
                return "OPINIONI";
            case 2:
                return "MAPS";
        }
        return null;
    }
}}

一切都在这项活动的最底层。 每个不同的“recensione”都有自定义的公布id无关紧要......

What i need to retrieve

我该如何解决?我真的不知道,我不明白什么是错的,对不起,但我是新来的。

1 个答案:

答案 0 :(得分:0)

方法Datasnapshot.getValue()的参数是您要将值转换为的类。您可能正在尝试将其投射到String。将您的getUpdates方法更改为如下所示:

private void getUpdates(DataSnapshot dataSnapshot){
    recensioni.clear();
    for (DataSnapshot ds : dataSnapshot.getChildren()){
        Recensione s=new Recensione();
        s.setUsername(ds.getValue(String.class));
        s.setCommento(ds.getValue(String.class));
        s.setRating(ds.getValue(String.class));
        s.setData(ds.getValue(String.class));
        recensioni.add(s);
    }

    if(recensioni.size()>0){
        adapter=new MyCommentsAdapter(getActivity(), recensioni);
        rv.setAdapter(adapter);
    }else {
        Toast.makeText(getActivity(),"NON CI SONO ANCORA OPINIONI.", Toast.LENGTH_LONG).show();
    }
}