2012-09-08 136 views
4

public class HttpHelper extends AsyncTask> { ArrayList list = new ArrayList();Android AsyncTask:開始新活動onPostExecute()

@Override 
protected ArrayList<String> doInBackground(String... urls) { 
    // TODO Auto-generated method stub 

    String result=""; 
    for(String url:urls) 
    { 
     HttpClient client = new DefaultHttpClient(); 
     HttpGet request = new HttpGet(url); 
     try 
     { 
      HttpResponse response = client.execute(request); 
      InputStream in = response.getEntity().getContent(); 
      BufferedReader br = new BufferedReader(new InputStreamReader(in)); 
      String line = null; 
      StringBuffer sb = new StringBuffer(); 
      while((line = br.readLine())!=null) 
      { 
       sb.append(line+"\n"); 

      } 
      in.close(); 
      result = sb.toString(); 
      String pageSource = new String(result); 
      int startindex = pageSource.indexOf("pdf_doc/"); 
      String str=""; 
      String []temp; 
      while(startindex !=-1) 
      { 
       int endindex = pageSource.indexOf(".pdf",startindex); 
       str = pageSource.substring(startindex+8, endindex); 
       String delimiter = "%20"; 
       String value=""; 
       temp = str.split(delimiter) ; 
       for(int i=0;i<temp.length;i++) 
       { 
        value= value+temp[i]+" "; 

       } 

       list.add(value); 
       startindex = pageSource.indexOf("pdf_doc/",endindex); 
      } 
     } 


     catch(Exception ex) 
     { 
      Log.e("Error in HTML Reading",ex.getMessage()); 

     } 

    } 

    return list; 

} 

@Override 
protected void onPostExecute(ArrayList<String> result) { 
    // TODO Auto-generated method stub 

     // Here i want to start new UI that use the result of AsyncTask 
} 

}

在該代碼中,我通過的AsyncTask從服務器讀取數據和結果應當是在新的裝置UI.That我想要開始onPostExecute新活動()。

+1

得到你當前活動的背景和究竟是你的問題?你有什麼嘗試?你得到什麼錯誤? –

回答

18

試試這個,

@Override 
protected void onPostExecute(Void result) 
{ 
    super.onPostExecute(result); 
    Intent intent = new Intent(MyAsyncTaskActivity.this, NextActivity.class); 
    intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK); 
    getApplicationContext().startActivity(intent); 
} 
+0

你需要更多upvotes。 :D – Sheharyar

+3

'getApplicationContext()'在AsyncTask中不可用。至少如果你把它放到一個沒有從'Context'繼承的類中 – High6

0

getApplicationContext()不能從AsyncTasck調用。相反,你可以在構造函數中聲明一個變量ctx,它是getApplicationContext()

@Override 
protected void onPostExecute(Void result) 
{ 
    super.onPostExecute(result); 
    Intent intent = new Intent(ctx.this, NextActivity.class); 
    intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK); 
    ctx.startActivity(intent); 
} 
0

或者,你可以通過調用當前的名字,像這樣MyAsyncTaskActivity.this

@Override 
protected void onPostExecute(Void result) 
{ 
    super.onPostExecute(result); 
    Intent intent = new Intent(MyAsyncTaskActivity.this, NextActivity.class); 
    intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK); 
    MyAsyncTaskActivity.this.startActivity(intent); 
}