В коде происходит сбой из-за следующей ошибки: невозможно преобразовать объект типа java .lang.String в тип - PullRequest
0 голосов
/ 03 мая 2020

Мой код работал отлично. Затем я обновил Android Studio, и теперь приложение продолжает обрабатывать sh со следующей ошибкой: «Не удается преобразовать объект типа java .lang.String в тип». Я вернул версию к предыдущей версии, когда она работала, и я все еще получаю ту же ошибку. Любая помощь будет принята с благодарностью. Спасибо!

Error Log:
2020-05-03 15:15:17.133 24783-24783/com.example.updatedhapana1 E/AndroidRuntime: FATAL EXCEPTION: main
    Process: com.example.updatedhapana1, PID: 24783
    com.google.firebase.database.DatabaseException: Can't convert object of type java.lang.String to type com.example.updatedhapana1.Personal_Posts
        at com.google.firebase.database.core.utilities.encoding.CustomClassMapper.convertBean(com.google.firebase:firebase-database@@19.3.0:435)
        at com.google.firebase.database.core.utilities.encoding.CustomClassMapper.deserializeToClass(com.google.firebase:firebase-database@@19.3.0:231)
        at com.google.firebase.database.core.utilities.encoding.CustomClassMapper.convertToCustomClass(com.google.firebase:firebase-database@@19.3.0:79)
        at com.google.firebase.database.DataSnapshot.getValue(com.google.firebase:firebase-database@@19.3.0:203)
        at com.firebase.ui.database.ClassSnapshotParser.parseSnapshot(ClassSnapshotParser.java:29)
        at com.firebase.ui.database.ClassSnapshotParser.parseSnapshot(ClassSnapshotParser.java:15)
        at com.firebase.ui.common.BaseCachingSnapshotParser.parseSnapshot(BaseCachingSnapshotParser.java:36)
        at com.firebase.ui.common.BaseObservableSnapshotArray.get(BaseObservableSnapshotArray.java:52)
        at com.firebase.ui.database.FirebaseRecyclerAdapter.getItem(FirebaseRecyclerAdapter.java:109)
        at com.firebase.ui.database.FirebaseRecyclerAdapter.onBindViewHolder(FirebaseRecyclerAdapter.java:149)
        at androidx.recyclerview.widget.RecyclerView$Adapter.onBindViewHolder(RecyclerView.java:7065)
        at androidx.recyclerview.widget.RecyclerView$Adapter.bindViewHolder(RecyclerView.java:7107)
        at androidx.recyclerview.widget.RecyclerView$Recycler.tryBindViewHolderByDeadline(RecyclerView.java:6012)
        at androidx.recyclerview.widget.RecyclerView$Recycler.tryGetViewHolderForPositionByDeadline(RecyclerView.java:6279)
        at androidx.recyclerview.widget.RecyclerView$Recycler.getViewForPosition(RecyclerView.java:6118)
        at androidx.recyclerview.widget.RecyclerView$Recycler.getViewForPosition(RecyclerView.java:6114)
        at androidx.recyclerview.widget.LinearLayoutManager$LayoutState.next(LinearLayoutManager.java:2303)
        at androidx.recyclerview.widget.LinearLayoutManager.layoutChunk(LinearLayoutManager.java:1627)
        at androidx.recyclerview.widget.LinearLayoutManager.fill(LinearLayoutManager.java:1587)
        at androidx.recyclerview.widget.LinearLayoutManager.onLayoutChildren(LinearLayoutManager.java:665)
        at androidx.recyclerview.widget.RecyclerView.dispatchLayoutStep2(RecyclerView.java:4134)
        at androidx.recyclerview.widget.RecyclerView.onMeasure(RecyclerView.java:3540)
        at android.view.View.measure(View.java:24710)
        at android.view.ViewGroup.measureChildWithMargins(ViewGroup.java:6858)
        at android.widget.FrameLayout.onMeasure(FrameLayout.java:194)
        at android.view.View.measure(View.java:24710)
        at android.view.ViewGroup.measureChildWithMargins(ViewGroup.java:6858)
        at android.widget.LinearLayout.measureChildBeforeLayout(LinearLayout.java:1552)
        at android.widget.LinearLayout.measureVertical(LinearLayout.java:842)
        at android.widget.LinearLayout.onMeasure(LinearLayout.java:721)
        at android.view.View.measure(View.java:24710)
        at androidx.core.widget.NestedScrollView.measureChildWithMargins(NestedScrollView.java:1534)
        at android.widget.FrameLayout.onMeasure(FrameLayout.java:194)
        at androidx.core.widget.NestedScrollView.onMeasure(NestedScrollView.java:581)
        at android.view.View.measure(View.java:24710)
        at androidx.drawerlayout.widget.DrawerLayout.onMeasure(DrawerLayout.java:1119)
        at android.view.View.measure(View.java:24710)
        at android.view.ViewGroup.measureChildWithMargins(ViewGroup.java:6858)
        at android.widget.FrameLayout.onMeasure(FrameLayout.java:194)
        at androidx.appcompat.widget.ContentFrameLayout.onMeasure(ContentFrameLayout.java:143)
        at android.view.View.measure(View.java:24710)
        at android.view.ViewGroup.measureChildWithMargins(ViewGroup.java:6858)
        at android.widget.LinearLayout.measureChildBeforeLayout(LinearLayout.java:1552)
        at android.widget.LinearLayout.measureVertical(LinearLayout.java:842)
2020-05-03 15:15:17.133 24783-24783/com.example.updatedhapana1 E/AndroidRuntime:     at android.widget.LinearLayout.onMeasure(LinearLayout.java:721)
        at android.view.View.measure(View.java:24710)
        at android.view.ViewGroup.measureChildWithMargins(ViewGroup.java:6858)
        at android.widget.FrameLayout.onMeasure(FrameLayout.java:194)
        at android.view.View.measure(View.java:24710)
        at android.view.ViewGroup.measureChildWithMargins(ViewGroup.java:6858)
        at android.widget.LinearLayout.measureChildBeforeLayout(LinearLayout.java:1552)
        at android.widget.LinearLayout.measureVertical(LinearLayout.java:842)
        at android.widget.LinearLayout.onMeasure(LinearLayout.java:721)
        at android.view.View.measure(View.java:24710)
        at android.view.ViewGroup.measureChildWithMargins(ViewGroup.java:6858)
        at android.widget.FrameLayout.onMeasure(FrameLayout.java:194)
        at com.android.internal.policy.DecorView.onMeasure(DecorView.java:749)
        at android.view.View.measure(View.java:24710)
        at android.view.ViewRootImpl.performMeasure(ViewRootImpl.java:3259)
        at android.view.ViewRootImpl.measureHierarchy(ViewRootImpl.java:2042)
        at android.view.ViewRootImpl.performTraversals(ViewRootImpl.java:2337)
        at android.view.ViewRootImpl.doTraversal(ViewRootImpl.java:1930)
        at android.view.ViewRootImpl$TraversalRunnable.run(ViewRootImpl.java:8018)
        at android.view.Choreographer$CallbackRecord.run(Choreographer.java:1163)
        at android.view.Choreographer.doCallbacks(Choreographer.java:986)
        at android.view.Choreographer.doFrame(Choreographer.java:902)
        at android.view.Choreographer$FrameDisplayEventReceiver.run(Choreographer.java:1148)
        at android.os.Handler.handleCallback(Handler.java:883)
        at android.os.Handler.dispatchMessage(Handler.java:100)
        at android.os.Looper.loop(Looper.java:214)
        at android.app.ActivityThread.main(ActivityThread.java:7682)
        at java.lang.reflect.Method.invoke(Native Method)
        at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:516)
        at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:950)





    public class Personal_Posts {
    private String firstname, lastname, profileimage, banner_images;
    public Personal_Posts()
        {

        }

        public Personal_Posts(String firstname, String lastname, String profileimage, String banner_images) {
            this.firstname = firstname;
            this.lastname = lastname;
            this.profileimage = profileimage;
            this.banner_images = banner_images;
        }

        public String getFirstname() {
            return firstname;
        }

        public void setFirstname(String firstname) {
            this.firstname = firstname;
        }

        public String getLastname() {
            return lastname;
        }

    public void setLastname(String lastname) {
        this.lastname = lastname;
    }

    public String getProfileimage() {
        return profileimage;
    }

    public void setProfileimage(String profileimage) {
        this.profileimage = profileimage;
    }

    public String getBanner_images() {
        return banner_images;
    }

    public void setBanner_images(String banner_images) {
        this.banner_images = banner_images;
    }


}








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

        mAuth = FirebaseAuth.getInstance();



        Toolbar toolbar = findViewById(R.id.toolbar);
        setSupportActionBar(toolbar);
        //this tells our system to actually use the toolbar as the actionbar.


        drawer = findViewById(R.id.drawer_layout);
        NavigationView navigationView = findViewById(R.id.nav_view);
        navigationView.setNavigationItemSelectedListener(this);

        ActionBarDrawerToggle toggle = new ActionBarDrawerToggle(this, drawer, toolbar, R.string.navigation_drawer_open, R.string.navigation_drawer_close);
        drawer.addDrawerListener(toggle);
        toggle.syncState();

        //Button to navigate to profile edit page//
        Button personal_wall_button = findViewById(R.id.navigate_to_profile_page);
        personal_wall_button.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                startActivity(new Intent(MainActivity.this, Personal_Wall.class));
            }
        });
        //Button to navigate to profile edit page//


        //RecyclerView
        mRecyclerView = findViewById(R.id.recyclerView);
        mRecyclerView.setHasFixedSize(true);
        //RecyclerView


        //set layout as Linear Layout
        mRecyclerView.setLayoutManager(new LinearLayoutManager(this));


        //send Query to FirebaseDatabase
        mfirebaseDatabase = FirebaseDatabase.getInstance();
        UsersReference = mfirebaseDatabase.getReference("Users");





    }


    //load data into recycler view onStart

    @Override
    protected  void onStart() {
        super.onStart();

        FirebaseRecyclerOptions<Personal_Posts> options =
                new FirebaseRecyclerOptions.Builder<Personal_Posts>()
                        .setQuery(UsersReference, Personal_Posts.class)
                        .build();

        FirebaseRecyclerAdapter<Personal_Posts, Personal_Post_ViewHolder> firebaseRecyclerAdapter =
                new FirebaseRecyclerAdapter<Personal_Posts, Personal_Post_ViewHolder>(options) {
                    @Override
                    protected void onBindViewHolder(@NonNull Personal_Post_ViewHolder holder, int position, @NonNull Personal_Posts model) {
                        holder.textViewFirst.setText(model.getFirstname());
                        holder.textViewLast.setText(model.getLastname());
                        Picasso.get().load(model.getBanner_images()).into(holder.imageViewBanner);
                        Picasso.get().load(model.getProfileimage()).into(holder.imageViewProfilePicture);


                    }

                    @NonNull
                    @Override
                    public Personal_Post_ViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
                        View v = LayoutInflater.from(parent.getContext()).inflate(R.layout.post_layout, parent, false);

                        return new Personal_Post_ViewHolder(v);
                    }
                };
        firebaseRecyclerAdapter.startListening();
        mRecyclerView.setAdapter(firebaseRecyclerAdapter);

    }







    @Override
    public boolean onNavigationItemSelected(@NonNull MenuItem item) {
        switch (item.getItemId()) {
            case R.id.log_out:
                LogOut();
                break;

        }
        return true;


    }


    @Override
    public void onBackPressed() {
        if (drawer.isDrawerOpen(GravityCompat.START)) {
            drawer.closeDrawer(GravityCompat.START);
        } else {
            super.onBackPressed();
        }
    }

    // Attempting to create log out button for navigation menu//

    private void LogOut() {
        FirebaseAuth.getInstance().signOut();
        sendToLogin();
    }

    private void sendToLogin() {

        Intent loginIntent = new Intent(MainActivity.this, Login_Activity.class);
        startActivity(loginIntent);
        finish();

    }


}








  [1]: https://i.stack.imgur.com/m3A8f.png

1 Ответ

0 голосов
/ 03 мая 2020

Как видно из журнала ошибок, вы пытаетесь сохранить данные в типе объекта Personal_Posts, но данные, поступающие из базы данных, имеют тип String. Таким образом, вы не можете привести строковый объект к Personal_Posts.

Проверьте свой onBindViewHolder () в классе адаптера, где вы можете пытаться получить данные из DataSnapshot.

...