Skip to content
Advertisement

Failed to convert a value of type java.lang.String to int?

I am trying to display the total expenses in a Text view but the application keeps giving me this error. The application uses Firebase and I had the getAmount() and setAmount() initiated as String since I only needed to display. It works as Strings but the amount doesn’t get added to himself it just goes in front of the first amount, like a string. Anyone know what can I do to have my to application reed integer.

I’m using the getAmount() type and it is initiated as an integer.

Error is in the personal fragment inside the addValueEvent Listener HELP!

Personal fragment where the addValueEventListener should display me the total amount.

import android.annotation.SuppressLint;
import android.content.pm.ActivityInfo;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;

import com.firebase.ui.database.FirebaseRecyclerAdapter;
import com.firebase.ui.database.FirebaseRecyclerOptions;
import com.google.firebase.auth.FirebaseAuth;
import com.google.firebase.auth.FirebaseUser;
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.Query;
import com.google.firebase.database.ValueEventListener;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.fragment.app.Fragment;
import androidx.recyclerview.widget.ItemTouchHelper;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

public class personalFragment extends Fragment {

    private FirebaseAuth mAuth;
    private String currentUserID;
    private RecyclerView recyclerView;
    private FirebaseRecyclerAdapter adapter;
    String [] listValue = {};
    private DatabaseReference mDatabase;
    private TextView expense_txt;

    @SuppressLint("SourceLockedOrientationActivity")
    @Nullable
    @Override
    public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        final View myView = inflater.inflate(R.layout.fragment_personal, container, false);


        FirebaseUser user = FirebaseAuth.getInstance().getCurrentUser();
        String uid = user.getUid();
        mDatabase    = FirebaseDatabase.getInstance().getReference("Expenses").child(uid);
        mAuth = FirebaseAuth.getInstance();
        currentUserID = mAuth.getCurrentUser().getUid();
        recyclerView = myView.findViewById(R.id.recycler_expense);
        expense_txt = myView.findViewById(R.id.expenses_txt);
        getActivity().setRequestedOrientation(
                ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);

        final LinearLayoutManager layoutManager = new LinearLayoutManager(getActivity());
        layoutManager.setStackFromEnd(true);
        layoutManager.setReverseLayout(true);
        recyclerView.setHasFixedSize(true);


        Query query = FirebaseDatabase.getInstance()
                .getReference("Expenses")
                .child(currentUserID)
                .limitToLast(100);

        FirebaseRecyclerOptions<PersonalExpenses> options =
                new FirebaseRecyclerOptions.Builder<PersonalExpenses>()
                        .setQuery(query, PersonalExpenses.class)
                        .build();


        adapter = new FirebaseRecyclerAdapter<PersonalExpenses, MyViewHolder>(options) {
            @Override
            protected void onBindViewHolder(final MyViewHolder holder, int position, PersonalExpenses personalExpenses) {


                holder.setDate(personalExpenses.getDate());
                holder.setDescription(personalExpenses.getDescription());
                holder.setAmount(personalExpenses.getAmount());
                holder.setType(personalExpenses.getType());
                //holder.setCurrency(personalExpenses.getCurrency());
            }

            @Override
            public MyViewHolder onCreateViewHolder( ViewGroup parent, int viewType) {
                View view = LayoutInflater.from(parent.getContext())
                        .inflate(R.layout.expense_recycler, parent, false);
                return new MyViewHolder(view);
            }
        };
        recyclerView.setLayoutManager(layoutManager);
        recyclerView.setAdapter(adapter);

        final ItemTouchHelper helper = new ItemTouchHelper(new ItemTouchHelper.SimpleCallback(0, ItemTouchHelper.LEFT) {
            @Override
            public boolean onMove(@NonNull RecyclerView recyclerView, @NonNull RecyclerView.ViewHolder viewHolder, @NonNull RecyclerView.ViewHolder target) {
                return false;
            }

            @Override
            public void onSwiped(@NonNull RecyclerView.ViewHolder target, int i) {

               int swipedPosition = target.getAdapterPosition();
               adapter.notifyDataSetChanged();

            }
        });
        helper.attachToRecyclerView(recyclerView);

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

                int totalsum = 0;
                for(DataSnapshot mySnapshot: dataSnapshot.getChildren()){

                    PersonalExpenses personal = mySnapshot.getValue(PersonalExpenses.class);// Error appears for this line of code
                    totalsum += personal.getAmount(); 

                    String stTotalsum = String.valueOf((totalsum));

                    expense_txt.setText(stTotalsum);
                }



            }

            @Override
            public void onCancelled(@NonNull DatabaseError databaseError) {

            }
        });


        return myView;
    }


    @Override
    public void onStart() {

        super.onStart();
        adapter.startListening();
    }


    @Override
    public void onStop() {

        super.onStop();
        adapter.stopListening();
    }


   public static class MyViewHolder extends RecyclerView.ViewHolder {

        private final View mView;

        public MyViewHolder(View itemView) {
            super(itemView);
            mView = itemView;
        }

        protected void setDate(String date) {
            TextView mDate = mView.findViewById(R.id.date_income);
            mDate.setText(date);
        }

        protected void setType(String type) {
            TextView mType = mView.findViewById(R.id.type_txt);
            mType.setText(type);
        }

        protected void setDescription(String description) {
            TextView mNote = mView.findViewById(R.id.note_txt);
            mNote.setText(description);
        }

        protected void setAmount(int amount) {
            TextView mAmount = mView.findViewById(R.id.ammount_income);
            String strammount = String.valueOf(amount);
            mAmount.setText(strammount);
        }
        /*
       protected void setCurrency(String currency) {
           TextView mCurrency = mView.findViewById(R.id.ammount_income);
           mCurrency.setText(currency);
       }*/
    }
}

Personal Expense data

public class PersonalExpenses {

    public String description;
    public int amount;
    public String date;
    public String type;
    public String currency;

    public PersonalExpenses() {}


    public PersonalExpenses(String description, int amount, String date, String type, String currency) {
        this.amount = amount;
        this.date = date;
        this.type = type;
        this.currency = currency;
        this.description = description;
    }


    public String getDescription() {
        return description;
    }

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

    public int getAmount() { return amount; }

    public void setAmount(int amount) { this.amount = amount; }

    public String getDate() {
        return date;
    }

    public void setDate(String date) {
        this.date = date;
    }

    public String getType() {return type;}

    public void setType(String type) { this.type = type; }

    public String getCurrency() { return currency; }

    public void setCurrency(String currency) { this.currency = currency; }

}

This the error

 com.google.firebase.database.DatabaseException: Failed to convert a value of type java.lang.String to int
        at com.google.firebase.database.core.utilities.encoding.CustomClassMapper.convertInteger(com.google.firebase:firebase-database@@19.2.1:363)
        at com.google.firebase.database.core.utilities.encoding.CustomClassMapper.deserializeToPrimitive(com.google.firebase:firebase-database@@19.2.1:289)
        at com.google.firebase.database.core.utilities.encoding.CustomClassMapper.deserializeToClass(com.google.firebase:firebase-database@@19.2.1:214)
        at com.google.firebase.database.core.utilities.encoding.CustomClassMapper.deserializeToType(com.google.firebase:firebase-database@@19.2.1:178)
        at com.google.firebase.database.core.utilities.encoding.CustomClassMapper.access$100(com.google.firebase:firebase-database@@19.2.1:47)
        at com.google.firebase.database.core.utilities.encoding.CustomClassMapper$BeanMapper.deserialize(com.google.firebase:firebase-database@@19.2.1:592)
        at com.google.firebase.database.core.utilities.encoding.CustomClassMapper$BeanMapper.deserialize(com.google.firebase:firebase-database@@19.2.1:562)
        at com.google.firebase.database.core.utilities.encoding.CustomClassMapper.convertBean(com.google.firebase:firebase-database@@19.2.1:432)
        at com.google.firebase.database.core.utilities.encoding.CustomClassMapper.deserializeToClass(com.google.firebase:firebase-database@@19.2.1:231)
        at com.google.firebase.database.core.utilities.encoding.CustomClassMapper.convertToCustomClass(com.google.firebase:firebase-database@@19.2.1:79)
        at com.google.firebase.database.DataSnapshot.getValue(com.google.firebase:firebase-database@@19.2.1:203)
        at uk.brighton.ama75.project.personalFragment$3.onDataChange(personalFragment.java:118)
        at com.google.firebase.database.core.ValueEventRegistration.fireEvent(com.google.firebase:firebase-database@@19.2.1:75)
        at com.google.firebase.database.core.view.DataEvent.fire(com.google.firebase:firebase-database@@19.2.1:63)
        at com.google.firebase.database.core.view.EventRaiser$1.run(com.google.firebase:firebase-database@@19.2.1:55)
        at android.os.Handler.handleCallback(Handler.java:790)
        at android.os.Handler.dispatchMessage(Handler.java:99)
        at android.os.Looper.loop(Looper.java:164)
        at android.app.ActivityThread.main(ActivityThread.java:6494)
        at java.lang.reflect.Method.invoke(Native Method)
        at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:438)
        at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:807)

Here is the database from Firebase

This is how I am storing the data in the database

expenses.setDescription(mDescription.getText().toString().trim());
                expenses.setAmount(Integer.valueOf(mAmount.getText().toString().trim()));
                expenses.setDate(mDate.getText().toString().trim());
                expenses.setType(text.trim());
                mDatabase.push().setValue(expenses);

Advertisement

Answer

I guess your database is sending getAmount in String format. Use

int totalsum = 0;
for(DataSnapshot mySnapshot: dataSnapshot.getChildren()) {
PersonalExpenses personal = mySnapshot.getValue(PersonalExpenses.class);
totalsum += Integer.parseInt(personal.getAmount());
}
String stTotalsum = String.valueOf(totalsum);
expense_txt.setText(stTotalsum);
User contributions licensed under: CC BY-SA
10 People found this is helpful
Advertisement