androidjsonasynchronousloopjasynchttpclient

AsyncHttpClient LoopJ and preserving data from onSuccess method


I have this method called "invokeWS". All I want to is to do is to update an ArrayAdapter adapter2 I use in my app with the listdata ArrayList that gets data from a JSON file. I tried different things.

Thanks for reading!


Solution

  • Something you can do is, after onSuccess pass the "listdata" that you create like a parameter of a function (for example "refreshData"):

        @Override
            public void onSuccess(int statusCode, Header[] headers, JSONObject response) {
                System.out.println("Inside Success invokeWS");
                try {
                    JSONArray json = response.getJSONArray("Companies");
                    System.out.println("JSON is parsed!" +json.toString() + "Length is " + json.length());
                    System.out.println("First value is " + json.getString(0));
                    int i;
                    for (i=0;i<json.length();i++){
                        listdata.add(json.getString(i));
                     }
                 System.out.println("Listdata contains" +listdata);
                 refreshData(listdata);
                 } catch (Exception e) {
                    System.out.println("FAILED invokeWS");
                    e.printStackTrace();
                 }
    
            }
    

    And then use that function to update the array with the new list:

    public void refreshData(ArrayList<String> listdata){
        ArrayAdapter<String> adapter2 = new ArrayAdapter<String>(this,
        android.R.layout.simple_spinner_item, listdata);
       sp1.setAdapter(adapter2);
    
    }