我无法从其他类访问getsongList()
方法。
我想从“Songs”类访问MainActivity
类中的方法。我尝试通过以下代码,但我收到一个错误。请检查我的代码是否正确。
帮我修复代码。
歌曲类
public class Songs extends Fragment {
private ArrayList<SongModel> songList;
public void getsongList(){
//retrieve song info
ContentResolver musicResolver = getActivity().getContentResolver();
Uri musicUri = android.provider.MediaStore.Audio.Media.EXTERNAL_CONTENT_URI;
Cursor musicCursor = musicResolver.query(musicUri, null, null, null, null);
if(musicCursor!=null && musicCursor.moveToFirst()){
//get columns
int titleColumn = musicCursor.getColumnIndex
(android.provider.MediaStore.Audio.Media.TITLE);
int idColumn = musicCursor.getColumnIndex
(android.provider.MediaStore.Audio.Media._ID);
int artistColumn = musicCursor.getColumnIndex
(android.provider.MediaStore.Audio.Media.ARTIST);
//add songs to list
do {
long thisId = musicCursor.getLong(idColumn);
String thisTitle = musicCursor.getString(titleColumn);
String thisArtist = musicCursor.getString(artistColumn);
songList.add(new SongModel(thisId, thisTitle, thisArtist));
}
while (musicCursor.moveToNext());
}
}
}
MainActivity Class
public class MainActivity extends Activity {
@Override
protected void onCreate(Bundle savedInstanceState) {
Songs obj1 = new Songs();
song = obj1.getsongList();
}
}
答案 0 :(得分:0)
只需尝试一次将您的方法返回类型void更改为您的arraylit
private songList;
public ArrayList<SongModel> getsongList(){
return song;}
MainActivity Class
public class MainActivity extends Activity {
@Override
protected void onCreate(Bundle savedInstanceState) {
Songs obj1 = new Songs();
ArrayList<SongModel> song = obj1.getsongList();
}
}
答案 1 :(得分:0)
方法getsongList()返回void。访问类似
song = obj1.getsongList();您应该将方法签名从void修改为ArrayList并返回该方法中的歌曲列表
public void getsongList()
to
public ArrayList<SongModel> getsongList() {
return songList;
}
答案 2 :(得分:0)
您应该创建一个返回列表的方法,记住始终programming to interface:
private List<SongModel> songList;
public List<SongModel> getsongList() {
return songList;
}
但是以下一行有一个缺陷:
public class MainActivity extends Activity {
@Override
protected void onCreate(Bundle savedInstanceState) {
Songs obj1 = new Songs();
// You can't call it here!!!!
song = obj1.getsongList();
}
}
因为歌曲是片段(您还应该将其名称更改为SongsFragment),所以需要时间来初始化和创建自己。因此,您需要添加Callback
,以便在片段完成创建时告诉MainActivity
。