You need to enable JavaScript to run this app. Android Studio中点击ListView从Fragment向Activity传数据时应用崩溃求助
优惠活动
大模型
产品
解决方案
定价
更多

Android Studio中点击ListView从Fragment向Activity传数据时应用崩溃求助

崩溃核心原因
  • 图片资源参数错误:InformationActivity 中 setImageResource 的兜底值写了 R.id.pic_name,这是布局控件的ID,不是Drawable资源ID,会触发资源类型不匹配崩溃。
  • 字符串取值逻辑错误:PlacesFragment 传入的 name/info/address/time 是 R.string 开头的整型资源ID,但在 InformationActivity 里直接用 getStringExtra 取值,无法拿到有效文本。
  • 未注册Activity:如果 InformationActivity 没有在 AndroidManifest.xml 中声明,跳转时会抛出 ActivityNotFoundException 直接崩溃。
修正后的核心代码

PlacesFragment 点击事件部分

listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
    @Override
    public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
        Word clickedCard = (Word) parent.getItemAtPosition(position);
        Intent intent = new Intent(getActivity(), InformationActivity.class);
        intent.putExtra("pic_name", clickedCard.getImage());
        intent.putExtra("info_name", clickedCard.getName());
        intent.putExtra("some_information", clickedCard.getInfo());
        intent.putExtra("addressTextView", clickedCard.getAddress());
        intent.putExtra("timeTextView", clickedCard.getTime());
        startActivity(intent);
    }
});

InformationActivity 取值部分

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_information);

    imageView = findViewById(R.id.pic_name);
    nameOfpic =  findViewById(R.id.info_name);
    nameOfInfo = findViewById(R.id.some_information);
    nameOfAdress =  findViewById(R.id.addressTextView);
    nameOfTime =  findViewById(R.id.timeTextView);

    Intent intent = getIntent();
    // 修正图片资源取值,兜底用默认drawable资源
    imageView.setImageResource(intent.getIntExtra("pic_name", R.drawable.medinam1));
    // 拿到字符串资源ID后,通过getString获取实际文本
    nameOfpic.setText(getString(intent.getIntExtra("info_name", R.string.place1)));
    nameOfInfo.setText(getString(intent.getIntExtra("some_information", R.string.about1)));
    nameOfAdress.setText(getString(intent.getIntExtra("addressTextView", R.string.address1)));
    nameOfTime.setText(getString(intent.getIntExtra("timeTextView", R.string.time1)));
}
额外检查项
  • 打开 app/src/main/AndroidManifest.xml,添加 InformationActivity 的注册声明:
<activity android:name=".InformationActivity" />
  • 确认 Word 类的 getImage()/getName() 等方法返回的是 int 类型(对应传入的R.string/R.drawable资源ID)。

内容的提问来源于stack exchange,提问作者x07

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.11.27 01:54:04