Member-only story
Seamlessly Pass a JSONArray Between Activities in Android
Passing Single Values with Common Data Types in Android Using Intents is Simple, But What If You Need to Pass an Array? Here’s How You Can Easily Transfer Array Values Between Activities in Android with These Code Examples.
On Your First Activity
To pass the JSONArray
from your current activity to another, you simply need to convert the JSONArray
into a String
representation and send it using an Intent
.
// In your first Activity
Intent intent = new Intent(FirstActivity.this, SecondActivity.class);
intent.putExtra("jsonArray", mJsonArray.toString()); // Convert JSONArray to String and pass it
startActivity(intent);
Here, we are converting the JSONArray
into a String
using toString()
to make it easy to pass via an Intent
.
In the Next Activity
On the receiving end, you’ll retrieve the String
extra and then convert it back into a JSONArray
. Here's how you can do that:
// In the next Activity
Intent intent = getIntent();
String jsonArrayString = intent.getStringExtra("jsonArray"); // Get the passed JSON string
try {
JSONArray array = new JSONArray(jsonArrayString); // Convert back to JSONArray
System.out.println(array.toString(2)); // Print or use the JSONArray as needed
} catch (JSONException e) {
e.printStackTrace(); // Handle any JSON parsing errors
}
Summary
In just a few lines of code, you can easily pass a JSONArray
between activities by converting it to a String
and back. It’s a simple and effective way to share more complex data between Android activities. 🙂