読者です 読者をやめる 読者になる 読者になる

name_untitledのエッセイ

IT関係で知ったことなどを記事としてあげていきます。内容に不備や質問などあればぜひコメントをよせてください。

Android ライブラリを使ったサンプルアプリ 今の天気

f:id:name_untitled:20161202234929p:plainf:id:name_untitled:20161202234922p:plain

build.gradle

apply plugin: 'com.android.application'

android {
    compileSdkVersion 24
    buildToolsVersion "24.0.2"

    defaultConfig {
        applicationId "xx.xxx.weathernews"
        minSdkVersion 21
        targetSdkVersion 21
        versionCode 1
        versionName "1.0"
    }
    buildTypes {
        release {
            minifyEnabled false
            proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
        }
    }
}

dependencies {
    compile fileTree(dir: 'libs', include: ['*.jar'])
    testCompile 'junit:junit:4.12'
    compile 'com.android.support:appcompat-v7:24.2.1'
    compile 'com.squareup.okhttp:okhttp:2.7.0'
    compile 'com.google.code.gson:gson:2.3.1'
    compile 'com.jakewharton:butterknife:8.4.0'
    compile 'com.jakewharton:butterknife-compiler:8.4.0'
    compile 'com.fasterxml.jackson.core:jackson-core:2.7.1'
    compile 'com.fasterxml.jackson.core:jackson-annotations:2.7.1'
    compile 'com.fasterxml.jackson.core:jackson-databind:2.7.1'
    compile 'org.glassfish.main:javax.annotation:4.0-b33'
}

画面をこんな感じで作る
f:id:name_untitled:20161203000915p:plain


天気アイコンをこのサイトに載っている分だけ用意する。
Weather Conditions- OpenWeatherMap


JSONファイルからModelクラスを生成して、プロジェクトに入れる。
www.jsonschema2pojo.org

f:id:name_untitled:20161203001120p:plain


MainActivity.java

package la.fe_nuol.weathernews;

import android.graphics.drawable.Drawable;
import android.media.Image;
import android.os.Handler;
import android.os.Looper;
import android.provider.ContactsContract;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ImageView;
import android.widget.Spinner;
import android.widget.TextView;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.google.gson.Gson;
import com.squareup.okhttp.Callback;
import com.squareup.okhttp.OkHttpClient;
import com.squareup.okhttp.Request;
import com.squareup.okhttp.Response;
import org.json.JSONException;
import org.json.JSONObject;
import java.io.IOException;

import butterknife.BindDrawable;
import butterknife.BindView;

public class MainActivity extends AppCompatActivity {
    String baseUrl = "http://api.openweathermap.org/data/2.5/weather";
    String appId = "XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX";
    Handler mHandler;

    @BindView(R.id.textView) TextView weather;
    @BindView(R.id.imageView) ImageView icon;
    @BindView(R.id.textView2) TextView temperature;
    @BindView(R.id.textView3) TextView humidity;
    @BindView(R.id.textView4) TextView description;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        Spinner cities = (Spinner)findViewById(R.id.spinner);
        cities.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
            @Override
            public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
                if(((TextView)view) == null) return;
                setWeather(((TextView)view).getText().toString());
            }
            @Override
            public void onNothingSelected(AdapterView<?> parent) {}
        });
    }
    @Override
    protected void onStart(){
        super.onStart();
        mHandler = new Handler(Looper.getMainLooper());
        setWeather("Vientiane");

    }

    private Drawable getIconDrawable(String name){
        int id = getResources().getIdentifier("w" + name,
                "drawable",getPackageName());
        return getDrawable(id);
    }

    private void setWeather(String cityName){
        String urlText = String.format("%s?q=%s&appid=%s&units=metric",baseUrl,cityName,appId);
        Request request = new Request.Builder().url(urlText).build();
        OkHttpClient client = new OkHttpClient();
        client.newCall(request).enqueue(new Callback() {
            @Override
            public void onFailure(Request request, IOException e) {}
            @Override
            public void onResponse(Response response) throws IOException {
                final String result = response.body().string().toString();
                Runnable runnable = new Runnable() {
                    @Override
                    public void run() {
                        try{
                            ObjectMapper mapper = new ObjectMapper();
                            WeatherInfo info = mapper.readValue(result, WeatherInfo.class);
                            weather.setText(info.getWeather().get(0).getMain());
                            icon.setImageDrawable(getIconDrawable(info.getWeather().get(0).getIcon()));
                            temperature.setText("temp: " + info.getMain().getTemp().toString());
                            humidity.setText("humidity: " + info.getMain().getHumidity().toString());
                            description.setText("description: " +info.getWeather().get(0).getDescription());
                        }catch(IOException ioe){ioe.getStackTrace();}
                    }
                };
                mHandler.post(runnable);
            }
        });
    }
}