2017-02-26 39 views
0

我已經從我的API獲取數據,但我不知道如何將這個獲取的數據分配給我的適配器?如何將數據從後臺線程檢索到aysnctask中的UI線程?

問題:

  1. 如何設置取出的數據到陣列上方界定?

  2. 如何設置適配器?

    公共類FetchLists擴展的AsyncTask <> {

    public List<MailChimpList> listTitles = new ArrayList<>(); 
    
        @Override 
        protected List<MailChimpList> doInBackground(Integer... params) { 
         int count = params[0]; 
         int offset = params[1]; 
    
         String urlString = "https://us14.api.mailchimp.com/lists?apikey=efb918ee8791215bac4c8a3a8a77-us14" 
    
         urlString = urlString + "&count=" + count + "&offset=" + offset; 
    
         try { 
          URL url = new URL(urlString); 
          HttpURLConnection connection = (HttpURLConnection) url.openConnection(); 
          connection.setRequestMethod("GET"); 
          InputStream stream = connection.getInputStream(); 
          BufferedReader reader = new BufferedReader(new InputStreamReader(stream)); 
          String line = reader.readLine(); 
          String response = ""; 
          while (line != null) { 
           response += line; 
           line = reader.readLine(); 
          } 
    
          JSONObject object = new JSONObject(response); 
    
          JSONArray lists = object.getJSONArray("lists"); 
    
          for (int i = 0; i < lists.length(); i++) { 
           JSONObject listData = (JSONObject) lists.get(i); 
           MailChimpList mailChimpList = new MailChimpList(); 
           mailChimpList.id = listData.getString("id"); 
           mailChimpList.title = listData.getString("name"); 
    
           String id = listData.getString("id"); 
           String title = listData.getString("name"); 
    
           Log.d("ashutosh","id are: "+id); 
           Log.d("ashutosh","list name are: "+title); 
    
           listTitles.add(mailChimpList); 
          } 
    
         } catch (Exception e) { 
          e.printStackTrace(); 
         } 
    
         return listTitles; 
        } 
    
    @Override 
    protected void onPostExecute(List<MailChimpList> mailChimpLists) { 
    
    } 
    

    }

+0

裏面你線程可以使用可運行的,因爲你正在使用異步,你可以在你onPostExecute方法 – Arshad

+0

我知道設置適配器!但是如何? –

+0

檢查下面的答案 – Arshad

回答

1
@Override 
protected void onPostExecute(List<MailChimpList> mailChimpLists) { 
    MyCustomAdapter adapter = new MyCustomAdapter(context, mailChimpLists); 
    myListView.setAdapter(adapter); 
} 

當你的列表自定義列表,你需要編寫一個客戶適配器

你可以聲明你的ListView作爲全局變量,它可以在post執行中被訪問。