我无法使用 Intent ,原因如下。另外,我尝试调用该方法,但它抛出 NullPointerException
。
我想做的是将字符串songName
从ListActivity
发送到具有方法getSongIndex()
的类,它将传入的字符串 (songName
) 与 ArrayList
中的歌曲进行比较,然后将索引(整数)返回给调用 Activity 。
我无法使用 Intent 的原因:
如果我从 ListActivity 的 onClickListener 发送 Intent 到 java 类,接收端的 getIntent.getExtras() 会导致错误。另外,我需要 java 类中的另一个 Intent 将 songIndex
发送回 ListActivity
。
这是所需的代码:
This is the function in java class: SongsManager.java This is how I get songName in the method and compare it to songtitles in the phone:
public int songIndex;
ArrayList<String> songs = new ArrayList<String>();
public int getSongIndex(String s, Context c) {
String songName = s;
String songTitle;
String song;
final Cursor mCursor = c.getContentResolver().query(
MediaStore.Audio.Media.EXTERNAL_CONTENT_URI,
new String[]{MediaStore.Audio.Media.TITLE}, null, null,
"LOWER(" + MediaStore.Audio.Media.TITLE + ") ASC");
/* run through all the columns we got back and save the data we need into the arraylist for our listview*/
if (mCursor.moveToFirst()) {
do {
song = MediaStore.Audio.Media.TITLE;//mCursor.getString(mCursor.getColumnIndexOrThrow(MediaStore.Audio.Media.TITLE));
songs.add(song);
} while (mCursor.moveToNext());
}
String tempSong;
for(int i=0; i <songs.size();i++) {
tempSong = songs.get(i);
if(songName.equalsIgnoreCase(tempSong))
{
songIndex = i;
}
}
mCursor.close(); //cursor has been consumed so close it
return songIndex;
}
这就是我在 ListActivity 中实例化 SongsManager 对象的方法:
public SongsManager manager = new SongsManager();
这是ListActivity的onClickListener中调用函数getSongIndex的代码。
lv.setOnItemClickListener(new AdapterView.OnItemClickListener() {
@Override
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
TextView textView = (TextView) view.findViewById(android.R.id.text1);
String songName = textView.getText().toString();
songIndex = manager.getSongIndex(songName);
// Starting new intent
Intent i = new Intent(getApplicationContext(),MusicPlayerActivity.class);
Log.d("TAG", "onItemClick");
//// Sending songIndex to PlayerActivity
i.putExtra("songIndex", songIndex);
startActivity(i);
}
});
我正在寻找解决或破解此问题的方法。有没有办法使用 Intent 来解决这个问题(请注意,我的 ListActivity 已经从 onCreate() 中的另一个 Activity 收到了 Intent )。我读到了关于 BroadcastReciever 的内容,但它看起来真的很麻烦。任何其他简单的方法将受到高度赞赏。 谢谢
最佳答案
问题是:
final Cursor mCursor = getApplicationContext().getContentResolver().query(...
线。
因为SongsManager
是普通的java类,那么如何访问其中的getApplicationContext()
方法呢?
表示 Activity 或任何其他组件在 SongsManager
类中扩展,但未在 AndroidManifest.xml
中注册
因此,要解决此问题,请删除您在 SongsManager
中扩展的类,并在 getSongIndex
方法中传递 Context 来访问 getContentResolver()
。像:
public int getSongIndex(String s,Context mContext) {
String songName = s;
String songTitle;
final Cursor mCursor = mContext.getContentResolver().query(...);
...
return songIndex;
}
并调用getSongIndex
方法:
songIndex = manager.getSongIndex(songName,getApplicationContext());
关于java - 如何从java类(不是 Activity ,没有布局)调用方法到 Activity ?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38303703/