简体   繁体   中英

Getting java.lang.ClassCastException: android.widget.SimpleAdapter cannot be cast

I am creating listView using SimpleAdapter but while clicking on items I am getting class cast exception.In onItemClick method I am trying to get reference of my Customer class at that point only getting class cast exception which I can see in Android monitor log.

MainActivity.java

public class MainActivity extends AppCompatActivity  {

private ListView listView;
ArrayList<HashMap<String, String>> data;
SimpleAdapter adapter;
Customer customer;


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

    data=new ArrayList<>();
    data.add(new Customer("Cusomer Name1", "customer1 Name").toHasMap());
    data.add(new Customer("Cusomer Name2", "customer2 Name").toHasMap());

    String[] hasMapProperties={"FirstName",              "LastName"};
    int[] texfields={R.id.list_item_customer2_firstname,R.id.list_item_customer2_secndname};

    adapter=new SimpleAdapter(this,data,R.layout.list_item_customer_2,hasMapProperties,texfields);
    listView=(ListView)findViewById(R.id.main_activity_listView);
    listView.setAdapter(adapter);
    listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
        @Override
        public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
            TextView textView= (TextView) view.findViewById(R.id.list_item_customer2_firstname);

            Customer customer= (Customer) adapter.getItem(position);
            Toast.makeText(MainActivity.this,"Clicked " + customer.getFirstname() + " Postion " + position,Toast.LENGTH_SHORT).show();

        }
    });
}

Customer

public class Customer {
private final String firstname;
private final String lastname;

public Customer(String firstname, String lastname) {
    this.firstname = firstname;
    this.lastname = lastname;
}


public String getFirstname() {
    return firstname;
}

public String getLastname() {
    return lastname;
}

@Override
public String toString() {
    return getFirstname() + "" + getLastname();
}

public HashMap<String,String> toHasMap() {

    HashMap<String, String> returnValue=new HashMap<>();
    returnValue.put("FirstName",getFirstname());
    returnValue.put("LastName",getLastname());
    return  returnValue;

}
}

I am beginner in android development

That is because your adapter.getItem returns a HashMap. Change you code like this:

Map<String,String> customer= (HashMap<String, String>) adapter.getItem(position); // CHANGE CUSTOMER TYPE TO MAP

Toast.makeText(MainActivity.this,"Clicked " + customer.get("FirstName") + " Postion " + position,Toast.LENGTH_SHORT).show(); 

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