Skip to content
Advertisement

How to use getIntExtra value as an array index in next activity

So I have a listview that shows 5 chapters of the book of James from the Bible. As the user chooses the chapter he wants to read, the verses from the chapter will show. What I’m trying to do is to get position value from JamesChapter.java to be passed to the next activity Bible.java and use that value as an index value to the array I want to access in my json file that will display the verses. What happens is the app crashes when I click the chapter. I tried using getIntent() and getIntExtra() but I don’t know how to use the value from those method to apply as an array index. Appreciate the help on how I can use the value from last activity to the array in my next activity. have a great day

enter image description here

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);
            }
        });
    }
}
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);
        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");
            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;
    }
}

This is the format of my json file

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

Here is the error from 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


Advertisement

Answer

Your app is crashing because you have defined tvReference but it is not initialized and then you’re trying to access it in displayJArray() method which results in a NullPointerException at runtime because Android fails to locate the view in Activity. Initialize your textViews in onCreate Method like the example below.

protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_bible);
        
        // Initialize views like this
        tvReference = findViewById(R.id.id_of_your_textView_in_xml);
        tvVersion = same as above ;
        tvVerse = same as above;

        Intent intent = getIntent();
        int position = intent.getIntExtra("position",0);
        displayJArray(position);
    }
User contributions licensed under: CC BY-SA
1 People found this is helpful
Advertisement