Woowoo Woowoo - 2 months ago 13
Android Question

Error "Cannot resolve symbol 'listView'" for a CustomListAdapter

I am currently working on a basic custom ListAdapater.

On my MainActivity, it shows this error when trying to find my ListView from my XML file.

Here is my MainActivity.java:

public class MainActivity extends ListActivity {

ListView list;

String[] itemName = {
"Item 1",
"Item 2",
"Item 3"
};
String [] itemContent = {
"Item Content 1",
"Item Content 2",
"Item Content 3"
};

Integer[] imageId = {
R.mipmap.pic1,
R.mipmap.pic2,
R.mipmap.pic3,
};

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

CustomListAdapter adapter = new CustomListAdapter(this, itemName, itemContent, imageId);
list = (ListView)findViewById(R.id.list);
list.setAdapter(adapter);

list.setOnItemClickListener(new AdapterView.OnItemClickListener() {
@Override
public void onItemClick(AdapterView<?> adapterView, View view, int position, long id) {
String SelectedItem = itemName[+position];
Toast.makeText(getApplicationContext(), SelectedItem, Toast.LENGTH_SHORT).show();
}
});
}
}


and here is the XML:

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:id="@+id/activity_main"
android:layout_width="match_parent"

<ListView
android:layout_width="match_parent"
android:layout_height="match_parent"
android:id="@android:id/list"
android:layout_centerHorizontal="true" />

</RelativeLayout>


I actually had a different error before for this issue here.

My code showed completely fine apart from the error with the
android:id
, and this fixed this particular issue, but I now have the error with the
R.id.list
.

I also tried the suggestion of just Activity and dropping the keyword
android
in the XML.

Also fixed my old error but not this one.

I have just posted my original code however.

Answer

This findViewById line isn't completely necessary in a ListActivity

list = (ListView)findViewById(R.id.list);

It can instead be gotten with getListView(), or you can do that manually

list = (ListView)findViewById(android.R.id.list);

Basically, your XML is using android.R.id.list, and not R.id.list. There's a difference.

If you see the error that ListView cannot be resolved, then you are missing an import statement.

Comments