如果网络可用,java从服务器获取JSON
如何从互联网上加载变量为负值的文件,以及从手机上加载变量为正值的文件
它应该是这样工作的:
我的系统检查是否有互联网
如果不是,则从内存加载
如果有,请从站点url加载
public String getJSONFromAssets(Context context) {
String json = null;
try {
InputStream inputData = context.getAssets().open("data.json"); //load assets file
//Log.e("100rad", ":"+inputData);
int size = inputData.available();
byte[] buffer = new byte[size];
inputData.read(buffer);
inputData.close();
json = new String(buffer, "UTF-8");
} catch (IOException ex) {
ex.printStackTrace();
return null;
}
return json;
}
private class AsyncTaskGetMareker extends AsyncTask<String , String, JSONArray> {
@Override
protected void onPreExecute() {
super.onPreExecute();
}
@Override
protected JSONArray doInBackground(String... strings) {
String stationsJsonString = getJSONFromAssets(MainActivity.this);
try {
JSONArray stationsJsonArray = new JSONArray(stationsJsonString);
return stationsJsonArray;
} catch (JSONException e) {
e.printStackTrace();
}
//This will only happen if an exception is thrown above:
return null;
}
protected void onPostExecute (JSONArray result){
if (result !=null){
for (int i =0; i <result.length(); i++){
JSONObject jsonObject= null;
try {
jsonObject= result.getJSONObject(i);
String name=jsonObject.getString("store_name");
String lat=jsonObject.getString("latitude");
String lang=jsonObject.getString("longitude");
String desc=jsonObject.getString("store_desc");
String oxr=jsonObject.getString("telephone");
String sost=jsonObject.getString("keywords");
int cat=jsonObject.getInt("category_id");
int id=jsonObject.getInt("id");
} catch (JSONException e) {
e.printStackTrace();
}
}
}
}
}
# 1 楼答案
您也可以添加此支票
然后在你的活动/片段中检查这个
# 2 楼答案
您可以通过以下代码检查您的移动设备是否连接到互联网
您的AsyncTask类代码类似于下面的代码
}
# 3 楼答案
下面是JSONParser类