티스토리 뷰

ANDROID/android

Android - RXAndroid Retrofit

BAEKNAMU 2016. 11. 14. 16:55


APP Build.Gradle


compile 'io.reactivex:rxandroid:1.2.1'


MainActivity.java

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
public class MainActivity extends AppCompatActivity {
    static final String BASE_URL = "http://api.openweathermap.org";
    static final String API_KEY = "*****************************";
    EditText city;
    TextView result;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        result = (TextView) findViewById(R.id.result);
        city = (EditText) findViewById(R.id.editText);
        Button btnWeather = (Button) findViewById(R.id.btnWeather);
 
        btnWeather.setOnClickListener( e -> getWeather() );
 
    }
 
    public void getWeather(){
        String cityName = city.getText().toString();
 
        // 1. Retrofit 클라이언트 생성
        Retrofit client = new Retrofit.Builder()
                .baseUrl(BASE_URL)
                .addConverterFactory(GsonConverterFactory.create())
                .addCallAdapterFactory(RxJavaCallAdapterFactory.create())
                .build();
 
        // 2. RestAPi 서비스 생성
        IWeather service = client.create(IWeather.class);
 
        // 3. 데이터 Observable 생성
        Observable<Data> weatherData = service.getData(cityName, API_KEY);
 
        // 4. scribeOn
        // 가. 데이터를 가져오는 대상 Observable : newTHread 로 새로운 Thread 에서 작업한다.
        // 나. 화면에 새팅하는 Observer : main Thread에서 작업한다.
        weatherData.subscribeOn(Schedulers.newThread())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(
                        data -> {
                            String temp = "";
                            temp += "ID:" + data.getId();
                            temp += "\nName:" + data.getName();
                            temp += "\nBase:" + data.getBase();
                            result.setText(temp);
                    }
                );
 
    }
}
cs


https://github.com/baekcedar/RXAndroid


'ANDROID > android' 카테고리의 다른 글

Android - phone 번호 가져오기  (0) 2016.11.30
Android - back 버튼 활용  (0) 2016.11.28
Android Google Map 추가하기  (0) 2016.11.10
Android - Code Obfuscation (난독화) / Decompile  (0) 2016.11.02
Android - Motion Sensors  (0) 2016.11.01
Comments
최근에 올라온 글
최근에 달린 댓글
TAG
more
Total
Today
Yesterday