Hello, I'm pretty new with the Volley Library.
I'm making a nested request to two (2) different API using Volley.
the response is of a String type which is converted to JSONObject.
both requests are successful as I store them in local variable within a try and catch block, log them and get the expected response.
However outside the try and catch block the local variable become empty as defined initially.
Is there a way to permanently store the response data in the local variable?
Thanks in advanced.
here is my code:
public class MainActivity extends AppCompatActivity {
String topStoriesIDUrl = "https://hacker-news.firebaseio.com/v0/topstories.json?print=pretty";
static JSONArray myJsonArray = new JSONArray();
ArrayList<String> arrayList = new ArrayList<>();
ListView mListView;
ArrayAdapter<String> adapter;
Toolbar mainToolbar;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mListView = (ListView) findViewById(R.id.mListView);
mainToolbar = (Toolbar) findViewById(R.id.toolbar);
mainToolbar.inflateMenu(R.menu.menu_main);
getDataFromServer();
// adapter = new ArrayAdapter<String>(getApplicationContext(), android.R.layout.simple_list_item_1, arrayList);
// mListView.setAdapter(adapter);
}
public void getDataFromServer() {
StringRequest stringRequest = new StringRequest(Request.Method.GET, topStoriesIDUrl,
new Response.Listener<String>() {
@Override
public void onResponse(String response) {
try {
String topStoriesJson;
String storyID;
JSONArray jsonArray = new JSONArray(response);
for(int i = 0; i < 20; i++) {
storyID = jsonArray.getString(i);
Log.i("ArticleID", storyID);
topStoriesJson = "https://hacker-news.firebaseio.com/v0/item/" + storyID + ".json?print=pretty";
final int indexInt = i;
StringRequest myStrReq = new StringRequest(Request.Method.GET, topStoriesJson,
new Response.Listener<String>() {
@Override
public void onResponse(String response) {
try {
JSONObject myJsonObj = new JSONObject(response);
myJsonArray.put(myJsonObj);
Log.i("Title", myJsonArray.getJSONObject(indexInt).getString("title"));
}
catch (JSONException e) {
e.printStackTrace();
}
}
},
new Response.ErrorListener() {
@Override
public void onErrorResponse(VolleyError error) {
Log.i("myError", error.getMessage());
error.printStackTrace();
}
}
);
MySingleton.getInstance(MainActivity.this).addToRequestQue(myStrReq);
}
}
catch (JSONException e) {
e.printStackTrace();
}
}
},
new Response.ErrorListener() {
@Override
public void onErrorResponse(VolleyError error) {
Log.i("myError", error.getMessage());
error.printStackTrace();
}
}
);
MySingleton.getInstance(MainActivity.this).addToRequestQue(stringRequest);
}
}