我是Android新手。我从另一个类访问ArrayList,但我在访问类时得到零大小的ArrayList。在主类中,它显示了数组列表大小的正值。我不知道为什么我在访问课程时获得零大小。检查我的代码是否有错误。
Tab3Tracks类
public class Tab3Tracks extends ListFragment {
public void onCreate(Bundle savedInstanceState){
super.onCreate(savedInstanceState);
}
private ArrayList<String> trackslist = new ArrayList<>();
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View v = inflater.inflate(R.layout.tab3tracks, container, false);
final String trackid = MediaStore.Audio.Media._ID;
final String trackno = MediaStore.Audio.Media.TRACK;
final String trackname = MediaStore.Audio.Media.TITLE;
final String path = MediaStore.Audio.Media.DATA;
Uri uri = MediaStore.Audio.Media.EXTERNAL_CONTENT_URI;
ContentResolver cr = getContext().getContentResolver();
final String[] projection = {trackid,trackno,trackname,path
};
final Cursor cursor = cr.query(uri,projection,null,null,null);
if (cursor!=null){
if(cursor.moveToFirst()){
do{
int trackIndex = cursor.getColumnIndexOrThrow(MediaStore.Audio.Media.TITLE);
trackslist.add(cursor.getString(trackIndex));
}while(cursor.moveToNext());
}System.out.println(trackslist.size());
} cursor.close();
ArrayAdapter<String> adapter = new ArrayAdapter<String>(
getActivity(),R.layout.playlist_item,R.id.songTitle,trackslist
);
setListAdapter(adapter);
return v;
}
public ArrayList<String> getList(){
return trackslist;
}
@Override
public void onListItemClick(ListView l, View v, int position, long id) {
super.onListItemClick(l, v, position, id);
int songIndex = position;
// Starting new intent
Intent in = new Intent(getActivity(), NowPlaying.class);
// Sending songIndex to PlayerActivity
in.putExtra("songIndex", songIndex);
startActivityForResult(in, 100);
}
}
NowPlaying Class
public class NowPlaying extends AppCompatActivity {
public ArrayList<String> songsList = new ArrayList<String>();
public Tab3Tracks tab3tracks;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.player);
// Getting all songs list
tab3tracks = new Tab3Tracks();
songsList= tab3tracks.getList();
System.out.println("songsListSize"+songsList.size());
System.out.println("List" +songsList);
}
答案 0 :(得分:1)
您的ArrayList已初始化,但未添加任何内容。
trackslist.add(cursor.getString(trackIndex));
它嵌套在onCreateView中,导致它只被调用一次。您可能需要考虑将onTOuchListener添加到活动中,并将您的代码添加到侦听器内部,以便在触摸屏幕时更新它。
在线程内添加也可能有效,但这实际上取决于您的代码。
答案 1 :(得分:0)
trackslist.add(cursor.getString(trackIndex));
不会随时致电