There is a code that ensures data retrieval from a WCF service. It works, a JSON string is obtained from the service, which is parsed and displayed on the screen.

I want to fill the class with data from this line, and use it further, outside the AsynkTask block, but I cannot “pull” it out of this block. How to do it?

public class MainActivity extends ActionBarActivity { public static String LOG_TAG = "my_log"; AutoCompleteTextView txtSearch; List<Fruit> mList; FruitAdapter adapter; public List<Fruit> retrievePeople;//массив, который надо возвращать @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); new ParseTask1().execute(); mList = retrievePeople; } public void BTN_click(View view) { new ParseTask1().execute(); } //код для чтения из WCF private class ParseTask1 extends AsyncTask<Void, Void, String> { HttpURLConnection urlConnection = null; BufferedReader reader = null; String resultJson = ""; @Override protected String doInBackground(Void... params) { try { URL url = new URL("http://192.168.1.94:8080/Test.svc/jsonaray"); urlConnection = (HttpURLConnection) url.openConnection(); urlConnection.setRequestMethod("GET"); urlConnection.connect(); InputStream inputStream = urlConnection.getInputStream(); StringBuffer buffer = new StringBuffer(); reader = new BufferedReader(new InputStreamReader(inputStream)); String line; while ((line = reader.readLine()) != null) { buffer.append(line); } resultJson = buffer.toString(); } catch (Exception e) { e.printStackTrace(); } return resultJson; } //получаем json-массив, распарсиваем его и читаем @Override protected void onPostExecute(String resultJson){ super.onPostExecute(resultJson); Log.d(LOG_TAG, resultJson); JSONObject dataJsonObj = null; String Name = ""; try { String resj=resultJson.substring(1,resultJson.length()-1); resj=resj.replace("\\",""); dataJsonObj = new JSONObject(resj); JSONArray arr = dataJsonObj.getJSONArray("Prod"); // 1. достаем инфо о элементе с индексом 1 JSONObject secondFriend = arr.getJSONObject(3); Name = secondFriend.getString("Name"); Log.d(LOG_TAG, "Название: " + Name); // 2. здесь идет заполнение массива, который надо вернуть for (int i = 0; i < arr.length(); i++) { JSONObject obj = arr.getJSONObject(i); String _name = obj.getString("Name"); String _expiry = obj.getString("Expiry"); retrievePeople = new ArrayList<Fruit>(); retrievePeople.add(new Fruit(_name,_expiry)); Log.d(LOG_TAG, "name: " + _name); Log.d(LOG_TAG, "data: " + _expiry); } EditText editText =(EditText)findViewById(R.id.editText); editText.setText(Name); } catch (JSONException e) { e.printStackTrace(); } } } } 
  • And what specific object do you need to “return”? If I understand correctly, you mean retrievePeople , but this is not an array at all . You declared retrievePeople as a class field (more precisely, not a class, but a class object) MainActivity with the public modifier, therefore it is visible everywhere. - post_zeew
  • And also, retrievePeople = new ArrayList<Fruit>(); should be performed at least before the cycle, because at each iteration of the cycle you create a new object, which eventually will contain only (one) last element. - post_zeew
  • @post_zeew, public List <Fruit> retrievePeople; - I declare an array of class Fruit, no? Yes, it has a public access modifier, and it is available everywhere. When I fill it in the AsyncTask block - it is filled, but then, in mList = retrievePeople ;, which occurs after filling this array, the retrievePeople is empty - lcnw
  • one
    Not. The array is Fruit[] retrievePeople; , you have the List<Fruit> retrievePeople , and more specifically the ArrayList is a list. Here it is mList = retrievePeople immediately after the launch of asynstask, and it is quite possible (even likely) that at this moment retrievePeople is only null . You start a new stream, well. And these two threads are executed asynchronously . - post_zeew
  • one
    mList = retrievePeople; You can register at the end of the onPostExecute(...) method, then get what you want (although I don’t understand the meaning of these cunning manipulations at all). - post_zeew

2 answers 2

As it turned out from the comments, the question was why in the onCreate(...) method the data is not loaded into mList in the row mList = retrievePeople; .

But they are not loaded because at the time of the execution of the string mList = retrievePeople; retrievePeople does not yet have this data. The data in retrievePeople loaded in another stream (already after mList = retrievePeople; is executed).

    try this

     public class MainActivity extends ActionBarActivity { public static String LOG_TAG = "my_log"; AutoCompleteTextView txtSearch; List<Fruit> mList; FruitAdapter adapter; public List<Fruit> retrievePeople;//массив, который надо возвращать @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); new ParseTask1().execute(); mList = retrievePeople; } public void BTN_click(View view) { // ....... } public void asyncFinished() { mList = retrievePeople; // !!!!!!!!!! // делаете что хотите со списком. он теперь тут } //код для чтения из WCF private class ParseTask1 extends AsyncTask<Void, Void, String> { HttpURLConnection urlConnection = null; BufferedReader reader = null; String resultJson = ""; @Override protected String doInBackground(Void... params) { // ....... } //получаем json-массив, распарсиваем его и читаем @Override protected void onPostExecute(String resultJson){ super.onPostExecute(resultJson); Log.d(LOG_TAG, resultJson); JSONObject dataJsonObj = null; String Name = ""; try { String resj=resultJson.substring(1,resultJson.length()-1); resj=resj.replace("\\",""); dataJsonObj = new JSONObject(resj); JSONArray arr = dataJsonObj.getJSONArray("Prod"); // 1. достаем инфо о элементе с индексом 1 JSONObject secondFriend = arr.getJSONObject(3); Name = secondFriend.getString("Name"); Log.d(LOG_TAG, "Название: " + Name); // 2. здесь идет заполнение массива, который надо вернуть retrievePeople = new ArrayList<Fruit>(); // !!!!!! for (int i = 0; i < arr.length(); i++) { JSONObject obj = arr.getJSONObject(i); String _name = obj.getString("Name"); String _expiry = obj.getString("Expiry"); retrievePeople.add(new Fruit(_name,_expiry)); Log.d(LOG_TAG, "name: " + _name); Log.d(LOG_TAG, "data: " + _expiry); } EditText editText =(EditText)findViewById(R.id.editText); editText.setText(Name); } catch (JSONException e) { e.printStackTrace(); } asyncFinished(); } } }