簡體   English   中英

Android使用JSON中的數組數據填充listview(由后台線程填充)

[英]Populating a listview with array data from JSON (populated by a background thread) Android

我正在嘗試創建一個窗口,該窗口將顯示一個列表框,該列表框填充有從JSON解析的數組。

列表視圖是在MainActivityOnCreate方法中填充並創建的。 在主要活動中,我還要調用AsyncTask來從網站解析JSON數組。

任務如下所示:

    public class JSONParse extends AsyncTask<String, String, String[]> {
@Override
protected String[] doInBackground(String... params) {
    HttpURLConnection connection = null;
    BufferedReader reader = null;

    try {
        URL url = new URL(params[0]);
        connection = (HttpURLConnection) url.openConnection();
        connection.connect();

        InputStream IStream = connection.getInputStream();

        reader = new BufferedReader(new InputStreamReader(IStream));

        StringBuffer buffer = new StringBuffer();

        String recievedLine = "";

        while ((recievedLine = reader.readLine()) != null) {
            buffer.append(recievedLine);
        }

        String full = buffer.toString();


        JSONObject JSONParent = new JSONObject(full);
        JSONArray j_Puzzles = JSONParent.getJSONArray("PuzzleIndex");
        int arraySize = j_Puzzles.length();
        String[] s_Puzzles = new String[arraySize];

        StringBuffer endString = new StringBuffer();

        for (int i = 0; i < j_Puzzles.length(); i++) {
            s_Puzzles[i] = j_Puzzles.toString(i);
            endString.append(s_Puzzles[i] + "\n");
        }

        MainActivity.Waiting = true;
        return s_Puzzles;
    } catch (MalformedURLException e) {
        e.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
    } catch (JSONException e) {
        e.printStackTrace();
    } finally {
        if (connection != null) {
            connection.disconnect();
        }
        try {
            if (reader != null) {

                reader.close();
            }
        } catch (IOException e) {
            e.printStackTrace();
        }

        return null;
    }
}
}

什么是使s_Puzzles從后台線程進入我的OnCreate的最佳方法,因此可以像這樣使用它:

public class MainActivity extends AppCompatActivity {

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    new JSONParse().execute("http://www.hull.ac.uk/php/349628/08309/acw/index.json");


    ListView listView = (ListView) findViewById(R.id.listView);

    ArrayAdapter<String> arrayAdapter = new ArrayAdapter<String>(this,
            android.R.layout.simple_list_item_1, android.R.id.text1, s_Puzzles);

    listView.setAdapter(arrayAdapter);
}
}

此外,為了防止由於工作線程未完成而導致列表視圖不進行任何更新,我是否必須暫停OnCreate方法直到背景工作器完成。

任何幫助表示贊賞。 謝謝

這樣的事情將起作用,而無需過於復雜化您已經擁有的東西:

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    final ListView listView = (ListView) findViewById(R.id.listView);
    final ArrayAdapter<String> arrayAdapter = new ArrayAdapter<String>(this,
                android.R.layout.simple_list_item_1, android.R.id.text1, new ArrayList<String>());

    listView.setAdapter(arrayAdapter);

    new JSONParse() {
        @Override
        protected void onPostExecute(String[] puzzles)
        {
            super.onPostExecute(puzzles);

            arrayAdapter.addAll(puzzles);
        }
    }.execute("http://www.hull.ac.uk/php/349628/08309/acw/index.json");
}

您試圖調用AsyncTask,然后在不確定是否已加載信息時設置信息。 請記住,它是異步加載的。 我建議您在AsyncTask的onPostExecute()方法上執行此操作。 AsyncTask具有4種您可以自定義的方法:

  1. doInProgress:從線程發送到UI線程(活動)的進度,通常是一個數字。 您可以在此處更新UI。
  2. onPreExecute:在線程開始運行之前進行設置。 您可以在此處更新UI。
  3. doInBackground:您已經擁有了,非常完美。 在這里,您無法更新UI,因為該UI在后台線程上運行。 這是AsyncTask中唯一不在UI線程(活動)上運行的方法。
  4. onPostExecute:您從doInBackground獲得結果。 這是您應該更新UI的地方。

您可以找到有關AsyncTask的任何教程及其簡單內容。 在此項目中,我將AsyncTask用於相同的類型。 https://github.com/isaacurbina/ViewHolderListView/tree/master/app/src/main/java/com/mac/isaac/viewholderlistview

希望能幫助到你!

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM