You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Android中如何将getIntExtra值用作数组索引并解决崩溃问题

Android应用崩溃问题修复

问题场景

开发Android应用,用ListView展示圣经《雅各书》的5个章节,用户选择章节后通过Intent传递position值到Bible页面,以此作为JSON数组索引获取对应经文,但点击章节时应用崩溃。

相关代码

JamesChapters.java

public class JamesChapters extends AppCompatActivity {

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

        ListView listView = findViewById(R.id.listview);

        List<String> list = new ArrayList<>();
        list.add("Chapter 1");
        list.add("Chapter 2");
        list.add("Chapter 3");
        list.add("Chapter 4");
        list.add("Chapter 5");


        ArrayAdapter arrayAdapter = new ArrayAdapter(getApplicationContext(), android.R.layout.simple_list_item_1,list);
        listView.setAdapter(arrayAdapter);

        listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                    Intent intent = new Intent(JamesChapters.this, Bible.class);
                    intent.putExtra("position", position);
                    startActivity(intent);
            }
        });
    }
}

Bible.java(修复后)

public class Bible extends AppCompatActivity {
    TextView tvReference, tvVersion, tvVerse;
    String reference, version, verse;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_bible);
        
        // 初始化TextView,替换为你布局文件中对应的ID
        tvReference = findViewById(R.id.tv_reference);
        tvVersion = findViewById(R.id.tv_version);
        tvVerse = findViewById(R.id.tv_verse);
        
        Intent intent = getIntent();
        int position = intent.getIntExtra("position",0);
        displayJArray(position);
    }

    public void displayJArray(int value){
        String rid = rid();
        try{
            JSONObject json = new JSONObject(rid);
            JSONArray jsonarray = json.getJSONArray("James");
            // 新增索引合法性判断,避免越界异常
            if(value >= 0 && value < jsonarray.length()){
                JSONObject newjson = jsonarray.getJSONObject(value);
                reference = newjson.getString("Reference");
                version = newjson.getString("Version");
                verse = newjson.getString("Verse");
                tvReference.setText(reference);
                tvVersion.setText(version);
                tvVerse.setText(verse);
            }
        } catch (JSONException e) {
            e.printStackTrace();
        }
    }

    public String rid(){
        String content="";
        try{
            InputStream ist = getAssets().open("james.json");
            int size = ist.available();
            byte [] buffer = new byte[size];
            ist.read(buffer);
            content = new String(buffer);
        }catch (IOException e) {
            e.printStackTrace();
        }
        return content;
    }
}

JSON文件格式(修复后)

{
  "James": [
    {
      "Reference": "James 1:1-27",
      "Version": "NIV",
      "Verse": "......"
    },
    {
      "Reference": "James 2:1-26",
      "Version": "NIV",
      "Verse": "....."
    }
  ]
}

Logcat错误信息

2022-11-02 15:51:32.805 25637-25676/ph.edu.nu.soco.finalproject E/eglCodecCommon: GoldfishAddressSpaceHostMemoryAllocator: ioctl_ping failed for device_type=5, ret=-1
2022-11-02 15:51:42.272 25637-25637/ph.edu.nu.soco.finalproject E/AndroidRuntime: FATAL EXCEPTION: main
    Process: ph.edu.nu.soco.finalproject, PID: 25637
    java.lang.RuntimeException: Unable to start activity ComponentInfo{ph.edu.nu.soco.finalproject/ph.edu.nu.soco.finalproject.Bible}: java.lang.NullPointerException: Attempt to invoke virtual method 'void android.widget.TextView.setText(java.lang.CharSequence)' on a null object reference
        at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2913)
        at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:3048)
        at android.app.servertransaction.LaunchActivityItem.execute(LaunchActivityItem.java:78)
        at android.app.servertransaction.TransactionExecutor.executeCallbacks(TransactionExecutor.java:108)
        at android.app.servertransaction.TransactionExecutor.execute(TransactionExecutor.java:68)
        at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1808)
        at android.os.Handler.dispatchMessage(Handler.java:106)
        at android.os.Looper.loop(Looper.java:193)
        at android.app.ActivityThread.main(ActivityThread.java:6669)
        at java.lang.reflect.Method.invoke(Native Method)
        at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:493)
        at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:858)
     Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'void android.widget.TextView.setText(java.lang.CharSequence)' on a null object reference
        at ph.edu.nu.soco.finalproject.Bible.displayJArray(Bible.java:37)
        at ph.edu.nu.soco.finalproject.Bible.onCreate(Bible.java:25)
        at android.app.Activity.performCreate(Activity.java:7136)
        at android.app.Activity.performCreate(Activity.java:7127)
        at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1271)
        at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2893)
        at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:3048) 
        at android.app.servertransaction.LaunchActivityItem.execute(LaunchActivityItem.java:78) 
        at android.app.servertransaction.TransactionExecutor.executeCallbacks(TransactionExecutor.java:108) 
        at android.app.servertransaction.TransactionExecutor.execute(TransactionExecutor.java:68) 
        at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1808) 
        at android.os.Handler.dispatchMessage(Handler.java:106) 
        at android.os.Looper.loop(Looper.java:193) 
        at android.app.ActivityThread.main(ActivityThread.java:6669) 
        at java.lang.reflect.Method.invoke(Native Method) 
        at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:493) 
        at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:858) 
2022-11-02 15:51:43.018 25695-25721/ph.edu.nu.soco.finalproject E/eglCodecCommon: GoldfishAddressSpaceHostMemoryAllocator: ioctl_ping failed for device_type=5, ret=-1

问题原因与修复方案

  1. 空指针异常核心原因:Bible.java中仅声明了TextView变量,但未调用findViewById绑定布局中的控件,导致调用setText时触发NullPointerException。

    • 修复:在setContentView(R.layout.activity_bible);之后添加TextView初始化代码,注意替换为布局文件中对应的ID。
  2. JSON语法错误:原JSON中第二个对象的"Version": "NIV"字段后缺少逗号,会导致JSON解析失败。

    • 修复:在该字段后添加逗号,确保JSON格式合法。
  3. 可选优化:添加索引合法性判断,避免当position超出JSON数组长度时触发越界异常。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.14 05:06:02