我试图将活动A中的额外内容发送给B. 发送部分很好,变量不是空值,但我无法弄清楚如何在活动B中获取它们。 这是发送代码:
public void sendToFavorites(Context context){
String vID,vThumbnail,vTitle;
vID = sendResult.getId().getVideoId();
vThumbnail = sendResult.getSnippet().getThumbnails().getMedium().getUrl();
vTitle = sendResult.getSnippet().getTitle();
Intent fav = new Intent(context,Favorites.class);
fav.putExtra("title",vTitle);
fav.putExtra("thumbnail",vThumbnail);
fav.putExtra("id",vID);
}
这是获取代码:
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.favorites_layout);
getSupportActionBar().setTitle("Favorites");
initializeViews();
//////////////////
Bundle extras = getIntent().getExtras();
vidID = extras.getString("id");
vidTitle = extras.getString("title");
vidThumbnail = extras.getString("thumbnail");
loadFavorites();
}
我在这里开始活动B:
@Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()){
case R.id.favorites:
intent = new Intent(this, Favorites.class);
startActivity(intent);
}
return super.onOptionsItemSelected(item);
}
出于某种原因,当我使用NO log启动Activity B时,应用程序崩溃了..
我在做什么?
答案 0 :(得分:0)
public void sendToFavorites(Context context){
String vID,vThumbnail,vTitle;
vID = sendResult.getId().getVideoId();
vThumbnail = sendResult.getSnippet().getThumbnails().getMedium().getUrl();
vTitle = sendResult.getSnippet().getTitle();
Intent fav = new Intent(context,Favorites.class);
fav.putExtra("title",vTitle);
fav.putExtra("thumbnail",vThumbnail);
fav.putExtra("id",vID);
}
您的Intent
对象fav
仅适用于此方法。由于您从未在此方法中调用startActivity(fav)
,因此您开始Activity B
时不会包含您的捆绑数据。有两种可能的替代方法 - 将fav
声明为类变量并稍后引用它,如下所示:
public class MyClass extends ... {
Intent fav;
//...
public void sendToFavorites(Context context){
String vID,vThumbnail,vTitle;
vID = sendResult.getId().getVideoId();
vThumbnail = sendResult.getSnippet().getThumbnails().getMedium().getUrl();
vTitle = sendResult.getSnippet().getTitle();
fav = new Intent(context,Favorites.class);
fav.putExtra("title",vTitle);
fav.putExtra("thumbnail",vThumbnail);
fav.putExtra("id",vID);
}
//...later, during a button click....
if (fav != null) {
startActivity(fav);
}
或者,正如我所希望的那样,将sendToFavourites()
方法中的逻辑放在点击事件中:
@Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()){
case R.id.favorites:
String vID,vThumbnail,vTitle;
vID = sendResult.getId().getVideoId();
vThumbnail = sendResult.getSnippet().getThumbnails().getMedium().getUrl();
vTitle = sendResult.getSnippet().getTitle();
Intent fav = new Intent(context, Favorites.class); //Could use "this" instead of context if this class extends Activity
fav.putExtra("title",vTitle);
fav.putExtra("thumbnail",vThumbnail);
fav.putExtra("id",vID);
startActivity(fav);
}
return super.onOptionsItemSelected(item);
}