티스토리 뷰
public class GetExample extends Thread {
private String uurl = "http://api.openweathermap.org/data/2.5/weather?lat=35&lon=139&appid=2de143494c0b295cca9337e1e96b00e0";
private String parse;
private OkHttpClient client = new OkHttpClient();
private Handler handler;
public GetExample(Handler handler) {
this.handler = handler;
}
@Override
public void run() {
super.run();
try {
parse = run(uurl);
} catch (IOException e) {
e.printStackTrace();
}
Mhandler(parse);
}
String run(String url) throws IOException {
Request request = new Request.Builder()
.url(url)
.build();
Response response = client.newCall(request).execute();
return response.body().string();
}
private void Mhandler(String parse) {
Message msg = new Message();
msg.obj = parse;
handler.sendMessage(msg);
}
}
public class MainActivity extends Activity implements View.OnClickListener {
private Button main_btn;
private TextView main_txt;
public String mStrJson;
private Handler handler;
private GetExample getExample;
private String jsonparse, parseData;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
main_btn = (Button) findViewById(R.id.main_btn);
main_txt = (TextView) findViewById(R.id.main_txt);
main_btn.setOnClickListener(this);
}
private void parsing(String mStrJson) {
try {
JSONObject object0 = new JSONObject(mStrJson);
JSONObject coord=object0.getJSONObject("coord");
String coorddata="lon : "+coord.getString("lon")+" lat : "+coord.getString("lat");
Log.e("coorddata : ",coorddata);
main_txt.setText(coorddata);
} catch (JSONException e) {
Log.e("", e.getMessage());
}
}
@Override
public void onClick(View v) {
handler = new Handler() {
@Override
public void handleMessage(Message msg) {
super.handleMessage(msg);
mStrJson = (String) msg.obj;
Log.e("점검", mStrJson);
parsing(mStrJson);
}
};
GetExample getExample = new GetExample(handler);
getExample.start();
switch (v.getId()) {
case R.id.main_btn:
break;
}
}
}
151112