简体   繁体   中英

No suitable method found for makeText

I seem to be getting this error, I'm new to Android Studio and I'm trying to get names from an array into a ListView then when user taps on the any of the list a Toast is activated. But I seem to be stuck with this error below:

error: no suitable method found for makeText(MainActivity,Object,int)
method Toast.makeText(Context,CharSequence,int) is not applicable
(argument mismatch; Object cannot be converted to CharSequence)
method Toast.makeText(Context,int,int) is not applicable
(argument mismatch; Object cannot be converted to int)

Here's my code:

final ArrayList names = new ArrayList();
names.add("Samuel");
names.add("Manuel");
names.add("King");

listv.setOnItemClickListener(new AdapterView.OnItemClickListener() {
    @Override
    public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
        Toast.makeText(MainActivity.this, names.get(position), Toast.LENGTH_LONG).show();
    }
});

What is the problem and how can I fix this?

I think your ArrayList is defaulting to the type Object because you didn't specify String when you instantiated it. If this is true then when you call names.get(position) it would be returning you an Object instead of a String which is causing a problem for you because the Toast.makeText() method is expecting arguments of types (Context,CharSequence,int) rather than what you are passing it which is (Context,Object,int)

Note that CharSequence and String can be treated as the same for your purposes in this case.

If this theory is correct you could resolve the problem a few different ways.

  1. you could call toString() to explicitly convert your object to a string. Like this:

    Toast.makeText(MainActivity.this, names.get(position).toString(), Toast.LENGTH_LONG).show();

or 2) you could declare the type of String when you initialize your ArrayList Like this:

final ArrayList<String> names = new ArrayList<>();

then your call of names.get(position) should be returning a String instead of an Object

Change to:

Toast.makeText(MainActivity.this, String.valueOf(names.get(position)), Toast.LENGTH_LONG).show();

In Toast class there is no method makeText(MainActivity, Object, int) with this arg that is the reason you are getting this error.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM