2012-04-08 103 views
0

我想從HttpPost下載字符串,並使用Async類來執行此操作。但是,當我運行該應用程序時,它崩潰了。這是我第一次使用Async類,恐怕我做了一些非常愚蠢的事情,你能幫我找到錯誤嗎?異步任務崩潰我的應用程序

只需要注意,我還想在獲取字符串時更新列表視圖。我試圖做到這一點,購買他們在一個單獨的方法。

代碼:

public static final String PREFS_NAME = "MyPrefsFile"; 
    BufferedReader in = null; 
    String data = null; 
    String username; 
    List headlines; 
    List links; 
    String password; 
    ArrayAdapter adapter; 


    @Override 
    public void onCreate(Bundle savedInstanceState) { 
     super.onCreate(savedInstanceState); 
      // listview method 
      ContactsandIm(); 
     new loadcontactsandIm().execute(PREFS_NAME); 

    } 

    public class loadcontactsandIm extends AsyncTask<String, Integer, String> { 
     @Override 
     protected String doInBackground(String... arg0) { 
      // TODO Auto-generated method stub 

      // Create a new HttpClient and Post Header 
      HttpClient httpclient = new DefaultHttpClient(); 

      /* login.php returns true if username and password is equal to saranga */ 
      HttpPost httppost = new HttpPost("http://gta5news.com/login.php"); 

      try { 

       List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(2); 
       nameValuePairs.add(new BasicNameValuePair("username", username)); 
       nameValuePairs.add(new BasicNameValuePair("password", password)); 
       httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs)); 

       // Execute HTTP Post Request 
       Log.w("HttpPost", "Execute HTTP Post Request"); 
       HttpResponse response = httpclient.execute(httppost); 
       Log.w("HttpPost", "Execute HTTP Post Request"); 
       in = new BufferedReader(new InputStreamReader(response.getEntity() 
         .getContent())); 
       StringBuffer sb = new StringBuffer(""); 
       String l =""; 
       String nl =""; 
       while ((l =in.readLine()) !=null) { 
        sb.append(l + nl); 
       } 
       in.close(); 
       data = sb.toString(); 
       ListView lv = getListView(); 
       lv.setTextFilterEnabled(true); 

       headlines.add(data); 




       setListAdapter(adapter); 
       return null; 

      } catch (ClientProtocolException e) { 
       e.printStackTrace(); 
      } catch (IOException e) { 
       e.printStackTrace(); 
      } 
      return data; 
     } 

     private StringBuilder inputStreamToString(InputStream is) { 
      String line = ""; 
      StringBuilder total = new StringBuilder(); 
      // Wrap a BufferedReader around the InputStream 
      BufferedReader rd = new BufferedReader(new InputStreamReader(is)); 
      // Read response until the end 
      try { 
       while ((line = rd.readLine()) != null) { 
        total.append(line); 
       } 
      } catch (IOException e) { 
       e.printStackTrace(); 
      } 
      // Return full string 
      return total; 
     } 

     } 


    public void ContactsandIm() { 
     headlines = new ArrayList(); 

     //get prefs 
     SharedPreferences settings = getSharedPreferences(PREFS_NAME, 0); 
     String username = settings.getString("key1", null); 
     String password = settings.getString("key2", null); 
     if(username.equals("irock97")) { 
      Toast toast=Toast.makeText(this, "Hello toast", 2000); 
      toast.setGravity(Gravity.TOP, -30, 50); 
      toast.show(); 

     } else { 
      Toast toast=Toast.makeText(this, "Hello toast", 2000); 
      toast.setGravity(Gravity.TOP, -30, 150); 
      toast.show(); 
     } 
     ArrayAdapter adapter = new ArrayAdapter(this, 
       android.R.layout.simple_list_item_1, headlines); 


    } 

} 

的logcat:

03-25 13:47:37.356: E/AndroidRuntime(2484): FATAL EXCEPTION: AsyncTask #1 
03-25 13:47:37.356: E/AndroidRuntime(2484): java.lang.RuntimeException: An error occured while executing doInBackground() 
03-25 13:47:37.356: E/AndroidRuntime(2484):  at android.os.AsyncTask$3.done(AsyncTask.java:200) 
03-25 13:47:37.356: E/AndroidRuntime(2484):  at java.util.concurrent.FutureTask$Sync.innerSetException(FutureTask.java:273) 
03-25 13:47:37.356: E/AndroidRuntime(2484):  at java.util.concurrent.FutureTask.setException(FutureTask.java:124) 
03-25 13:47:37.356: E/AndroidRuntime(2484):  at java.util.concurrent.FutureTask$Sync.innerRun(FutureTask.java:307) 
03-25 13:47:37.356: E/AndroidRuntime(2484):  at java.util.concurrent.FutureTask.run(FutureTask.java:137) 
03-25 13:47:37.356: E/AndroidRuntime(2484):  at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1068) 
03-25 13:47:37.356: E/AndroidRuntime(2484):  at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:561) 
03-25 13:47:37.356: E/AndroidRuntime(2484):  at java.lang.Thread.run(Thread.java:1096) 
03-25 13:47:37.356: E/AndroidRuntime(2484): Caused by: android.view.ViewRoot$CalledFromWrongThreadException: Only the original thread that created a view hierarchy can touch its views. 
03-25 13:47:37.356: E/AndroidRuntime(2484):  at android.view.ViewRoot.checkThread(ViewRoot.java:2802) 
03-25 13:47:37.356: E/AndroidRuntime(2484):  at android.view.ViewRoot.requestLayout(ViewRoot.java:594) 
03-25 13:47:37.356: E/AndroidRuntime(2484):  at android.view.View.requestLayout(View.java:8125) 
03-25 13:47:37.356: E/AndroidRuntime(2484):  at android.view.View.requestLayout(View.java:8125) 
03-25 13:47:37.356: E/AndroidRuntime(2484):  at android.view.View.requestLayout(View.java:8125) 
03-25 13:47:37.356: E/AndroidRuntime(2484):  at android.view.ViewGroup.removeAllViews(ViewGroup.java:2255) 
03-25 13:47:37.356: E/AndroidRuntime(2484):  at com.android.internal.policy.impl.PhoneWindow.setContentView(PhoneWindow.java:196) 
03-25 13:47:37.356: E/AndroidRuntime(2484):  at android.app.Activity.setContentView(Activity.java:1647) 
03-25 13:47:37.356: E/AndroidRuntime(2484):  at android.app.ListActivity.ensureList(ListActivity.java:314) 
03-25 13:47:37.356: E/AndroidRuntime(2484):  at android.app.ListActivity.getListView(ListActivity.java:299) 
03-25 13:47:37.356: E/AndroidRuntime(2484):  at com.gta5news.bananaphone.ChatService$loadcontactsandIm.doInBackground(ChatService.java:87) 
03-25 13:47:37.356: E/AndroidRuntime(2484):  at com.gta5news.bananaphone.ChatService$loadcontactsandIm.doInBackground(ChatService.java:1) 
03-25 13:47:37.356: E/AndroidRuntime(2484):  at android.os.AsyncTask$2.call(AsyncTask.java:185) 
03-25 13:47:37.356: E/AndroidRuntime(2484):  at java.util.concurrent.FutureTask$Sync.innerRun(FutureTask.java:305) 

回答

2

你工作在doInBackground,並使用你的職位上onPostExecute導致。

例如:

public class TestActivity extends Activity 
{ 
    private GetTask getTask; 
    public ListView fList; 

    @Override 
    public void onCreate(Bundle savedInstanceState) 
    { 
    getTask = new GetTask(); 
    getTask.execute(); 
    fList = (ListView) findViewById(R.id.lstview); 
    } 

    public class GetTask extends AsyncTask<Void, Void, List> 
    { 
    @Override 
    protected List doInBackground(Void... params) { 
     return load(); 
    }  

    @Override 
    protected void onPostExecute(List result) { 
     ArrayAdapter adapter = new ArrayAdapter(this, 
       android.R.layout.simple_list_item_1, headlines); 

     fList.setAdapter(adapter); 
    } 
    } 

    private List load() { 
    // get your data from http 
    // add to your list, probably you can use model. 
    List headlines; 
    headlines.add(data); 

    return headlines; 
    } 


} 
2

您設置doInBackground你的ListView適配器。永遠不要在UI線程之外操作UI

2

您不能與除主線程以外的任何其他線程交互UI元素。您需要完成onPostExecute方法中ListView的所有交互操作。

基本上你會想要編譯doInBackground方法中的web請求中的所有數據,存儲在你的任務實例上,然後onPostExecute獲取列表視圖並設置適配器並填充數據。

+0

好吧,我來試試,並報告。 – TheBlueCat 2012-04-08 15:10:52

+0

你是說'onPostExecute'在UI線程中執行?我一直認爲它也在後臺線程中執行? – Ali 2012-04-08 15:34:20

+0

否,onPostExecute(),onPreExecute()和onProgressUpdate()都在UI線程上運行。 – Shubhayu 2012-04-08 16:08:46

1

首先,你必須很好地處理doInBackground(任何UI相關的任務)與UI相關的任務,我們有一個方法調用onPostExecute(),我們可以處理所有UI相關的任務.. 如果您還不想使用這些方法和處理它在doInBackground(),那麼你這樣做在下面的代碼::::

runOnUiThread(new Runnable() { 
public void run() { 
//your UI related code stuff  
    ListView lv = getListView(); 
    lv.setTextFilterEnabled(true); 
    headlines.add(data); 
    setListAdapter(adapter); //do what you like here 
} 
}); 
+0

我會在幾分鐘內嘗試,所以我會在onPostExecute()中做所有UI元素?包括更新列表視圖? – TheBlueCat 2012-04-08 17:40:27