我真的生鏽了Java,我是Android的新手,我將一些代碼放在一起,這些代碼在MainActivity類中完全正常工作。但現在我想清理這些函數,並將它們放在自己的類中,以使代碼看起來很漂亮。這是我正在嘗試做的一個例子。我在IDE中沒有收到任何錯誤,但是我的設備崩潰,MainActivity嘗試運行setArtist和setAlbum函數。在Android中遇到新的類問題
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);
}
}
請給我們LogCat錯誤。 –
ViewFiller爲什麼要擴展MainActivity?你能提一下這個計劃的目的嗎? – ujvl
製作一個音樂播放器,這是將加載帶有專輯和藝術家名字的ListView的代碼。我真的不知道爲什麼我擴展了MainActivity,它是唯一擺脫ContentResolver未定義錯誤的方法。 – Xearo