我试图通过使用下面的代码将Gson对象传递给intent,并将其传递给另一个活动以获取详细信息。我尝试在评论中使用此指令中的代码,但仍然是错误的..(How to pass gson serialised object to Intent in android?)
这是我的代码:
public class CustomListAdapter extends ArrayAdapter<Beer> {
Context context;
int layoutResourceId;
public List<Beer> data = null;
public CustomListAdapter(Context context, int resource, List<Beer> objects) {
super(context, resource, objects);
this.context = context;
this.layoutResourceId = resource;
this.context = context;
this.data = objects;
}
static class DataHolder
{
ImageView ivBeer;
TextView tvBeerName;
TextView tvDescription;
TextView abv;
}
@NonNull
@Override
public View getView(int position, View convertView, ViewGroup parent)
{
DataHolder holder = null;
if (convertView == null)
{
LayoutInflater inflater = ((Activity) context).getLayoutInflater();
convertView = inflater.inflate(layoutResourceId, parent,false);
holder = new DataHolder();
holder.ivBeer = (ImageView) convertView.findViewById(R.id.ivBeer);
holder.tvBeerName = (TextView) convertView.findViewById(R.id.tvBeerName);
holder.tvDescription = (TextView) convertView.findViewById(R.id.tvDescription);
holder.abv = (TextView) convertView.findViewById(R.id.abv);
convertView.setTag(holder);
}
else
{
holder = (DataHolder) convertView.getTag();
}
Beer beer=data.get(position);
holder.tvBeerName.setText(beer.name);
Picasso.with(context).load(beer.imageUrl).into(holder.ivBeer);
holder.tvDescription.setText(beer.description);
holder.abv.setText(beer.abv);
// this is the trouble part:
Gson gson = new Gson();
Intent intent = new Intent (CustomListAdapter.this, BeerDetailActivity.class);
intent.putExtra("obj", gson.toJson(data));
return convertView;
}
}
答案 0 :(得分:1)
如果您想将data
对象传递给另一个活动BeerDetailActivity
,则必须“调用”此活动开始:
context.startActivity(intent);
紧随其后:
intent.putExtra("obj", gson.toJson(data));
但是我不确定在getView
adapter
方法中这是否正确