Created
November 18, 2015 23:41
-
-
Save michaelrkn/14c623e43437001ed098 to your computer and use it in GitHub Desktop.
asynchrony
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package com.example.michael.forecaster; | |
import com.squareup.okhttp.Call; | |
import com.squareup.okhttp.Callback; | |
import com.squareup.okhttp.OkHttpClient; | |
import com.squareup.okhttp.Request; | |
public class Forecaster { | |
public void fetchForecast(int zip, Callback callback) { | |
String forecastUrl = "https://api.forecast.io/forecast/cf0a68ec329b33b4189e84ce83990a97/47,122"; | |
OkHttpClient client = new OkHttpClient(); | |
Request request = new Request.Builder() | |
.url(forecastUrl) | |
.build(); | |
Call call = client.newCall(request); | |
call.enqueue(callback); | |
} | |
} |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package com.example.michael.forecaster; | |
import android.support.v7.app.AppCompatActivity; | |
import android.os.Bundle; | |
import android.view.View; | |
import android.widget.Button; | |
import android.widget.EditText; | |
import android.widget.TextView; | |
import com.squareup.okhttp.Callback; | |
import com.squareup.okhttp.Request; | |
import com.squareup.okhttp.Response; | |
import java.io.IOException; | |
public class MainActivity extends AppCompatActivity { | |
EditText mZipInput; | |
Button mGetForecastButton; | |
TextView mForecastText; | |
@Override | |
protected void onCreate(Bundle savedInstanceState) { | |
super.onCreate(savedInstanceState); | |
setContentView(R.layout.activity_main); | |
mZipInput = (EditText) findViewById(R.id.zipInput); | |
mGetForecastButton = (Button) findViewById(R.id.getForecastButton); | |
mForecastText = (TextView) findViewById(R.id.forecastText); | |
mGetForecastButton.setOnClickListener(new View.OnClickListener() { | |
@Override | |
public void onClick(View v) { | |
fetchForecast(); | |
} | |
}); | |
} | |
private void fetchForecast() { | |
int zip = Integer.parseInt(mZipInput.getText().toString()); | |
final Forecaster forecaster = new Forecaster(); | |
forecaster.fetchForecast(zip, new Callback() { | |
@Override | |
public void onResponse(Response response) throws IOException { | |
// handle response | |
MainActivity.this.runOnUiThread(new Runnable() { | |
public void run() { | |
MainActivity.this.mForecastText.setText("rainy"); | |
} | |
}); | |
} | |
@Override | |
public void onFailure(Request request, IOException e) { | |
// handle failure | |
} | |
}); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment