2012-04-23 7 views
0

私は呼び出しているメソッドがありますが、新しいバージョンのAndroidでは失敗します。明らかに、これはスレッディングがないためです。私の方法は私のサーバーにメッセージを送信することです。アンドロイドでスレッドを作成すると動作しない

public String sendMessage(String username, Editable message){ 
     BufferedReader in = null; 
     String data = null; 
Thread sendThread = new Thread(){ 
     try{ 
      DefaultHttpClient client = new DefaultHttpClient(); 
      URI website = new URI("http://thenjtechguy.com/njit/gds/user_send.php?username="+username+"&message="+message); 

      HttpPost post_request = new HttpPost(); 
      post_request.setURI(website); 


      HttpGet request = new HttpGet(); 

      request.setURI(website); 
      //executing actual request 
      HttpResponse response = client.execute(request); 

      in = new BufferedReader(new InputStreamReader(response.getEntity().getContent())); 
      StringBuffer sb = new StringBuffer(""); 
      String l = ""; 
      String nl = System.getProperty("line.separator"); 
      while ((l = in.readLine()) != null) { 
       sb.append(l); 

      } 
      in.close(); 
      data = sb.toString(); 
      return data; 
     }catch (Exception e){ 
      return "ERROR"; 
     } 
} sendThread.start(); 
} 

をしかし、それは動作しません:これはちょうどそれの周りに糸を入れしようとしている、今のコード(スレッドサンセリフ)

public String sendMessage(String username, Editable message){ 
     BufferedReader in = null; 
     String data = null; 

     try{ 
      DefaultHttpClient client = new DefaultHttpClient(); 
      URI website = new URI("http://abc.com/user_send.php?username="+username+"&message="+message); 

      HttpPost post_request = new HttpPost(); 
      post_request.setURI(website); 


      HttpGet request = new HttpGet(); 

      request.setURI(website); 
      //executing actual request 
      HttpResponse response = client.execute(request); 

      in = new BufferedReader(new InputStreamReader(response.getEntity().getContent())); 
      StringBuffer sb = new StringBuffer(""); 
      String l = ""; 
      String nl = System.getProperty("line.separator"); 
      while ((l = in.readLine()) != null) { 
       sb.append(l); 

      } 
      in.close(); 
      data = sb.toString(); 
      return data; 
     }catch (Exception e){ 
      return "ERROR"; 
     } 
    } 

です。私は間違って何をしていますか?また、HttpClientに関するAndroidの基本的なルールを破っていることに気がついたら、私に知らせてください。

答えて

1

頭をよくしてAsyncTaskのコンセプトを使用してください。

AsyncTaskを使用すると、UIスレッドを適切かつ簡単に使用できます。このクラスを使用すると、スレッドやハンドラを操作することなく、バックグラウンド操作を実行し、UIスレッドで結果を公開できます。 サンプル実装のために、このLINKを参照してください

2

あなたの実装が正しくありません - あなたが実行を無効にしませんでした()メソッド

class SendThread extends Thread { 
    public void run(){ 
     //add your implementation here 
    } 
} 

トウスレッドが

SendThread sendThread = new SendThread(); 
sendThread.start(); 
+0

うーん...私はそれを実行してみまし開始しかし、私は括弧でエラーを取得します。私はあなたの答えを正しく使っているとは思わない。申し訳ありませんが、私はまだ非常にプログラミングに新しいです。 – EGHDK

+0

エラーは何ですか? –

+0

それは致命的な例外を言う:4月23日00:30:18.234:E/AndroidRuntime(29500):java.lang.RuntimeException:Looper.prepare(呼び出されていないスレッド内でハンドラを作成することはできません) – EGHDK

関連する問題