效果图:
项目结构不变,不清楚的请拉到最顶部查看上一章博文
MainActivity.java
public class MainActivity extends AppCompatActivity {
private static final String TAG = "MainActivity"; //Log-Name
private CardBean cardBean = new CardBean(); //新增代码
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
queryOkHttp();
}
//请求服务器数据
private void queryOkHttp() {
new Thread(new Runnable() {
@Override
public void run() {
try {
JSONObject jsonObject = new JSONObject();
jsonObject.put("UserName", "user1");
jsonObject.put("CarId",1);
final JSONObject result = OkHttp.send("GetCarAccountBalance.do", jsonObject);
Log.i(TAG, "run: " + result);
parsingJson(result); //手动解析JSON数据
} catch (JSONException e) {
e.printStackTrace();
}
}
}).start();
}
//手动解析JSON数据,根据服务器返回的对应键名来取值并且赋值给bean
private void parsingJson(JSONObject result) throws JSONException {
try {
bean.setPm2_5(result.getInt("pm2.5"));
bean.setCo2(result.getInt("co2"));
bean.setHumidity(result.getInt("humidity"));
bean.setLightIntensity(result.getInt("LightIntensity"));
bean.setTemperature(result.getInt("temperature"));
}catch (JSONException e){
e.printStackTrace();
}
}
}