我只想将我从游标获得的变量传递给Service。但总是得到一个NullPointerException
。
这是我的适配器,用于将数据显示到listView中。
public class DetailCategoryCursorAdapter extends CursorAdapter{
private Services services;
public DetailCategoryCursorAdapter(Context context, Cursor c) {
super(context, c);
}
@Override
public View newView(Context context, Cursor cursor, ViewGroup parent) {
return LayoutInflater.from(context).inflate(R.layout.list_item_detail, parent, false);
}
@Override
public void bindView(View view, final Context context, Cursor cursor) {
TextView titleTextView = (TextView) view.findViewById(R.id.title);
ImageView imageView = (ImageView) view.findViewById(R.id.dplay);
int titleColumnIndex = cursor.getColumnIndex(Contract.Entry.COLUMN_TITLE);
int urlColumnIndex = cursor.getColumnIndex(Contract.Entry.COLUMN_URL);
String title = cursor.getString(titleColumnIndex);
String url = cursor.getString(urlColumnIndex);
nameTextView.setText(title);
imageView.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
try {
Intent sIntent = new Intent(context, Services.class);
sIntent.putExtra("url", url);
services.startService(sIntent); // in this part always show NullPointerEception
Log.v("url", url);
}catch (Exception e){
e.printStackTrace();
}
}
});
}
}
还是有更好的方法呢?需要咨询。谢谢
最佳答案
在您的onBind
中使用它不会引发异常。 (因为您的services
为空)
Intent sIntent = new Intent(context, Services.class);
sIntent.putExtra("url", url);
context.startService(sIntent);