I want to create a method to add data into sqlite
database which take HashMap<String,Person>
as argument in a class.
From another class, I want to add person details in HashMap<String,Person>
that can be used by my database handler class.
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
.
Class 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);
so when you will read this entry, you need to use map.get("data")
because here key is data
.
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.