我正在尝试从活动A向活动B发送一些数据。 Ytadapter的代码:
@Override
public View getView(final int position, View convertView, final ViewGroup parent) {
final ViewHolder mHolder;
if(convertView != null){
mHolder = (ViewHolder)convertView.getTag();
}else{
mHolder = new ViewHolder();
convertView = mLayoutInflater.inflate(R.layout.view_video_item,null);
mHolder.mVideoThumbnail = (ImageView)convertView.findViewById(R.id.video_thumbnail);
mHolder.mVideoTitle = (TextView)convertView.findViewById(R.id.video_title);
mHolder.mVideoFavorite = (ImageView)convertView.findViewById(R.id.video_favorite);
convertView.setTag(mHolder);
}
//Setting the data
final SearchResult result = mVideoList.get(position);
mHolder.mVideoTitle.setText(result.getSnippet().getTitle());
//Loading the image
Picasso.with(mActivity).load(result.getSnippet().getThumbnails().getMedium().getUrl()).into(mHolder.mVideoThumbnail);
//OnClickListeners
mHolder.mVideoFavorite.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
AppUtils.showToast(result.getSnippet().getTitle() + " Was added to favorites.");
m.sendResult = result;
m.sendToFavorites();
}
});
在YtAdapter中初始化:
private Activity mActivity = null;
private List<SearchResult> mVideoList = null;
private LayoutInflater mLayoutInflater = null;
MainActivity m = new MainActivity();
这是A:
的代码public void sendToFavorites(){
Intent fav = new Intent(MainActivity.this,Favorites.class);
fav.putExtra("title",sendResult.getSnippet().getTitle());
fav.putExtra("thumbnail",sendResult.getSnippet().getThumbnails().getMedium().getUrl());
fav.putExtra("id", sendResult.getId().getVideoId());
}
这是我得到的问题:
java.lang.NullPointerException: Attempt to invoke virtual method 'java.lang.String android.content.Context.getPackageName()' on a null object reference
根据IDE,问题在于行中的MainActivity Intent fav = new ...
答案 0 :(得分:0)
你永远不应该创建一个extends Activity
的类,使用Android框架为你提供的实例。
new Intent(MainActivity.this
&gt; MainActivity.this
在代码中的这个位置是null
(它提供的上下文)。
查看new Intent(Context
的源代码,您会看到它的作用context.getPackageName
https://github.com/android/platform_frameworks_base/blob/master/core/java/android/content/Intent.java#L4160 导致: https://github.com/android/platform_frameworks_base/blob/master/core/java/android/content/ComponentName.java#L64
要解决此问题,您需要使用正确的上下文(活动)
将您的方法调用更改为
m.sendToFavorites(mActivity);
和你的方法
public void sendToFavorites(Context context){
Intent fav = new Intent(context,Favorites.class);
。