public static final int downloadDone = 1;//用户model数组
ArrayList loginers = new ArrayList<>();//hander
Handler downloadLoginerHandler = newHandler(){
@Overridepublic voidhandleMessage(Message msg) {switch(msg.what){casedownloadDone:
Toast.makeText(MyApplication.getApplication(),"同步用户数据成功", Toast.LENGTH_SHORT).show();break;
}super.handleMessage(msg);
}
};//从服务器更新loginer数据
public void downloadData() throwsIOException, XmlPullParserException {new Thread(newRunnable() {
@Overridepublic voidrun() {
String url= "http://222.169.11.226:7000/WebServiceAndroidcm.asmx/getloginerInfo";
MyHTTP myHTTP= newMyHTTP();
Map map= newHashMap();
map.put("pw", "0535deer");try{
String string=myHTTP.doPost(url, map);
System.out.println("成功::::"+string);
String newString= string.replace("<?xml version=\"1.0\" encoding=\"utf-8\"?>{\"Result\":\"1\",\"Value\":", "");
String lastString= newString.replace("}", "");//将字符串进行解析
JsonParser jsonParser = newJsonParser();//将jsonstring转换为jaonArray
JsonArray jsonArray =jsonParser.parse(lastString).getAsJsonArray();//gson
Gson gson = newGson();//for 循环遍历josnarray
for(JsonElement loginerElement : jsonArray) {
Loginer loginer= gson.fromJson(loginerElement, Loginer.class);
loginers.add(loginer);
System.out.println("大小是"+loginers.size());
}//获取dao对象
loginerDao =MyApplication.getApplication().getDaoSession().getLoginerDao();//新建一个Message对象
Message msg = newMessage();//通过for循环插入数据到数据库
for (int i = 0; i < loginers.size(); i++) {
System.out.println("终于找到你:"+loginers.get(i).getLoginer_code());long result =loginerDao.insertOrReplace(loginers.get(i));
System.out.println("结果是:"+result);//如果全部替换或插入成功, 则弹出更新用户数据成功
if (result == loginers.get(loginers.size() - 1).getLoginer_id()) {//发送同步完成的消息到message
msg.what =downloadDone;
downloadLoginerHandler.sendMessage(msg);
System.out.println("到最后一条了");
}
}
}catch(Exception e) {
e.printStackTrace();
}
}
}).start();
}