You can not select more than 25 topics
Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
96 lines
2.9 KiB
96 lines
2.9 KiB
package net.micode.notes.ui;
|
|
|
|
import android.app.Activity;
|
|
import android.os.Bundle;
|
|
import android.os.Message;
|
|
import android.util.Log;
|
|
import android.view.View;
|
|
import android.widget.EditText;
|
|
import android.widget.TextView;
|
|
|
|
import com.google.gson.Gson;
|
|
import com.google.gson.reflect.TypeToken;
|
|
|
|
import net.micode.notes.R;
|
|
import net.micode.notes.data.WeatherBean;
|
|
|
|
import java.io.IOException;
|
|
import java.lang.reflect.Type;
|
|
|
|
import okhttp3.Call;
|
|
import okhttp3.Callback;
|
|
import okhttp3.OkHttpClient;
|
|
import okhttp3.Request;
|
|
import okhttp3.Response;
|
|
|
|
public class WeatherActivity extends Activity {
|
|
EditText et_search;
|
|
TextView tv_search,city,weather;
|
|
String content;
|
|
@Override
|
|
protected void onCreate(Bundle savedInstanceState) {
|
|
super.onCreate(savedInstanceState);
|
|
setContentView(R.layout.activity_weather);
|
|
et_search = (EditText) findViewById(R.id.et_search);
|
|
tv_search = (TextView) findViewById(R.id.tv_search);
|
|
weather = (TextView) findViewById(R.id.weather);
|
|
city = (TextView) findViewById(R.id.content);
|
|
tv_search.setOnClickListener(new View.OnClickListener() {
|
|
@Override
|
|
public void onClick(View view) {
|
|
content = et_search.getText().toString();
|
|
request();
|
|
}
|
|
});
|
|
|
|
}
|
|
|
|
private void request() {
|
|
|
|
|
|
//通过okhttp访问servlet
|
|
String strURL = "https://apis.tianapi.com/tianqi/index?key=46b609e64712e310beaabd3901fce265&city=101020100&city="+content+"&type=1";
|
|
|
|
|
|
Request request = new Request.Builder()
|
|
.url(strURL)
|
|
|
|
.build();
|
|
|
|
|
|
OkHttpClient okHttpClient = new OkHttpClient();
|
|
Call call = okHttpClient.newCall(request);
|
|
|
|
//接收相应,进入子线程
|
|
call.enqueue(new Callback() {
|
|
@Override
|
|
public void onFailure(Call call, IOException e) {
|
|
Message message = new Message();
|
|
message.what = 2;
|
|
message.obj = e.getMessage();
|
|
//通过handler向主线程发生json数据
|
|
}
|
|
|
|
@Override
|
|
public void onResponse(Call call, Response response) throws IOException {
|
|
String json = response.body().string();
|
|
Log.d("weather","weather"+json);
|
|
Gson gson = new Gson();
|
|
Type type = new TypeToken<WeatherBean>(){}.getType();
|
|
WeatherBean weatherObject = gson.fromJson(json, type);
|
|
if (weatherObject.code == 200) {
|
|
runOnUiThread(new Runnable() {
|
|
@Override
|
|
public void run() {
|
|
city.setText("城市:"+weatherObject.result.area);
|
|
weather.setText(weatherObject.result.weather+weatherObject.result.real);
|
|
}
|
|
});
|
|
}
|
|
|
|
}
|
|
});
|
|
}
|
|
|
|
}
|