简体   繁体   English

如何在HashMap中添加和获取类的对象值

[英]how to add and get class's object values in HashMap

I want to create a method to add data into sqlite database which take HashMap<String,Person> as argument in a class. 我想创建一种将数据添加到以HashMap<String,Person>作为类中参数的sqlite数据库中的方法。

From another class, I want to add person details in HashMap<String,Person> that can be used by my database handler class. 从另一个类中,我想在HashMap<String,Person>中添加人员详细信息,供我的数据库处理程序类使用。

I have search a lot and tried many examples for this, but couldn't get the solution. 我已经搜索了很多,并为此尝试了许多示例,但无法获得解决方案。 Now i'm bit confused how to do this. 现在我有点困惑如何做到这一点。

I am doing this in following manner now, and getting ClassCastException . 我现在按照以下方式进行此操作,并获取ClassCastException

Class 1 :PersonDataSource.java 第1类:PersonDataSource.java

public long createContact(HashMap<String, Contact> queryValues) {
ContentValues values = new ContentValues();    
Contact val = Contact.class.cast(queryValues);   

values.put(  MySQLiteHelper.COLUMN_FIRST_NAME,  val.getFirstName());
values.put(  MySQLiteHelper.COLUMN_LAST_NAME, val.getLastName());
values.put(  MySQLiteHelper.COLUMN_NICK_NAME, val.getNickName());
values.put(  MySQLiteHelper.COLUMN_BIRTHDATE, val.getBirthDate());  
values.put(  MySQLiteHelper.COLUMN_PRIMARY_CONTACT, val.getPrimaryContact());

long insertId = database.insert(MySQLiteHelper.TABLE_NAME, null, values);
return insertId;
}

And form another class : 并形成另一个类:

datasource = new ContactDataSource(this);
datasource.open();

    Cursor phones = getContentResolver().query(Phone.CONTENT_URI, PROJECTION,null,null, Phone.DISPLAY_NAME);
        while (phones.moveToNext())
        {
          String name=phones.getString(phones.getColumnIndex(Phone.DISPLAY_NAME));
          String phoneNumber = phones.getString(phones.getColumnIndex(Phone.NUMBER));

          Person data = new Person();
          data.setNickName(name);
          data.setPrimaryContact(phoneNumber);

          HashMap<String, Person> map =  new  HashMap<String, Person>();
          map.put("data", data);

          long id = datasource.createContact(map);

          Log.e(CLASS_NAME, "Contact id :" + String.valueOf(id));
        }
        phones.close();
        datasource.close();

How can i solve this ? 我该如何解决?

Use 采用

Contact val = (Contact) queryValues.get("data"); 

Instead of 代替

Contact val = Contact.class.cast(queryValues); 

This is because, you are trying to put a single contact into map as map.put("data", data); 这是因为,您试图将单个联系人作为map.put("data", data);放入地图中map.put("data", data); so when you will read this entry, you need to use map.get("data") because here key is data . 因此,当您阅读此条目时,需要使用map.get("data")因为此处的键是data

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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