2012-06-11 56 views
1

我試圖運行一個背景asynctask來加載我的數據。
我有2種方法加載數據,我在AsyncTask中運行它們。
加載完成後,我有一個名爲Filldata的方法,它用數據填充UI。Android在Asynctask中使用多種方法

現在的問題是,它只是填充用戶界面,無論哪種方法首先完成數據下載。
有沒有辦法在一個AsyncTask內運行多種方法,還是我需要多個AsyncTasks

這裏是我的AsyncTask

public class PostTask extends AsyncTask<Void, String, Boolean> { 

    @Override 
    protected Boolean doInBackground(Void... params) { 
     boolean result = false; 
     loadNewsFeed(); 
     loadResultsFeed(); 
     publishProgress("progress"); 
     return result; 
    } 


    protected void onProgressUpdate(String... progress) { 
     StringBuilder str = new StringBuilder(); 
      for (int i = 1; i < progress.length; i++) { 
       str.append(progress[i] + " "); 

      } 
    } 

     @Override 
    protected void onPostExecute(Boolean result) { 
     super.onPostExecute(result); 
     Log.v("BGThread", "begin fillin data"); 
     FillData(); 
    } 
} 

我的繼承人完整的代碼

public void checkPreferences(){ 

     SharedPreferences preferences = getSharedPreferences("prefs", Context.MODE_PRIVATE); 
     ChosenMethod = preferences.getString("ChosenMethod", ChosenMethod); 
     ChosenLeagueID = preferences.getString("ChosenLeagueId", ChosenLeagueID); 
     ChosenTeamId = preferences.getString("ChosenTeamId", ChosenTeamId); 

     Log.v("lc", "newsurl" + newsFeedURL); 


     Log.v("myapp", "ChosenMethod Home = " + ChosenMethod); 
     Log.v("myapp", "ChosenLeagueID Home = " + ChosenLeagueID); 
     Log.v("myapp", "ChosenTeamID Home = " + ChosenTeamId); 

     if (ChosenMethod.equals("Team")) { 
      setContentView(R.layout.homeactteam2); 
      newsAmount = 5; 

     } else { 
      newsAmount = 10; 
      setContentView(R.layout.homeactteam); 
     } 

} 


@Override 
protected void onCreate(Bundle savedInstanceState) { 
    // TODO Auto-generated method stub 
    super.onCreate(savedInstanceState); 

    //Check Preferences which sets UI 

    checkPreferences(); 
    PostTask posttask; 
    posttask = new PostTask(); 
    posttask.execute(); 




    Button backbtn = (Button) findViewById(R.id.backbtn); 

    //Listening to button event 
    backbtn.setOnClickListener(new View.OnClickListener() { 

     public void onClick(View arg0) { 
      //Starting a new Intent 
      Intent previousScreen = new Intent(getApplicationContext(), ChooseTeamActivity.class); 
      ChosenMethod = "null"; 
      SharedPreferences preferences = getSharedPreferences("prefs", Context.MODE_PRIVATE); 
      SharedPreferences.Editor editor = preferences.edit(); 
      editor.putString("ChosenMethod", ChosenMethod);    
      editor.commit(); 
      previousScreen.putExtra("FullData", fulldata); 
      startActivity(previousScreen); 


     } 
    }); 

//((PullToRefreshListView) getListView()).setOnRefreshListener(new OnRefreshListener() { 
// 
// public void onRefresh() { 
//  // Do work to refresh the list here. 
//  loadData(); 
// } 
//}); 
// 


} 



public void loadNewsFeed(){ 

    newsFeedRequest = "" + chosenLeagueId + "" + unixTimeStamp; 
    newsFeedURL = "" + newsFeedRequest;  

     String myhash = buildHmacSignature(apiKey, newsFeedURL); 
     HttpClient client = new DefaultHttpClient(); 
     HttpPost post = new HttpPost(newsFeedURL); 

     List<NameValuePair> pairs = new ArrayList<NameValuePair>(); 
     pairs.add(new BasicNameValuePair("requestToken", myhash)); 
     pairs.add(new BasicNameValuePair("apiUser", apiUser)); 

      try { 
       post.setEntity (new UrlEncodedFormEntity(pairs)); 
       HttpResponse response = client.execute(post); 
       BufferedReader reader = new BufferedReader(new InputStreamReader(response.getEntity().getContent(), "UTF-8")); 
       String json = reader.readLine(); 
       fulldata = String.valueOf(json); 
       Log.v("myApp","newsdata" + fulldata); 

       newsList = new ArrayList<String>(); 
       newsList2 = new ArrayList<String>(); 
       newsList3 = new ArrayList<String>(); 
       imageList = new ArrayList<String>(); 


       JSONObject obj = new JSONObject(json);  
       JSONObject objData = obj.getJSONObject("data"); 
       JSONArray jArray = objData.getJSONArray("news"); 
       Log.v("lc","newsAmount= " + newsAmount); 

        for(int t = 0; t < newsAmount; t++){ 
         JSONObject newsTitleDict = jArray.getJSONObject(t); 
         imageList.add(newsTitleDict.getString("image_small")); 
        newsList3.add(newsTitleDict.getString("title")); 

        } 

        for(int t = 0; t < 1; t++){ 
         JSONObject newsTitleDict = jArray.getJSONObject(t); 

       newsList.add(newsTitleDict.getString("title")); 
      //  newsList2.add(newsTitleDict.getString("title")); 

        } 

        Log.v("BGThread", "Loaded news"); 
        loadResultsFeed(); 

    } catch (ClientProtocolException e) { 
     // TODO Auto-generated catch block 
     e.printStackTrace(); 
    } catch (IOException e) { 
     // TODO Auto-generated catch block 
     e.printStackTrace(); 
    } catch (JSONException e) { 
     // TODO Auto-generated catch block 
     e.printStackTrace(); 
    } 


}   


public void loadResultsFeed(){ 


    resultsFeedRequest = "" + chosenLeagueId + "" + ChosenTeamId + "" + unixTimeStamp; 
    resultsFeedURL = "https://secure.pitchero.com/_services/api/" + resultsFeedRequest; 

    String myhash = buildHmacSignature(apiKey, resultsFeedURL); 

    HttpClient client = new DefaultHttpClient(); 
    HttpPost post = new HttpPost(resultsFeedURL); 

    List<NameValuePair> pairs = new ArrayList<NameValuePair>(); 
    pairs.add(new BasicNameValuePair("requestToken", myhash)); 
    pairs.add(new BasicNameValuePair("apiUser", apiUser)); 

    try { 
     post.setEntity (new UrlEncodedFormEntity(pairs)); 
     HttpResponse response = client.execute(post); 
     BufferedReader reader = new BufferedReader(new InputStreamReader(response.getEntity().getContent(), "UTF-8")); 
     String json = reader.readLine(); 
     fulldata = String.valueOf(json); 
     Log.v("myApp","resultsdata" + fulldata); 

     newsList = new ArrayList<String>(); 
     newsList2 = new ArrayList<String>(); 
     newsList3 = new ArrayList<String>(); 
     imageList = new ArrayList<String>(); 


     JSONObject obj = new JSONObject(json);  
     JSONObject objData = obj.getJSONObject("data"); 
     JSONArray jArray = objData.getJSONArray("results"); 


     if(jArray.length() < 1) loadLastResults(); 

     for(int t = 0; t < 1; t++){ 

       resultsDict = jArray.getJSONObject(t); 
       HomeTeam = resultsDict.getString("hometeam"); 
       AwayTeam = resultsDict.getString("awayteam"); 
       HomeScore = resultsDict.getString("homescore"); 
       AwayScore = resultsDict.getString("awayscore"); 
       Attendance = resultsDict.getString("attendance"); 
       Division = resultsDict.getString("division"); 

       Log.v("lc","hometeam" + HomeTeam); 
       Log.v("lc","awayteam" + AwayTeam); 

      Log.v("BGThread", "Loaded results"); 

      } 

    } catch (ClientProtocolException e) { 
     // TODO Auto-generated catch block 
     e.printStackTrace(); 
    } catch (IOException e) { 
     // TODO Auto-generated catch block 
     e.printStackTrace(); 
    } catch (JSONException e) { 
     // TODO Auto-generated catch block 
     e.printStackTrace(); 
    } 


} 


public void loadLastResults(){ 

    resultsFeedRequest = "" + chosenLeagueId + "" + ChosenTeamId + "&limit=31&timestamp=" + unixTimeStamp; 
    resultsFeedURL = "" + resultsFeedRequest; 

    String myhash = buildHmacSignature(apiKey, resultsFeedURL); 

    Date anotherCurDate = new Date(); 
    SimpleDateFormat formatter = new SimpleDateFormat("MM"); 
    String CurMonth = formatter.format(anotherCurDate); 

    int Int = Integer.parseInt(CurMonth); 

    int MonthInt = Int -1; 


    CurMonth = (String) (String.valueOf(MonthInt)); 



    if (CurMonth.equals("1")){ 

     lastMonth = "12"; 

    }  
    else { 
     if(CurMonth.length() < 2){ 
      lastMonth = "0" + CurMonth; 
     } else { 
      lastMonth = CurMonth; 
     } 
    } 

    Log.v("lc","month= " + CurMonth); 
    Log.v("lc","LastMonth= " + lastMonth); 


     HttpClient client = new DefaultHttpClient(); 
     HttpPost post = new HttpPost(resultsFeedURL); 

     List<NameValuePair> pairs = new ArrayList<NameValuePair>(); 
     pairs.add(new BasicNameValuePair("requestToken", myhash)); 
     pairs.add(new BasicNameValuePair("apiUser", apiUser)); 

     try { 
      post.setEntity (new UrlEncodedFormEntity(pairs)); 
      HttpResponse response = client.execute(post); 
      BufferedReader reader = new BufferedReader(new InputStreamReader(response.getEntity().getContent(), "UTF-8")); 
      String json = reader.readLine(); 
      fulldata = String.valueOf(json); 
      Log.v("myApp","resultsdata" + fulldata); 

      newsList = new ArrayList<String>(); 
      newsList2 = new ArrayList<String>(); 
      newsList3 = new ArrayList<String>(); 
      imageList = new ArrayList<String>(); 


      JSONObject obj = new JSONObject(json);  
      JSONObject objData = obj.getJSONObject("data"); 
      JSONArray jArray = objData.getJSONArray("results"); 


       for(int t = 0; t < 1; t++){ 

        resultsDict = jArray.getJSONObject(t); 
        HomeTeam = resultsDict.getString("hometeam"); 
        AwayTeam = resultsDict.getString("awayteam"); 
        HomeScore = resultsDict.getString("homescore"); 
        AwayScore = resultsDict.getString("awayscore"); 
        Attendance = resultsDict.getString("attendance"); 
        Division = resultsDict.getString("division"); 

        Log.v("lc","hometeam" + HomeTeam); 
        Log.v("lc","awayteam" + AwayTeam); 

       Log.v("BGThread", "Loaded Last results"); 

       } 


     } catch (ClientProtocolException e) { 
      // TODO Auto-generated catch block 
      e.printStackTrace(); 
     } catch (IOException e) { 
      // TODO Auto-generated catch block 
      e.printStackTrace(); 
     } catch (JSONException e) { 
      // TODO Auto-generated catch block 
      e.printStackTrace(); 
     } 


    } 


public class PostTask extends AsyncTask<Void, String, Boolean> { 

    @Override 
    protected Boolean doInBackground(Void... params) { 
     boolean result = false; 

     loadNewsFeed(); 
     publishProgress("method1_complete"); 
     loadResultsFeed(); 
     publishProgress("method2_complete"); 
     return result; 
    } 


    protected void onProgressUpdate(String... progress) { 
     StringBuilder str = new StringBuilder(); 
      for (int i = 1; i < progress.length; i++) { 
       str.append(progress[i] + " "); 

      } 
    } 

     @Override 
    protected void onPostExecute(Boolean result) { 
     super.onPostExecute(result); 
     Log.v("BGThread", "begin fillin data"); 
     FillData(); 
    } 
} 



public void FillData(){ 


    if (ChosenMethod.equals("Team")) { 




     arrayAdapter = new ArrayAdapter<String>(this, R.layout.single_item, newsList); 

     String[] mStrings = (String[]) imageList.toArray(new String[imageList.size()]); 
     String[] news = (String[]) newsList3.toArray(new String[newsList3.size()]); 

     arrayAdapter3 = new LazyAdapter(this, mStrings, news); 


      ListView list = getListView(); 
       list.setTextFilterEnabled(true); 

       LayoutInflater inflater = (LayoutInflater) this.getSystemService(Context.LAYOUT_INFLATER_SERVICE); 
       View header = inflater.inflate(R.layout.homeheader, list, false); 
       View header2 = inflater.inflate(R.layout.homeheader2, list, false); 
       View header3 = inflater.inflate(R.layout.homeheader3, list, false); 


     //setListAdapter (arrayAdapter); 

       resultsView = LayoutInflater.from(getBaseContext()).inflate(R.layout.resultscell, 
         null); 

       TextView homeTeam = (TextView) resultsView.findViewById(R.id.HomeTeam); 
       homeTeam.setText(HomeTeam); 

       TextView awayTeam = (TextView) resultsView.findViewById(R.id.AwayTeam); 
       awayTeam.setText(AwayTeam); 

       TextView homeScore = (TextView) resultsView.findViewById(R.id.HomeScore); 
       homeScore.setText(HomeScore); 

       TextView awayScore = (TextView) resultsView.findViewById(R.id.AwayScore); 
       awayScore.setText(AwayScore); 

       TextView attendance = (TextView) resultsView.findViewById(R.id.Attendence); 
       attendance.setText("Att:" + Attendance); 

       TextView division = (TextView) resultsView.findViewById(R.id.Division); 
       division.setText(Division); 

       Log.v("BGThread", "Filled results"); 

      adapter = new MergeAdapter(); 
      adapter.addView(header); 
      adapter.addAdapter(arrayAdapter); 
      adapter.addView(header2); 
      adapter.addView(resultsView); 
      adapter.addView(header3); 
      adapter.addAdapter(arrayAdapter3); 
      setListAdapter(adapter); 

      Log.v("BGThread", "Filled Merge Adapter Team"); 

    } else { 

     arrayAdapter = new ArrayAdapter<String>(this, R.layout.single_item, newsList); 
      arrayAdapter2 = new ArrayAdapter<String>(this, R.layout.single_item, newsList2); 
      //arrayAdapter3 = new ArrayAdapter(this, R.layout.complex_item, newsList3); 

      String[] mStrings = (String[]) imageList.toArray(new String[imageList.size()]); 
      String[] news = (String[]) newsList3.toArray(new String[newsList3.size()]); 


      arrayAdapter3 = new LazyAdapter(this, mStrings, news); 


       ListView list = getListView(); 
        list.setTextFilterEnabled(true); 

        LayoutInflater inflater = (LayoutInflater) this.getSystemService(Context.LAYOUT_INFLATER_SERVICE); 
        View header3 = inflater.inflate(R.layout.homeheader3, list, false); 


      //setListAdapter (arrayAdapter); 


       adapter = new MergeAdapter(); 
       adapter.addView(header3); 
       adapter.addAdapter(arrayAdapter3); 
       setListAdapter(adapter); 

       Log.v("BGThread", "Filled Merge Adapter League"); 
     } 
} 

回答

1

這兩種方法會按順序執行,因爲他們是一個AsyncTask:第一loadNewsFeed()將被執行,然後如果這是完成,執行loadResultsFeed()

因此,查看您的代碼示例,沒有證據表明沒有執行一個或多個方法。

+0

爲什麼你認爲它只顯示其中一個例如,如果我註釋掉loadResultsFeed()所有的新聞故事加載,但結果沒有。但是當註釋只有結果顯示? –

+0

我們需要看到更多的代碼才能夠回答這個問題。 – nhaarman

+0

我已添加完整的代碼 –

1

你可以有以下邏輯(未測試!)

loadNewsFeed(); 
publishProgress("method1_complete"); 
loadResultsFeed(); 
publishProgress("method2_complete"); 

@Override 
protected void onProgressUpdate(Object... values) 
    { 
     if(values[0].toString().equalsIgnoreCase("method1_complete")) 
     { 
      fill ui from method 1 
     } 
     else 
     { 
      fill ui from method 2 
     } 
     super.onProgressUpdate(values); 
    } 

下面是示例代碼段。

class abc extends AsyncTask<Object, Object, Object> 
    { 

     int i, j; 
     Context context; 

     public abc(AActivity aActivity) 
     { 
      this.context = aActivity; 
     } 

     public void method1() 
     { 
      i = 1; 
     } 

     public void method2() 
     { 
      j = 2; 
     } 

     @Override 
     protected Object doInBackground(Object... params) 
     { 

      method1(); 
      publishProgress("method1"); 
      method2(); 
      publishProgress("method2"); 

      return null; 
     } 

     @Override 
     protected void onProgressUpdate(Object... values) 
     { 
      if (values[0].toString().equalsIgnoreCase("method1")) 
      { 
       EditText text1 = (EditText) findViewById(R.id.text1); 
       text1.setText(String.valueOf(i)); 
      } else 
      { 
       EditText text2 = (EditText) findViewById(R.id.text2); 
       text2.setText(String.valueOf(j)); 
      } 
      super.onProgressUpdate(values); 
     } 

    } 
+0

這將加載兩個在同一時間沒有一個在另一個? –

+0

是的,我測試了這個代碼!你可以給一個機會 –