【发布时间】:2019-11-11 18:52:20
【问题描述】:
我有一个 RecyclerView.Adapter 派生类型,它应该通过 http 将图像下载到设备。为此,我将ContentDownloadService 传递给它,它扩展了IntentService.
所以在我的MainActivity.kt 我这样做:
class MainActivity : AppCompatActivity(), NavigationView.OnNavigationItemSelectedListener {
private val Issues: ArrayList<Issue> = ArrayList<Issue>()
private val downloadService: ContentDownloadService = ContentDownloadService()
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
loadConfiguration();
val issueCards: RecyclerView = findViewById(R.id.issues_list)
issueCards.layoutManager = LinearLayoutManager(this, LinearLayout.VERTICAL, false)
issueCards.adapter = IssueAdapter(Issues.toTypedArray(), this, downloadService)
}
}
ContentDownloadService 是一个相当通用的 IntentService - 据我所知,它在这里并不真正相关,因为它从未被调用过。
在IssueAdapter 我们这样做:
class IssueAdapter(private var issues: Array<Issue>, private val context: Context, private val downloadService: ContentDownloadService) : RecyclerView.Adapter<IssueAdapter.IssueViewHolder>() {
class IssueViewHolder(public val cardView: CardView) : RecyclerView.ViewHolder(cardView)
override fun onCreateViewHolder(parent: ViewGroup, viewType: Int ) : IssueAdapter.IssueViewHolder {
val issueView = LayoutInflater.from(parent.context).inflate(R.layout.issue_card_view, parent, false)as CardView;
return IssueViewHolder(issueView);
}
override fun onBindViewHolder(holder: IssueViewHolder, position: Int) {
val issueView:CardView = holder.cardView
val title : TextView = issueView.findViewById(R.id.issue_title)
val image: ImageView = issueView.findViewById(R.id.issue_cover_image))
title.text = issues[position].title
description.text = issues[position].description
date.text = format.format(issues[position].date)
if ( issues[position].imagePath != null) {
downloadImage(position)
}
}
private fun downloadImage( position : Int ){
val downloadIntent = Intent()
val resultReceiver = object: ResultReceiver(Handler()){
override fun onReceiveResult(resultCode: Int, bundleResultData : Bundle)
{
if ( resultCode == 0 ) {
issues[position].imagePath = bundleResultData.getString("path")
}
}
};
downloadIntent.putExtra(ContentDownloadService.IMAGE, issues[position].imagePath)
downloadIntent.putExtra(ContentDownloadService.RECEIVER, resultReceiver)
downloadService.startActivity(downloadIntent);
}
}
当我尝试在调试器中运行它时,我收到以下消息:
java.lang.NullPointerException: Attempt to invoke virtual method 'void android.content.Context.startActivity(android.content.Intent)' on a null object reference
at android.content.ContextWrapper.startActivity(ContextWrapper.java:379)
at com.myapp.models.IssueAdapter.downloadImage(IssueAdapter.kt:72)
使用调试器进行单步调试显示downloadService 在调用时绝对是一个真实的对象。
为什么 Android 在调用时将我的服务视为 null,但在调试器中显示为正确?
【问题讨论】:
标签: android kotlin android-intent