试着把我自己的音乐播放器包起来,不知道我错在哪里。
得到NullPointerException
的错误。
我甚至尝试过替换
CREATE TABLE musicList(id integer primary key, path VARCHAR, name VARCHAR);");
与
CREATE TABLE IF NOT EXISTS musicList(id integer primary key, path VARCHAR, name VARCHAR);");
LOGCAT错误:http://lookpic.com/O/i2/1427/zQLBzHqB.png
public class MainActivity extends ActionBarActivity implements AdapterView.OnItemClickListener {
SQLiteDatabase musicDatabase = null;
ListView musicList;
String[] items;
ArrayList<File> mySongs;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
musicList = (ListView) findViewById(R.id.musicList);
musicDatabase = this.openOrCreateDatabase("MusicDatabase.db", MODE_PRIVATE, null);
musicDatabase.execSQL("CREATE TABLE musicList(id integer primary key, path VARCHAR, name VARCHAR);");
File database = getApplicationContext().getDatabasePath("MusicDatabase.db");
if (database.exists()) {
Cursor cursor = musicDatabase.rawQuery("SELECT * FROM musicList", null);
int nameID = cursor.getColumnIndex("name");
cursor.moveToFirst();
int i = 0;
if (cursor != null && cursor.getCount() > 0) {
do {
items[i] = cursor.getString(nameID);
i++;
} while (cursor.moveToNext());
}
} else {
String name, path;
mySongs = findSongs(Environment.getExternalStorageDirectory());
for (int i = 0; i < mySongs.size(); i++) {
items[i] = mySongs.get(i).getName().toString();
path = mySongs.get(i).toString();
name = mySongs.get(i).getName().toString();
musicDatabase.execSQL("INSERT INTO musicList(path,name) VALUES('" + path + "','" + name + "');");
}
}
ArrayAdapter<String> arrayAdapter = new ArrayAdapter<String>(getApplicationContext(), android.R.layout.simple_list_item_1, items);
musicList.setAdapter(arrayAdapter);
}
public ArrayList<File> findSongs(File root) {
ArrayList<File> al = new ArrayList<File>();
File[] files = root.listFiles();
for (File singleFile : files) {
if (singleFile.isDirectory() && !singleFile.isHidden()) {
al.addAll(findSongs(singleFile));
} else {
if (singleFile.getName().endsWith(".mp3") || singleFile.getName().endsWith(".aac"))
al.add(singleFile);
}
}
return al;
}
@Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
Intent i = new Intent(getApplicationContext(), playActivity.class);
i.putExtra("SONG_ID", position);
musicDatabase.close();
startActivity(i);
}
}
答案 0 :(得分:0)
将其替换为您当前的openOrCreateDatabase
musicDatabase = SQLiteDatabase.openDatabase("MusicDatabase.db", MODE_PRIVATE, SQLiteDatabase.CREATE_IF_NECESSARY);