MediaStore select query returns only one row - android-recyclerview

I'm trying to develop music player, I've made a loader and adapter for my data retreiving from mediastore, but when I call query from my app it only returns one row, I don't know wat's wrong with my code, would u help me fixing that problem?
That's my loader which should return a list I'll use in another place
public static List<Song> getAllArtistSongs(Context context, long artist_id){
List<Song> ArtistSongList = new ArrayList<>();
Uri uri = MediaStore.Audio.Media.EXTERNAL_CONTENT_URI;
String[] projection = new String[]{
"_id",
"title",
"album_id",
"album",
"artist",
"duration",
"track"
};
String sortorder = MediaStore.Audio.Media.DEFAULT_SORT_ORDER;
String selection = "is_music=1 and artist_id="+artist_id;
Cursor cursor = context.getContentResolver().query(uri, projection, selection, null, sortorder);
assert cursor != null;
if (cursor.moveToFirst()) {
do {
int trackNumber = cursor.getInt(6);
while (trackNumber >= 1000) {
trackNumber -= 1000;
}
Long id = cursor.getLong(cursor.getColumnIndexOrThrow(MediaStore.Audio.Media._ID));
String title = cursor.getString(cursor.getColumnIndexOrThrow(MediaStore.Audio.Media.TITLE));
Long albumid = cursor.getLong(cursor.getColumnIndexOrThrow(MediaStore.Audio.Media.ALBUM_ID));
String albumname = cursor.getString(cursor.getColumnIndexOrThrow(MediaStore.Audio.Media.ALBUM));
String artistname = cursor.getString(cursor.getColumnIndexOrThrow(MediaStore.Audio.Media.ARTIST));
int duration = cursor.getInt(cursor.getColumnIndexOrThrow(MediaStore.Audio.Media.DURATION));
ArtistSongList.add(new Song(id, title, albumid, albumname, artist_id, artistname, duration, trackNumber));
} while (cursor.moveToNext());
cursor.close();
}
return ArtistSongList;
}
And this is the adapter which I use to bind to a recyclerview
public void onBindViewHolder(#NonNull VH holder, int position) {
Song song = artistSongList.get(position);
if(song!=null){
holder.ttv.setText(song.title);
holder.dtv.setText(song.artistName);
int trackN = song.trackNumber;
if(trackN==0){
holder.ntv.setText("_");
}else holder.ntv.setText(String.valueOf(trackN));
}
}
And this is where I call the query func
private void setupAlbumList() {
System.out.println(artistId);
songList = ArtistSongLoader.getAllArtistSongs(getActivity(), artistId);
adapter = new ArtistSongAdapter(getActivity(), songList);
recy.addItemDecoration(new DividerItemDecoration(getActivity(), DividerItemDecoration.VERTICAL));
recy.setAdapter(new ArtistSongAdapter(getActivity(), songList));
}
Thx in advance for helping

My example to retrieve all tracks:
private final String track_id = MediaStore.Audio.Media._ID;
private final String track_no = MediaStore.Audio.Media.TRACK;
private final String track_name = MediaStore.Audio.Media.TITLE;
private final String artist = MediaStore.Audio.Media.ARTIST;
private final String artist_id = MediaStore.Audio.Media.ARTIST_ID;
private final String duration = MediaStore.Audio.Media.DURATION;
private final String album = MediaStore.Audio.Media.ALBUM;
private final String composer = MediaStore.Audio.Media.COMPOSER;
private final String year = MediaStore.Audio.Media.YEAR;
private final String path = MediaStore.Audio.Media.DATA;
private final String date_added = MediaStore.Audio.Media.DATE_ADDED;
public Cursor getAllTracks(Context context) {
// gets all tracks
if (context != null) {
ContentResolver cr = context.getContentResolver();
final String[] columns = {track_id, track_no, artist, track_name,
album, duration, path, year, composer};
return cr.query(uri, columns, null, null, null);
} else {
return null;
}
}
then you have
String selection = "is_music=1"
first, you do not need is_music=1. For multiple tracks you of course need more than 1 track by the same artist
The adapter is irrelevant, the query does the selection
To return albums for an artist
public Cursor getArtistsAlbumcursor(Context context, String artistId) {
ContentResolver cr = context.getContentResolver();
final String _id = MediaStore.Audio.Media._ID;
final String album_id = MediaStore.Audio.Media.ALBUM_ID;
final String artistid = MediaStore.Audio.Media.ARTIST_ID;
final String[] columns = {_id, album_id, artistid};
if (artistId != null) {
String where = artistid + " =?";
String[] aId = {artistId};
return cr.query(uri, columns, where, aId, null);
} else {
return null;
}
}

Related

null userId, Unhandled Exception: Null check operator used on a null value

I have an issue with userId in Habits table. it is a foreign key from id in Users Table. but I keep getting the error "Unhandled Exception: Null check operator used on a null value " from AddHabitDialogController class.
obviously userId should never be null. where is the issue? how can I solve it?
if more code is needed you can check : https://github.com/sarasoltan/habit_tracker
Users Table:
class UsersTable {
static const String tableName = 'Users';
static const String id = 'id';
static const String email = 'email';
static const String createQuery = '''
CREATE TABLE IF NOT EXISTS $tableName (
$id integer primary key autoincrement,
$email text not null unique);''';
#override
String toString() => 'Person, ID: $id, email: $email';
#override
bool operator ==(covariant Users other) => id == other.id;
#override
int get hashCode => id.hashCode;
}
Habits table:
class HabitsTable {
static const String tableName = 'Habits';
static const String id = 'id';
static const String userId = 'userId';
static const String text = 'text';
static const String emoji = 'emoji';
static const String period = 'period';
static const String startPeriod = 'startPeriod';
static const String createQuery = '''
CREATE TABLE IF NOT EXISTS $tableName (
$id integer primary key autoincrement,
$userId integer not null,
$text text not null,
$emoji text not null,
$period text not null,
$startPeriod integer,
FOREIGN Key($userId) REFERENCES ${UsersTable.tableName}(${UsersTable.id}));''';
User model class:
class Users {
late final int id;
late String email;
Users({
required this.id,
required this.email,
});
Users.fromDb(Map<String, dynamic> map) {
id = map[UsersTable.id];
email = map[UsersTable.email];
}
}
Habit model class:
class Habit {
late final int id;
late final int userId;
late String text;
late String emoji;
late final List<int> period;
late final DateTime? startPeriod;
Habit(
{
//required this.id,
required this.userId,
required this.text,
required this.emoji,
required this.period,
this.startPeriod});
Habit.fromDb(Map<String, dynamic> map) {
id = map[HabitsTable.id] as int;
userId = map[HabitsTable.userId] as int;
text = map[HabitsTable.text] as String;
emoji = map[HabitsTable.emoji];
period = (jsonDecode(map[HabitsTable.period]) as List<dynamic>)
.map((e) => e as int)
.toList();
if (map[HabitsTable.startPeriod] != null) {
startPeriod =
DateTime.fromMillisecondsSinceEpoch(map[HabitsTable.startPeriod]);
} else {
startPeriod = null;
}
}
Map<String, dynamic> toDb() {
Users? owner;
return {
//HabitsTable.id: id,
HabitsTable.userId: owner!.id,
HabitsTable.text: text,
HabitsTable.emoji: emoji,
HabitsTable.period: jsonEncode(period),
HabitsTable.startPeriod: startPeriod?.millisecondsSinceEpoch
};
}
AddHabitDialogController(error):
class AddHabitDialogController {
Users? owner;
//final user = FirebaseAuth.instance.currentUser;
//String get owneruserId => AuthService.firebase().currentUser!.id;
final List<bool> period = [true, true, true, true, true, true, true];
int? id;
int? userId;
String? emoji;
String? text;
StartPeriod startPeriod = StartPeriod.none;
final StreamController<bool> _addBtnEnabledCtrl = StreamController();
Stream<bool> get addBtnEnabled => _addBtnEnabledCtrl.stream;
final StreamController<StartPeriod> _selectedStartPeriodCtrl =
StreamController();
Stream<StartPeriod> get selectedStartPeriod =>
_selectedStartPeriodCtrl.stream;
final StreamController<bool> _loadingCtrl = StreamController();
Stream<bool> get loading => _loadingCtrl.stream;
void changePeriodValue(int index, bool newValue) {
period[index] = newValue;
_updateAddBtnEnabledState();
}
void changeTextValue(String newValue) {
text = newValue;
_updateAddBtnEnabledState();
}
void changeEmojiValue(String newEmoji) {
emoji = newEmoji;
_updateAddBtnEnabledState();
}
void changeStartPeriod(StartPeriod newValue) {
startPeriod = newValue;
_selectedStartPeriodCtrl.add(startPeriod);
}
Future<void> addHabit(BuildContext context) async {
_loadingCtrl.add(true);
final dataService = GetIt.I.get<DataService>();
final List<int> forPeriod = [];
for (int i = 0; i < period.length; i++) {
if (period[i]) {
forPeriod.add(i + 1);
}
}
final habit = Habit(
//id: id!,
userId: owner!.id, //error from here
emoji: emoji!,
text: text!,
period: forPeriod,
startPeriod: _calculateStartPeriodDateTime());
await dataService.addHabit(habit);
_loadingCtrl.add(false);
Navigator.of(context).pop();
}
void _updateAddBtnEnabledState() {
_addBtnEnabledCtrl.add((text?.isNotEmpty ?? false) &&
(emoji?.isNotEmpty ?? false) &&
period.where((e) => e).isNotEmpty);
}
DateTime? _calculateStartPeriodDateTime() {
final now = DateTime.now();
switch (startPeriod) {
case StartPeriod.today:
return DateTime(now.year, now.month, now.day);
case StartPeriod.thisMonth:
return DateTime(now.year, now.month);
case StartPeriod.thisYear:
return DateTime(now.year);
case StartPeriod.none:
default:
return null;
}
}
void dispose() {
_addBtnEnabledCtrl.close();
_loadingCtrl.close();
_selectedStartPeriodCtrl.close();
}
}
enum StartPeriod { none, today, thisMonth, thisYear }
Because the local variable of AddHabitDialogController owner can't be referenced before it is declared
class AddHabitDialogController {
Users? owner; // -> you did not assign this owner?

How to call an api and select correct optional from update method in spring mvc

I have been following online tutorials for MVC but have hit a snag with updating.
Have used a updateStudent() method in the controller and pass in the id, but inside the updateStudent() I have alot of optionals.
Trying to figure out how to call the api and select the optional from within the method I want it to use
Any help is appreciated
Thanks.
Controller....
public class StudentController {
public final StudentService studentService;
#Autowired
public StudentController(StudentService studentService) {
this.studentService=studentService;
}
#PutMapping(path="/updateme/{id}")
public void updateStudent(#PathVariable ("id") UUID id,#RequestBody Student student) {
studentService.updateStudent(id, student);
}
StudentService...
#Service
public class StudentService {
private final StudentDao studentDao;
//constructor
public StudentService(#Qualifier("postgres3")StudentDao studentDao) {
this.studentDao=studentDao;
}
#PutMapping
public void updateStudent(UUID id, Student student) {
Optional.ofNullable(student.getChapterProgress())
.filter(cp -> !StringUtils.isEmpty(cp))
.ifPresent(cp -> studentDao.updateChapterProgress(id, cp));
Optional.ofNullable(student.getAvgTestScore())
.filter(avg -> !StringUtils.isEmpty(avg))
.ifPresent(avg -> studentDao.updateAvgTestScore(id, avg));
Optional.ofNullable(student.getChap1Score())
.filter(c1 -> !StringUtils.isEmpty(c1))
.ifPresent(c1 -> studentDao.updateChap1Score(id, c1));
Optional.ofNullable(student.getChap2Score())
.filter(c2 -> !StringUtils.isEmpty(c2))
.ifPresent(c2 -> studentDao.updateChap2Score(id, c2));
Optional.ofNullable(student.getChap3Score())
.filter(c3 -> !StringUtils.isEmpty(c3))
.ifPresent(c3 -> studentDao.updateChap3Score(id, c3));
Optional.ofNullable(student.getChap4Score())
.filter(c4 -> !StringUtils.isEmpty(c4))
.ifPresent(c4 -> studentDao.updateChap4Score(id, c4));
Optional.ofNullable(student.getChap5Score())
.filter(c5 -> !StringUtils.isEmpty(c5))
.ifPresent(c5 -> studentDao.updateChap5Score(id, c5));
Optional.ofNullable(student.getChap6Score())
.filter(c6 -> !StringUtils.isEmpty(c6))
.ifPresent(c6 -> studentDao.updateChap6Score(id, c6));
}
StudentDataAccessService...
#Repository("postgres3")
public class StudentDataAccessService implements StudentDao {
private JdbcTemplate jdbcTemplate;
#Autowired
public StudentDataAccessService(JdbcTemplate jdbcTemplate) {
this.jdbcTemplate= jdbcTemplate;
}
#Override
public int updateChapterProgress(UUID id, Integer chapterprogress) {
String sql = "UPDATE student SET chapterprogress = ? WHERE id = ?";
return jdbcTemplate.update(sql, chapterprogress, id);
}
#Override
public int updateAvgTestScore(UUID id, Double avg) {
String sql = "UPDATE student SET avgtestscore = ? WHERE id = ?";
return jdbcTemplate.update(sql, avg, id);
}
#Override
public int updateChap1Score(UUID id, Double chap1Score) {
String sql = "UPDATE student SET chap1score = ? WHERE id = ?";
return jdbcTemplate.update(sql, chap1Score, id);
}
#Override
public int updateChap2Score(UUID id, Double chap2Score) {
String sql = "UPDATE student SET chap2score = ? WHERE id = ?";
return jdbcTemplate.update(sql, chap2Score, id);
}
#Override
public int updateChap3Score(UUID id, Double chap3Score) {
String sql = "UPDATE student SET chap3score = ? WHERE id = ?";
return jdbcTemplate.update(sql, chap3Score, id);
}
#Override
public int updateChap4Score(UUID id, Double chap4Score) {
String sql = "UPDATE student SET chap4score = ? WHERE id = ?";
return jdbcTemplate.update(sql, chap4Score, id);
}
#Override
public int updateChap5Score(UUID id, Double chap5Score) {
String sql = "UPDATE student SET chap5score = ? WHERE id = ?";
return jdbcTemplate.update(sql, chap5Score, id);
}
#Override
public int updateChap6Score(UUID id, Double chap6Score) {
String sql = "UPDATE student SET chap6score = ? WHERE id = ?";
return jdbcTemplate.update(sql, chap6Score, id);
}
#Override
public int updateStudentById(UUID id, Student student) {
return 0;
}
StudentDao...
public interface StudentDao {
int updateStudentById(UUID id,Student student);
int updateChapterProgress(UUID id, Integer chapterprogress);
int updateAvgTestScore(UUID id, Double avg);
int updateChap1Score(UUID id, Double chap1Score);
int updateChap2Score(UUID id, Double chap2Score);
int updateChap3Score(UUID id, Double chap3Score);
int updateChap4Score(UUID id, Double chap4Score);
int updateChap5Score(UUID id, Double chap5Score);
int updateChap6Score(UUID id, Double chap6Score);
Ended up assigning each update to its own method call in the controller, thanks

It was okay until I tried to upgrade it to add one more column to it

I was learning to use sqlflite in my flutter application..when i upgraded it for the first time it worked absolutely fine..but then I wanted to add one more column but i actually don't know query for that.. so I tried the query shown below, but when I try to save my data, I get this error:
E/SQLiteLog(22556): (1) table tbl_employee has no column named employee_gender
I/flutter (22556): DatabaseException(table tbl_employee has no column named employee_gender (code 1 SQLITE_ERROR): , while compiling: INSERT OR REPLACE INTO tbl_employee (employee_name, employee_Student, employee_depertment, employee_DOB, employee_gender) VALUES (?, ?, ?, ?, ?)) sql 'INSERT OR REPLACE INTO tbl_employee (employee_name, employee_Student, employee_depertment, employee_DOB, employee_gender) VALUES (?, ?, ?, ?, ?)' args [Adrita, teacher, CMT, 19/00/2020, 2]}
This is my database class:
class DBHelper{
static final String CREATE_TABLE_EMPLOYEE = '''
create table $TABLE_EMPLOYEE(
$COL_EMP_ID integer primary key autoincrement,
$COL_EMP_NAME text not null,
$COL_EMP_PROFESSION text not null,
$COL_EMP_DEPARTMENT text not null
)
''';
static Future<Database> open() async{// to initialize data we used this method
final dbpath = await getDatabasesPath();//directory
final path = Path.join(dbpath,'employee.db');//main Path
return openDatabase(path,version: 3,onCreate: (db, version) async{
await db.execute(CREATE_TABLE_EMPLOYEE);
}, onUpgrade: (db, oldVersion, newVersion) async{
if(newVersion == 2){
db.execute(''' alter table $TABLE_EMPLOYEE add column $COL_EMP_DOB text ''');
}
if(newVersion == 3){
db.execute('''alter table $TABLE_EMPLOYEE add column $COL_RADIO_BUTTON integer ''');
}
},);
}
static Future<int> insertEmployee(String table, Map<String, dynamic> map) async {// insert method
final db = await open();
return await db.insert(table, map, conflictAlgorithm: ConflictAlgorithm.replace);
}
static Future<int> updateEmployee(EmployeeTeacherModel employeemodel) async{
final db = await open();
return await db.update(TABLE_EMPLOYEE, employeemodel.toMap(), where: '$COL_EMP_ID = ?', whereArgs: [employeemodel.id]);
}
static Future<int> DeleteEmployee(int id) async{
final db = await open();
return await db.delete(TABLE_EMPLOYEE,where: '$COL_EMP_ID = ?', whereArgs: [id]);
}
static Future<List<EmployeeTeacherModel>> getAllEmployees() async{
final db = await open();
final List<Map<String, dynamic>> map = await db.query(TABLE_EMPLOYEE, orderBy: COL_EMP_NAME);
return List.generate(map.length, (index){
return EmployeeTeacherModel.fromMap(map[index]);
});
}
static Future<EmployeeTeacherModel> getEmployeeByid(int id) async{
final db = await open();
final List<Map<String, dynamic>> emps = await db.query(TABLE_EMPLOYEE, where: '$COL_EMP_ID=?',whereArgs: [id]);
if(emps.length>0){
return EmployeeTeacherModel.fromMap(emps.first);
}
return null;
}
}
Here's the Model class:
final String TABLE_EMPLOYEE = "tbl_employee";
final String COL_EMP_ID = "employee_id";
final String COL_EMP_NAME = "employee_name";
final String COL_EMP_DEPARTMENT = "employee_depertment";
final String COL_EMP_PROFESSION = "employee_Student";
final String COL_EMP_DOB = "employee_DOB";
final String COL_RADIO_BUTTON = "employee_gender";
class EmployeeTeacherModel {
int id;
String name;
String depertment;
String Dob;
String profession;
int gender;
EmployeeTeacherModel({this.id, this.name, this.depertment, this.profession, this.Dob, this.gender});
Map<String,dynamic> toMap(){//method to insert data into database
var map = <String, dynamic>{//method
COL_EMP_NAME : name,
COL_EMP_PROFESSION: profession,
COL_EMP_DEPARTMENT: depertment,
COL_EMP_DOB: Dob,
COL_RADIO_BUTTON: gender,
};
if(id !=null){
map[COL_EMP_ID] = id;
}
return map;
}
EmployeeTeacherModel.fromMap(Map<String,dynamic> map){//named constructor to return emoloyee model obj
id = map[COL_EMP_ID];
name = map[COL_EMP_NAME];
profession = map[COL_EMP_PROFESSION];
depertment = map[COL_EMP_DEPARTMENT];
Dob = map[COL_EMP_DOB];
gender = map[COL_RADIO_BUTTON];
}
#override
String toString() {
return 'EmployeeTeacherModel{id: $id, name: $name, depertment: $depertment, Dob: $Dob, profession: $profession, gender: $gender}';
}
}

Arraylist not displaying the right output

My main class code
{
ArrayList<Item> items = new ArrayList<Item>();
Scanner file = new Scanner(kk.class.getResourceAsStream("product.txt"));
while (file.hasNextLine()) {
String[] sp = file.nextLine().split(",");
// extract item number, description, price and type
itemNum = Integer.parseInt(sp[0]);
des = sp[1];
price = Integer.parseInt(sp[2]);
Item objt = new Item(itemNum, des, price); // Creating a new object
items.add(objt); // Adding it to the list
}
System.out.println(items);
}
output I am getting
[dada.Item#4a5d4a62, dada.Item#32be8e12, dada.Item#7c6159c4, dada.Item#5b4c92a7, dada.Item#3040c5,
My item class code
private int itemNum = 0;
private String des = "";
private int price = 0;
public Item(int i, String d, int p) {
itemNum = i;
des = d;
price = p;
}
You're printing the Item reference's address instead of the fields inside your Item object. You have print the fields inside each Item object by looping through them.
Replace this line
System.out.println(items);
with
for(Item i : items)
{
System.out.println(i.getItemNum()+" "+i.getDes()+" "+i.getPrice());
}
Change the class so that you could access your private fields
private int itemNum = 0;
private String des = "";
private int price = 0;
public Item(int i, String d, int p) {
itemNum = i;
des = d;
price = p;
}
public void setItemNum(int itemNum) {
this.itemNum = itemNum;
}
public int getItemNum() {
return itemNum;
}
public void setDes(String des) {
this.des = des;
}
public String getDes() {
return des;
}
public void setPrice(int price) {
this.price = price;
}
public int getPrice() {
return price;
}

To display an album art from media store in android

I'm not able to display album art from media store while listing albums,I'm getting
error
Bad request for field slot 0,-1. numRows = 32, numColumns = 7
01-02 02:48:16.789: D/AndroidRuntime(4963): Shutting down VM
01-02 02:48:16.789: W/dalvikvm(4963): threadid=1: thread exiting with uncaught exception (group=0x4001e578)
01-02 02:48:16.804: E/AndroidRuntime(4963): FATAL EXCEPTION: main
01-02 02:48:16.804: E/AndroidRuntime(4963): java.lang.IllegalStateException: get field slot from row 0 col -1 failed
Can anyone kindly help with this issue,Thanks in advance
public class AlbumbsListActivity extends Activity {
private ListAdapter albumListAdapter;
private HashMap<Integer, Integer> albumInfo;
private HashMap<Integer, Integer> albumListInfo;
private HashMap<Integer, String> albumListTitleInfo;
private String audioMediaId;
private static final String TAG = "AlbumsListActivity";
Boolean showAlbumList = false;
Boolean AlbumListTitle = false;
ImageView album_art ;
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.albums_list_layout);
Cursor cursor;
ContentResolver cr = getApplicationContext().getContentResolver();
if (getIntent().hasExtra(Util.ALBUM_ID)) {
int albumId = getIntent().getIntExtra(Util.ALBUM_ID,
Util.MINUS_ONE);
String[] projection = new String[] { Albums._ID, Albums.ALBUM, Albums.ARTIST, Albums.ALBUM_ART, Albums.NUMBER_OF_SONGS };
String selection = null;
String[] selectionArgs = null;
String sortOrder = Media.ALBUM + " ASC";
cursor = cr.query(Albums.EXTERNAL_CONTENT_URI, projection, selection, selectionArgs, sortOrder);
/* final String[] ccols = new String[] {
//MediaStore.Audio.Albums.,
MediaStore.Audio.Albums._ID,
MediaStore.Audio.Albums.ALBUM,
MediaStore.Audio.Albums.ARTIST,
MediaStore.Audio.Albums.ALBUM_ART,
MediaStore.Audio.Albums.NUMBER_OF_SONGS
};
cursor = cr.query(MediaStore.Audio.Albums.getContentUri(
"external"), ccols, null, null,
MediaStore.Audio.Albums.DEFAULT_SORT_ORDER);*/
showAlbumList = true;
}
else
{
String order = MediaStore.Audio.Albums.ALBUM + " ASC";
String where = MediaStore.Audio.Albums.ALBUM;
cursor = managedQuery(Media.EXTERNAL_CONTENT_URI,
DbUtil.projection, null, null, order);
showAlbumList = false;
}
albumInfo = new HashMap<Integer, Integer>();
albumListInfo = new HashMap<Integer, Integer>();
ListView listView = (ListView) findViewById(R.id.mylist_album);
listView.setFastScrollEnabled(true);
listView.setOnItemLongClickListener(new ItemLongClickListener());
listView.setAdapter(new AlbumCursorAdapter(this, cursor,
DbUtil.displayFields, DbUtil.displayViews,showAlbumList));
final Uri uri = MediaStore.Audio.Albums.EXTERNAL_CONTENT_URI;
final Cursor albumListCursor = cr.query(uri, DbUtil.Albumprojection,
null, null, null);
}
private class AlbumCursorAdapter extends SimpleCursorAdapter implements SectionIndexer{
private final Context context;
private final Cursor cursorValues;
private Time musicTime;
private Boolean isAlbumList;
private MusicAlphabetIndexer mIndexer;
private int mTitleIdx;
public AlbumCursorAdapter(Context context, Cursor cursor, String[] from,
int[] to,Boolean isAlbumList) {
super(context, 0, cursor, from, to);
this.context = context;
this.cursorValues = cursor;
//musicTime = new Time();
this.isAlbumList = isAlbumList;
}
String albumName="";
String artistName = "";
String numberofsongs = "";
long albumid;
#Override
public View getView(int position, View convertView, ViewGroup parent)
{
View rowView = convertView;
if (rowView == null) {
LayoutInflater inflater = (LayoutInflater) context
.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
rowView = inflater
.inflate(R.layout.row_album_layout, parent, false);
}
this.cursorValues.moveToPosition(position);
String title = "";
String artistName = "";
String albumName = "";
int count;
long albumid = 0;
String songDuration = "";
if (isAlbumList) {
albumInfo.put(
position,
Integer.parseInt(this.cursorValues.getString(this.cursorValues
.getColumnIndex(MediaStore.Audio.Albums._ID))));
artistName = this.cursorValues
.getString(this.cursorValues
.getColumnIndex(MediaStore.Audio.Albums.ARTIST));
albumName = this.cursorValues
.getString(this.cursorValues
.getColumnIndex(MediaStore.Audio.Albums.ALBUM));
albumid=Integer.parseInt(this.cursorValues.getString(this.cursorValues
.getColumnIndex(MediaStore.Audio.Albums.ALBUM_ID)));
} else {
albumInfo.put(position, Integer.parseInt(this.cursorValues
.getString(this.cursorValues
.getColumnIndex(MediaStore.Audio.Media._ID))));
artistName = this.cursorValues.getString(this.cursorValues
.getColumnIndex(MediaStore.Audio.Media.ARTIST));
albumName = this.cursorValues.getString(this.cursorValues
.getColumnIndex(MediaStore.Audio.Media.ALBUM));
albumid=Integer.parseInt(this.cursorValues.getString(this.cursorValues
.getColumnIndex(MediaStore.Audio.Media.ALBUM_ID)));
}
//code for Alphabetical Indexer
mTitleIdx = cursorValues.getColumnIndex(MediaStore.Audio.Media.ALBUM);
mIndexer = new MusicAlphabetIndexer(cursorValues, mTitleIdx,
getResources().getString(R.string.fast_scroll_alphabet));
//end
TextView metaone = (TextView) rowView.findViewById(R.id.album_name);
TextView metatwo = (TextView) rowView.findViewById(R.id.artist_name);
ImageView metafour = (ImageView) rowView.findViewById(R.id.album_art);
TextView metathree = (TextView) rowView
.findViewById(R.id.songs_count);
metaone.setText(albumName);
metatwo.setText(artistName);
(metafour)getAlbumArt(albumid);
System.out.println("albumid----------"+albumid);
metaThree.setText(DbUtil.makeTimeString(context, secs));
getAlbumArt(albumid);
}
TextView metaone = (TextView) rowView.findViewById(R.id.album_name);
TextView metatwo = (TextView) rowView.findViewById(R.id.artist_name);
album_art = (ImageView) rowView.findViewById(R.id.album_art);
//TextView metathree = (TextView) rowView.findViewById(R.id.songs_count);
metaone.setText(albumName);
metatwo.setText(artistName);
return rowView;
}
}
String albumArtUri = "";
private void getAlbumArt(long albumid) {
Uri uri=ContentUris.withAppendedId(MediaStore.Audio.Albums.EXTERNAL_CONTENT_URI, albumid);
System.out.println("hhhhhhhhhhh" + uri);
Cursor cursor = getContentResolver().query(
ContentUris.withAppendedId(
MediaStore.Audio.Albums.EXTERNAL_CONTENT_URI, albumid),
new String[] { MediaStore.Audio.AlbumColumns.ALBUM_ART },
null,
null,
null);
if (cursor.moveToFirst()) {
albumArtUri = cursor.getString(0);
}
System.out.println("kkkkkkkkkkkkkkkkkkk :" + albumArtUri);
cursor.close();
if(albumArtUri != null){
Options opts = new Options();
opts.inJustDecodeBounds = true;
Bitmap albumCoverBitmap = BitmapFactory.decodeFile(albumArtUri, opts);
opts.inJustDecodeBounds = false;
albumCoverBitmap = BitmapFactory.decodeFile(albumArtUri, opts);
if(albumCoverBitmap != null)
album_art.setImageBitmap(albumCoverBitmap);
}else {
// TODO:
Options opts = new Options();
Bitmap albumCoverBitmap = BitmapFactory.decodeResource(getApplicationContext().getResources(),
R.drawable.albumart_mp_unknown_list, opts);
if(albumCoverBitmap != null)
album_art.setImageBitmap(albumCoverBitmap);
}
}
}
}