有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

如果网络可用,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();
                    }
                }
            }
        }
    }

共 (3) 个答案

  1. # 1 楼答案

    您也可以添加此支票

    public static boolean isNetworkAvailable(Context con) {
            try {
                ConnectivityManager cm = (ConnectivityManager) con
                        .getSystemService(Context.CONNECTIVITY_SERVICE);
                NetworkInfo networkInfo = cm.getActiveNetworkInfo();
    
                if (networkInfo != null && networkInfo.isConnected()) {
                    return true;
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
            return false;
        }
    

    然后在你的活动/片段中检查这个

    if (isNetworkAvailable)
    {
    //Do you task
    //callAPI(); fetch data from website / api call
    }
    else{
    /*No internet so, load from memory */
    }
    
  2. # 2 楼答案

    您可以通过以下代码检查您的移动设备是否连接到互联网

    public class ConnectionDetector
    {
    private Context _context;
    public ConnectionDetector(Context context)
    {
        this._context = context;
    }
    public  boolean isConnectingToInternet()
    {
        ConnectivityManager connectivity = (ConnectivityManager) _context.getSystemService(Context.CONNECTIVITY_SERVICE);
        if (connectivity != null)
        {
            NetworkInfo info = connectivity.getActiveNetworkInfo();
            if (info != null)
            {
                if (info.getType() == ConnectivityManager.TYPE_WIFI)
                {
                    return true;
                }
                else if (info.getType() == ConnectivityManager.TYPE_MOBILE)
                {
                    return true;
                }
            }
            else
            {
                // not connected to the internet
                return false;
            }
        }
        return false;
    }}
    

    您的AsyncTask类代码类似于下面的代码

    private class AsyncTaskGetMareker extends AsyncTask<String , String, JSONArray> 
     {
    @Override
    protected void onPreExecute() {
        super.onPreExecute();
    }
    
    @Override
    protected JSONArray doInBackground(String... strings) {
         JSONArray stationsJsonArray;
        String stationsJsonString = getJSONFromAssets(MainActivity.this);
        try {
             if(new ConnectionDetector().isConnectionToInternet())
             {
                Hashmap<String,String> mapToSend = new Hashmap();
             JSONParser jsonParser = new JSONParser();
    
              stationsJsonArray = jsonParser.makeHttpRequest("URL", "POST", mapToSend);
    
             }else{
               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();
                }
            }
        }
    }
    

    }

  3. # 3 楼答案

    下面是JSONParser类

    import android.util.Log;
    
    import org.json.JSONException;
    import org.json.JSONObject;
    
     import java.io.BufferedInputStream;
     import java.io.BufferedReader;
     import java.io.DataOutputStream;
     import java.io.IOException;
     import java.io.InputStream;
     import java.io.InputStreamReader;
     import java.io.UnsupportedEncodingException;
     import java.net.HttpURLConnection;
     import java.net.URL;
     import java.net.URLEncoder;
     import java.util.HashMap;
    
     public class JSONParser {
    
    String charset = "UTF-8";
    HttpURLConnection conn;
    DataOutputStream wr;
    StringBuilder result;
    URL urlObj;
    JSONObject jObj = null;
    StringBuilder sbParams;
    String paramsString;
    
    public JSONObject makeHttpRequest(String url, String method,
                                      HashMap<String, String> params) {
    
        sbParams = new StringBuilder();
        int i = 0;
        for (String key : params.keySet()) {
            try {
                if (i != 0){
                    sbParams.append("&");
                }
                sbParams.append(key).append("=")
                        .append(URLEncoder.encode(params.get(key), charset));
    
            } catch (UnsupportedEncodingException e) {
                e.printStackTrace();
            }
            i++;
        }
    
        if (method.equals("POST")) {
            // request method is POST
            try {
                urlObj = new URL(url);
    
                conn = (HttpURLConnection) urlObj.openConnection();
    
                conn.setDoOutput(true);
    
                conn.setRequestMethod("POST");
    
                conn.setRequestProperty("Accept-Charset", charset);
    
                conn.setReadTimeout(10000);
                conn.setConnectTimeout(15000);
    
                conn.connect();
    
                paramsString = sbParams.toString();
    
                wr = new DataOutputStream(conn.getOutputStream());
                wr.writeBytes(paramsString);
                wr.flush();
                wr.close();
    
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        else if(method.equals("GET")){
            // request method is GET
    
            if (sbParams.length() != 0) {
                url += "?" + sbParams.toString();
            }
    
            try {
                urlObj = new URL(url);
    
                conn = (HttpURLConnection) urlObj.openConnection();
    
                conn.setDoOutput(false);
    
                conn.setRequestMethod("GET");
    
                conn.setRequestProperty("Accept-Charset", charset);
    
                conn.setConnectTimeout(15000);
    
                conn.connect();
    
            } catch (IOException e) {
                e.printStackTrace();
            }
    
        }
    
        try {
            //Receive the response from the server
            InputStream in = new BufferedInputStream(conn.getInputStream());
            BufferedReader reader = new BufferedReader(new InputStreamReader(in));
            result = new StringBuilder();
            String line;
            while ((line = reader.readLine()) != null) {
                result.append(line);
            }
    
            Log.d("JSON Parser", "result: " + result.toString());
    
        } catch (IOException e) {
            e.printStackTrace();
        }
    
        conn.disconnect();
    
        // try parse the string to a JSON object
        try {
            jObj = new JSONObject(result.toString());
        } catch (JSONException e) {
            Log.e("JSON Parser", "Error parsing data " + e.toString());
        }
    
        // return JSON Object
        return jObj;
    }}