lilbiscuit
lilbiscuit

Reputation: 2249

incompatible types error on ListView of custom objects

I have a ListView of custom objects (MyCustomObj) and I am using a custom adapter. The ListView displays the list of objects perfectly.

I want to update an individual item in the list when an event occurs. So in the activity, I have:

private ListView parentLayout;
MyCustomObj customObj;

And then I am trying to pass an index i to access the specific item to be updated as follows:

customObj = parentLayout.getAdapter().getItem(i);

But this generates the error incompatible types. Required: MyCustomObj, Found: java.lang.Object

So I change the object initialization to:

Object customObj

The error goes away, but the object actually appears to be a MyCustomObj, because when I output customObject to console, the output is com.myapp.MyCustomObj@12ab34cd.

But setters/getters are not available on this object in Android Studio since it's an Object and not a MyCustomObj.

For example, if I want to change the id attribute, normally I'd do this:

customObj.setId(123); but this leads to cannot resolve errors even though setId is a proper setter in MyCustomObj class.

What's the proper way to access an individual object and update it, and why is the console showing the custom object? (I understand that after updating the object I will need to execute notifyDataSetChanged() )

The adapter looks something like this:

public class MyCustomManager extends ArrayAdapter<MyCustomObj> {
    public MyCustomManager(Context context, ArrayList<MyCustomObj> customObjects) {
        super(context, 0, customObjects);
    }

    @Override
    public View getView(int position, View customView, ViewGroup parent) {
        // Get the data item for this position
        MyCustomObj customObj = getItem(position);

        // Check if an existing view is being reused, otherwise inflate the view
        if (customView == null) {
            customView = LayoutInflater.from(getContext()).inflate(R.layout.template_my_custom_view, parent, false);
        }

        // Sets the tag
        customView.setTag(customObj.getId());

        //other view stuff goes here

        // Return the completed view to render on screen
        return customView;
    }
}

Upvotes: 0

Views: 143

Answers (1)

user12517395
user12517395

Reputation:

Try to cast the object as MyCustomObj

MyCustomObj  customObj = (MyCustomObj) parentLayout.getAdapter().getItem(i);

Upvotes: 1

Related Questions