[英]How do I retrieve the song list in this fragment?
There are two errors neither of which I can figure out why. 有两个错误,我都无法弄清楚为什么。
getContentResolver()
" 无法解析方法“ getContentResolver()
” 2.Cannot infer arguments (on the new ArrayAdapter<>()
). 2.无法推断参数(在new ArrayAdapter<>()
)。
I hope this is the right way to get the songs list from a fragment
? 我希望这是从fragment
获取歌曲列表的正确方法吗? If there is some better alternative, please explain that. 如果有更好的选择,请解释一下。 Thank you 谢谢
public class SongsFragment extends Fragment {
public SongsFragment() {
// Required empty public constructor
}
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
}
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View view=inflater.inflate(R.layout.fragment_songs, container, false);
ListView audioView = (ListView)view.findViewById(R.id.songView);
ArrayList<String> audioList = new ArrayList<>();
String[] proj = {MediaStore.Audio.Media._ID, MediaStore.Audio.Media.DISPLAY_NAME};
final Cursor audioCursor = getContentResolver().query(MediaStore.Audio.Media.EXTERNAL_CONTENT_URI, proj, null, null, null);
if (audioCursor != null) {
if (audioCursor.moveToFirst()) {
do {
int audioIndex = audioCursor.getColumnIndexOrThrow(MediaStore.Audio.Media.DISPLAY_NAME);
audioList.add(audioCursor.getString(audioIndex));
} while (audioCursor.moveToNext());
}
}
audioCursor.close();
ArrayAdapter<String> adapter = new ArrayAdapter<>(this, android.R.layout.simple_list_item_1, android.R.id.text1, audioList);
audioView.setAdapter(adapter);
return view;
}
}
In class which is extending Fragment
Context is not available to get it need to use getActivity()
method. 在正在扩展的类中,无法使用Fragment
Context来获取它,需要使用getActivity()
方法。
1. Cannot resolve method "getContentResolver()" 1. 无法解析方法“ getContentResolver()”
Because getContentResolver
method is not available in Fragment
class, need to user Context to access it: 由于Fragment
类中没有getContentResolver
方法,因此需要用户Context来访问它:
final Cursor audioCursor = getActivity().getContentResolver().query(
MediaStore.Audio.Media.EXTERNAL_CONTENT_URI,
proj, null, null, null);
2. Cannot infer arguments (on the new ArrayAdapter<>()). 2. 无法推断参数(在新的ArrayAdapter <>()上)。
Because ArrayAdapter
constructor require valid Context
as first parameter : 因为ArrayAdapter
构造函数需要有效的Context
作为第一个参数:
ArrayAdapter<String> adapter = new ArrayAdapter<>(getActivity(),
android.R.layout.simple_list_item_1,
android.R.id.text1, audioList);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.