2016-12-10 3 views
0

私はしましたAsyncTaskのメソッドAsyncTaskのメソッドをどのように渡しますか?

class Wrapper { 

    public static String AuthIn(String Login, String Password){ 
    String response = HTTPRequest.POST(client, GetAuthUrl(), RequestBuilder.AuthInVk(login, password)); 
        System.out.println(response); 
    } 

    public static String GetInfoUser(){ 
    String response = HTTPRequest.GET(client, "http://site1.com"); 
    System.out.println(response); 
    } 
} 

私はMainActivityクラスでこのメソッドを呼び出すと、エラーメッセージを取得「のメインスレッドを.....など」

どのように書き込みラッパークラスを持つクラス?

+0

あなたの質問を手直ししてください、 – Opiatefuchs

答えて

0

あなたは常にUIスレッド以外のスレッドのネットワーク要求フォームを実行する必要があります。したがって、AsyncTaskまたはThreadまたはRunnableを拡張するabstarctクラス(ネットワークディスパッチャ)を作成し、run/doInBackground /などで呼び出されるabstarctメソッドを追加できます。次に、メソッド内でabstarctメソッドを実装します。しかし、定型コードのほんの少し改良されています。また、JavaRx(AndroidRx)を使用してネットワーキング方法を実行することもできます。また、JavaRxでRetrofitを使用することもできます。私はあなたがあなたの質問を編集参照

EDIT

。 AsyncTaskを使用したい場合は、それを実装してdoInBackgroudでリクエストを実行する必要があります

+0

本当に理解できない各メソッド(authin、getuserinfoをit's )doInBackgroundに入れますか? – Petr

1

codexpediaからの素晴らしい例です。詳細はサイトをチェックしてください。

public class MainActivity extends AppCompatActivity { 

    TextView tvWeatherJson; 
    Button btnFetchWeather; 
    @Override 
    protected void onCreate(Bundle savedInstanceState) { 
     super.onCreate(savedInstanceState); 
     setContentView(R.layout.activity_main); 
     tvWeatherJson = (TextView) findViewById(R.id.tv_weather_json); 
     btnFetchWeather = (Button) findViewById(R.id.btn_fetch_weather); 
     btnFetchWeather.setOnClickListener(new View.OnClickListener() { 
      @Override 
      public void onClick(View v) { 
       new FetchWeatherData().execute(); 
      } 
     }); 
    } 


    private class FetchWeatherData extends AsyncTask<Void, Void, String> { 

     @Override 
     protected String doInBackground(Void... params) { 
      // These two need to be declared outside the try/catch 
      // so that they can be closed in the finally block. 
      HttpURLConnection urlConnection = null; 
      BufferedReader reader = null; 

      // Will contain the raw JSON response as a string. 
      String forecastJsonStr = null; 

      try { 
       // Construct the URL for the OpenWeatherMap query 
       // Possible parameters are avaiable at OWM's forecast API page, at 
       // http://openweathermap.org/API#forecast 
       URL url = new URL("http://api.openweathermap.org/data/2.5/forecast/daily?q=94043&mode=json&units=metric&cnt=7&appid=2de143494c0b295cca9337e1e96b00e0"); 

       // Create the request to OpenWeatherMap, and open the connection 
       urlConnection = (HttpURLConnection) url.openConnection(); 
       urlConnection.setRequestMethod("GET"); 
       urlConnection.connect(); 

       // Read the input stream into a String 
       InputStream inputStream = urlConnection.getInputStream(); 
       StringBuffer buffer = new StringBuffer(); 
       if (inputStream == null) { 
        // Nothing to do. 
        return null; 
       } 
       reader = new BufferedReader(new InputStreamReader(inputStream)); 

       String line; 
       while ((line = reader.readLine()) != null) { 
        // Since it's JSON, adding a newline isn't necessary (it won't affect parsing) 
        // But it does make debugging a *lot* easier if you print out the completed 
        // buffer for debugging. 
        buffer.append(line + "\n"); 
       } 

       if (buffer.length() == 0) { 
        // Stream was empty. No point in parsing. 
        return null; 
       } 
       forecastJsonStr = buffer.toString(); 
       return forecastJsonStr; 
      } catch (IOException e) { 
       Log.e("PlaceholderFragment", "Error ", e); 
       // If the code didn't successfully get the weather data, there's no point in attemping 
       // to parse it. 
       return null; 
      } finally{ 
       if (urlConnection != null) { 
        urlConnection.disconnect(); 
       } 
       if (reader != null) { 
        try { 
         reader.close(); 
        } catch (final IOException e) { 
         Log.e("PlaceholderFragment", "Error closing stream", e); 
        } 
       } 
      } 
     } 

     @Override 
     protected void onPostExecute(String s) { 
      super.onPostExecute(s); 
      tvWeatherJson.setText(s); 
      Log.i("json", s); 
     } 
    } 
} 

あなたは非同期タスクdoInBackgroundまたはonPostExcuteにデータを渡すと、よりこのstackoverflowのコメントをチェックしたい場合:what-arguments-are-passed-into-asynctaskarg1-arg2-arg3

に注意してくださいあなたのAsyncTaskは活動が破壊された場合であっても停止しません。活動からのネットワーク呼び出しを作成するための良い方法はHandlerそれとも、このようgoogle volleyok-httpとしてlibにasyncHttpクライアントを使用している:)

+0

クール!私はok-httpでasyncHttpに使用されます:) thx! – Petr

関連する問題