我对 Java 真的很生疏,而且我是 Android 新手,我整理了一些代码,这些代码在 MainActivity 类中运行得非常好。但现在我想清理函数并将它们放在自己的类中,以使代码看起来更漂亮。这是我正在尝试做的一个例子。我在 IDE 中没有收到任何错误,但我的设备在 MainActivity 尝试运行 setArtist 和 setAlbum 函数的第二秒崩溃。
public class MainActivity extends Activity {
private ListView lv;
String path, selectedFromList;
ArrayAdapter<String> adapter;
public ViewFiller k = new ViewFiller();
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
lv = (ListView) findViewById(R.id.listView1);
k.setArtist();
k.setAlbums();
adapter = new ArrayAdapter<String>(this,android.R.layout.simple_list_item_1, k.getAlbums());
lv.setAdapter(adapter);
ImageButton albumButton = (ImageButton) findViewById(R.id.albumButton);
ImageButton artistButton = (ImageButton) findViewById(R.id.artistButton);
albumButton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
k.album(lv, adapter);
}
});
artistButton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
k.artist(lv, adapter);
}
});
}
}
这是我遇到问题的班级...
public class ViewFiller extends MainActivity {
public ViewFiller(){
}
ArrayList<String> Albums = new ArrayList<String>();
ArrayList<String> Artist = new ArrayList<String>();
LinkedHashSet<String> hs = new LinkedHashSet<String>();
public ArrayList<String> getAlbums() {
return Albums;
}
public void setAlbums() {
String selection = AudioColumns.IS_MUSIC + " != 0";
String[] projection = { BaseColumns._ID, AudioColumns.ALBUM };
Cursor c = this.getContentResolver().query(
MediaStore.Audio.Media.EXTERNAL_CONTENT_URI, projection,
selection, null, null);
while (c.moveToNext()) {
Albums.add(c.getString(1));
}
hs.clear();
hs.addAll(Albums);
Albums.clear();
Albums.addAll(hs);
}
public ArrayList<String> getArtist() {
return Artist;
}
public void setArtist() {
String selection = AudioColumns.IS_MUSIC + " != 0";
String[] projection = { BaseColumns._ID, AudioColumns.ARTIST, };
Cursor c = this.getContentResolver().query(
MediaStore.Audio.Media.EXTERNAL_CONTENT_URI, projection,
selection, null, null);
while (c.moveToNext()) {
Artist.add(c.getString(1));
}
hs.clear();
hs.addAll(Artist);
Artist.clear();
Artist.addAll(hs);
}
public void artist(ListView lv, ArrayAdapter<String> s) {
lv.setAdapter(null);
s = new ArrayAdapter<String>(this,
android.R.layout.simple_list_item_1, Artist);
lv.setAdapter(s);
}
public void album(ListView lv, ArrayAdapter<String> s) {
lv.setAdapter(null);
s = new ArrayAdapter<String>(this,
android.R.layout.simple_list_item_1, Albums);
lv.setAdapter(s);
}
}