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.
Related
Before i used an ArrayList for this, but because of duplicate Album issues (which i resolved before API29 by using DISTINCT and GROUP BY statements) which are not allowed anymore to use inside a query.
I got values like this in my RecyclerViews Adapter: myArrayList.get(position).getAlbum();
But now that i'm using a HashMap, how can i get a value by position which i get from the adapter?
Code for adding values in Hashmap
HashMap<Integer, Album> albums = new HashMap<>();
String[] projection2 = { MediaStore.Audio.Media.ALBUM_ID,
MediaStore.Audio.Media.ALBUM,
MediaStore.Audio.Media.IS_MUSIC};
String selection = MediaStore.Audio.Media.IS_MUSIC + "!=0";
String sort = MediaStore.Audio.Media.ALBUM + " COLLATE NOCASE ASC";
cursor = resolver.query(musicUri, projection2, selection, null, sort);
try {
if (cursor != null) {
cursor.moveToFirst();
while (!cursor.isAfterLast()) {
int columnAlbumId = cursor.getColumnIndexOrThrow(MediaStore.Audio.Media.ALBUM_ID);
int columnAlbumName = cursor.getColumnIndexOrThrow(MediaStore.Audio.Media.ALBUM);
String albumId = cursor.getString(columnAlbumId);
String albumName = cursor.getString(columnAlbumName);
if(albums.containsKey(albumId) == false){
Album album = new Album(albumId, albumName);
albums.put(albumId, album);
}
cursor.moveToNext();
}
}
}catch (Exception e){
Log.e(TAG, "Exception caught when creating ALBUM!", e);
throw new Exception();
}
By definition the HashMap is not sorted so how about a SortedMap? An implementation of a SortedMap is a TreeMap which sorts the entries according to keys (or a Comparator).
I believe that suits you since your map has integers as keys.
Edit:
You can use a List or whatever collection suits you in your adapter. For example keep a reference to the ids and the albums which is the data that you're interested in displaying through the adapter.
private int[] ids;
private Album[] albums;
As you're passing the data (included in a map) to your adapter then you could extract that data and place it in the array containers so you can take advantage of the index. For example,
public MyAdapter(Map<Integer,Album> data){
ids = new int[map.size()];
albums = new Album[map.size()];
int i = 0;
for (Map.Entry<Integer,Album> e : map.entrySet()){
ids[i] = e.getKey();
albums[i++] = e.getValue();
}
}
Now that you have your arrays you can sort them also if you like and in case you want to grab the 3rd album and its id all you need to do is,
int id = ids[2];
Album album = albums[2];
I created one table has studId, studName, place.I also want to create another table related to the first one that has studId, day, timeone, timeTwo. How can I do it? I'm a beginner in firebase
this method will add the data for firebase
private void addDate(){
String studName = userName.getText().toString().trim();
String place = spinnerPlace.getSelectedItem().toString();
if(!TextUtils.isEmpty(studName)){
String id = databaseStudentData.push().getKey();
StudentData studentData = new StudentData(id, studName, place);
databaseStudentData.child(id).setValue(studentData);
addDay(id);
Toast.makeText(this, "Data is saved", Toast.LENGTH_LONG).show();
}else {
Toast.makeText(this, "you Should Enter your name", Toast.LENGTH_LONG).show();
}
}
and here the data that i stored
enter image description here
There is no benefit in creating another table just for one attribute, what you can do is the following. Since you already did this:
String id = databaseStudentData.push().getKey();
StudentData studentData = new StudentData(id, studName, place);
databaseStudentData.child(id).setValue(studentData);
Now to add time under this table you can do the following:
Map<String, Object> childUpdates = new HashMap<>();
childUpdates.put("time", time);
databaseStudentData.child(id).updateChildren(childUpdates);
This way you will have the following database:
id
studId : "id"
studName : "name"
studPlace : "place"
studTime : "time"
I'm trying to display the album names and album artwork from the songs on my device.
I tried using a comparator to sort the album names, but when i sort the album names the artwork doesn't match the album name.
How can i link the albumid with the matching artwork?
I use picasso to display the album art and.
I get the album art from MediaStore.Audio.Media.ALBUM_ID;
Then i tried using a hashmap to link albumid with album name.
But im getting this error;
E/Couldn't execute task: java.lang.NullPointerException: Attempt to invoke interface method 'boolean android.database.Cursor.moveToFirst()' on a null object reference
// Creating the map "Album IDs" -> "Album Names"
albumIdToAlbumNameMap = new HashMap<>();
//This is what we'll ask of the albums
String[] albumColumns = {
SONG_ALBUMID,
SONG_ALBUM,
};
// Querying the album database
cursor = resolver.query(musicUri, albumColumns, null, null, null);
// Iterating through the results and filling the map.
for (cursor.moveToFirst(); !cursor.isAfterLast(); cursor.moveToNext())
albumIdToAlbumNameMap.put(cursor.getString(0), cursor.getString(1));
cursor.close();
// Map Song IDs to Album IDs
songIdToAlbumIdMap = new HashMap<>();
// For each album, we'll query the databases
for (String albumID : albumIdToAlbumNameMap.keySet()) {
Uri uri = MediaStore.Audio.Albums.getContentUri(albumID);
cursor = resolver.query(uri, new String[] { SONG_ID }, null, null, null);
// Iterating through the results, populating the map
for (cursor.moveToFirst(); !cursor.isAfterLast(); cursor.moveToNext()) {
long currentSongID = cursor.getLong(cursor.getColumnIndex(SONG_ID));
songIdToAlbumIdMap.put(Long.toString(currentSongID), albumID);
}
cursor.close();
}
final String musicsOnly = MediaStore.Audio.Media.IS_MUSIC + "=1";
// Actually querying the system
cursor = resolver.query(musicUri, columns, musicsOnly, null, null);
if (cursor != null && cursor.moveToFirst())
{
// NOTE: I tried to use MediaMetadataRetriever, but it was too slow.
// Even with 10 songs, it took like 13 seconds,
do {
// Creating a song from the values on the row
QuerySongs song = new QuerySongs(cursor.getInt(cursor.getColumnIndex(SONG_ID)),
cursor.getString(cursor.getColumnIndex(SONG_FILEPATH)));
song.setTitle (cursor.getString(cursor.getColumnIndex(SONG_TITLE)));
song.setArtist (cursor.getString(cursor.getColumnIndex(SONG_ARTIST)));
song.setAlbumID (cursor.getInt(cursor.getColumnIndexOrThrow(SONG_ALBUMID)));
// Using the previously created genre maps
// to fill the current song genre.
String currentGenreID = songIdToGenreIdMap.get(Long.toString(song.getId()));
String currentGenreName = genreIdToGenreNameMap.get(currentGenreID);
String currentAlbumID = songIdToAlbumIdMap.get(Long.toString(song.getId()));
String currentAlbumName = albumIdToAlbumNameMap.get(currentAlbumID);
song.setGenre(currentGenreName);
song.setAlbum(currentAlbumName);
// Adding the song to the global list
songs.add(song);
}
while (cursor.moveToNext());
}
else
{
// What do I do if I can't find any songs?
}
cursor.close();
Here does the error occur
// Iterating through the results, populating the map
for (cursor.moveToFirst(); !cursor.isAfterLast(); cursor.moveToNext()) {
long currentSongID = cursor.getLong(cursor.getColumnIndex(SONG_ID));
songIdToAlbumIdMap.put(Long.toString(currentSongID), albumID);
}
Seems like you need to fix your query input to avoid null in cursor.
I have some data in SQLite database, which I would like to show in a List based on small logic.
I have three fields in my table,
first field : id
second field : title
third field : type
where Type can be : Monthly or Yearly
Here is my code:
// Generate real data for each item
public List<ReminderItem> generateData(int count) {
ArrayList<ReminderItem> items = new ArrayList<>();
// Get all reminders from the database
List<Reminder> reminders = rb.getAllReminders();
// Initialize lists
List<String> Titles = new ArrayList<>();
List<String> Type = new ArrayList<>();
List<Integer> IDList= new ArrayList<>();
// Add details of all reminders in their respective lists
for (Reminder r : reminders) {
Titles.add(r.getTitle());
Type.add(r.getType());
IDList.add(r.getID());
}
return items;
}
This is the situation, where I need help from you guys, As you can see still, I am showing each and every record from database to list, no matter from which Type it belongs.
Now, I just want to show records in a List, which belongs to Type "Monthly" only
So exactly what I have to do ? How can I show records in a List for the Type of "Monthly" only
I have a String variable namely, strType = "Monthly";
You have two option to do this.
First is directly get only those record from database which reminder type is "Monthly" by execute below sql statement.
SELECT id,title,type FROM table_name WHERE type = "Monthly"
Second is check reminder type is equal to "Monthly" when you add data into List.
for (Reminder r : reminders) {
String reminderType = r.getType();
if(reminderType.equalsIgnoreCase(strType)) {
Titles.add(r.getTitle());
Type.add(reminderType);
IDList.add(r.getID());
}
}
Full Code
// Generate real data for each item
public List<ReminderItem> generateData(int count) {
String strType = "Monthly";
ArrayList<ReminderItem> items = new ArrayList<>();
// Get all reminders from the database
List<Reminder> reminders = rb.getAllReminders();
// Initialize lists
List<String> Titles = new ArrayList<>();
List<String> Type = new ArrayList<>();
List<Integer> IDList= new ArrayList<>();
// Add details of all reminders which type="Monthly" in their respective lists
for (Reminder r : reminders) {
String reminderType = r.getType();
if(reminderType.equalsIgnoreCase(strType)) {
Titles.add(r.getTitle());
Type.add(reminderType);
IDList.add(r.getID());
}
}
return items;
}
When you select from your sqlite db you can add filter there
Cursor cursor = db.rawQuery("SELECT * FROM " + TABLE_A + " WHERE " +
COLUMN_TYPE + "=?", new String[]{ arg0 }); // arg0 = "Monthly"
This will increase your performance instead of filtering List after load
I created a small activity that displays all contacts with phone numbers in my phone. However, there are duplicates for contacts that have whatsapp installed. For example, if John is in my contact list and he has a whatsapp account as well, the list would look like this:
...
Jake
John
John
JP
...
This is my code for assigning the cursor to the the adapter which links to a listview.
Uri uri = ContactsContract.CommonDataKinds.Phone.CONTENT_URI;
String sortOrder = ContactsContract.CommonDataKinds.Phone.DISPLAY_NAME + " ASC";
final Cursor cursor = getContentResolver().query(uri, null, null, null, sortOrder);
String[] from = {ContactsContract.CommonDataKinds.Phone.DISPLAY_NAME, ContactsContract.CommonDataKinds.Phone.NUMBER, ContactsContract.CommonDataKinds.Phone._ID};
int[] to = {android.R.id.text1};
adapter = new SimpleCursorAdapter(this, android.R.layout.simple_list_item_multiple_choice, cursor, from, to, 0);
EDIT
With this code, I confirmed that the duplicates have 0 value for the ContactsContract.CommonDataKinds.Phone.TYPE which means it is a custom contact (Whatsapp). The rest are 2 which means it is a normal contact.
I need to figure out a query where it doesn't use any contacts where ContactsContract.CommonDataKinds.Phone.TYPE == 0
I know it might be a bit late. However I was having the same issue.
ContactsContract.CommonDataKinds.Phone.TYPE as per the android documentation refers not to whether it is a custom contact but to what type of contact it is i.e. Mobile(2), Home(1) or Work(3). Whatsapp contacts will be a 2 - mobile.
I used the following function to remove the duplicates (not sure if there is a better way):
private boolean checkDuplicate(String position) {
LinkedHashMap<String, Integer> map;
Integer testNull;
map=new LinkedHashMap<>();
testNull=map.get(position);
if(testNull==null) {
testNull=1;
map.put(position, testNull);
return false;
}
else {
testNull=testNull+1;
if(testNull==2) {
return true;
}
else {
map.put(position, testNull);
return false;
}
}
}