在Async Task android中解析json时处理可怜的互联网连接

时间:2014-11-26 06:43:14

标签: android

我将从相当长的任务中解决这个问题。我想要做的是我正在对JSON url进行HTTPRESPONSE调用,以解析包含文本和图像的数据。但是当互联网连接很弱时,它只是继续加载进度对话框并最终强制关闭。我该如何应对呢?下面是我的Asynctask和HTTP加载代码片段

MovieFragment.java

private class DownloadJSON extends AsyncTask<Void, Void, Void> {

    @Override
    protected void onPreExecute() {

        super.onPreExecute();
        // Create a progressdialog
        mProgressDialog = new ProgressDialog(getActivity());
        // Set progressdialog title
        mProgressDialog.setTitle("Loading Movies . . ");
        // Set progressdialog message
        mProgressDialog.setMessage("Loading...");
        mProgressDialog.setCancelable(false);
        mProgressDialog.setCanceledOnTouchOutside(false);
        mProgressDialog.setIndeterminate(false);
        // Show progressdialog
        mProgressDialog.show();
    }

    @Override
    protected Void doInBackground(Void... params) {

        // Create an array
        arraylist = new ArrayList<HashMap<String, String>>();
        languagelist = new ArrayList<String>();
        // Retrieve JSON Objects from the given URL address

        try {

            jsonobject = JSONfunctions.getJSONfromURL("MY_WEBSITE/movie_schedule.json");
        } catch (JSONException e1) {

            Toast.makeText(getActivity(),"Error!",5000).show();
            // TODO Auto-generated catch block
            e1.printStackTrace();
        } catch (Exception e) {

            Toast.makeText(getActivity(),"Error!",5000).show();
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        try {

            jsonarray = jsonobject.getJSONArray("Movie_list");
            languagelist.add("Select Language");
            languagelist.add("All");
            for (int i = 0; i < jsonarray.length(); i++) {

                HashMap<String, String> map = new HashMap<String, String>();
                HashMap<String, String> lang = new HashMap<String, String>();
                jsonobject = jsonarray.getJSONObject(i);
                // Retrive JSON Objects
                map.put("releaseYear", jsonobject.getString("releaseYear"));
                map.put("title", jsonobject.getString("title"));
                map.put("rating", jsonobject.getString("rating"));
                map.put("description", jsonobject.getString("description"));
                map.put("image", jsonobject.getString("image"));
                map.put("date", jsonobject.getString("date"));
                map.put("venue", jsonobject.getString("venue"));
                map.put("time", jsonobject.getString("time"));
                map.put("trailer", jsonobject.getString("trailer"));
                map.put("language", jsonobject.getString("language"));
                map.put("trailer", jsonobject.getString("trailer"));
                map.put("type", jsonobject.getString("type"));
                // Set the JSON Objects into the array
                arraylist.add(map);

                if(!languagelist.contains(jsonobject.getString("language"))) {

                    languagelist.add(jsonobject.getString("language"));
                }
            }
        } catch (JSONException e) {

            Log.e("Error", e.getMessage());
            e.printStackTrace();
            Toast.makeText(getActivity(),"Error!",5000).show();
        }
        return null;
    }

    @Override
    protected void onPostExecute(Void args) {

        // Locate the listview in fragment_event.xml
        ArrayAdapter<String> dataAdapter = new ArrayAdapter<String>(getActivity(), R.layout.dropdown_item, languagelist);
        ArrayAdapter<String> dataAdapter1 = new ArrayAdapter<String>(getActivity(), R.layout.dropdown_item, date);
        dataAdapter.setDropDownViewResource(R.layout.selected_item);
        dataAdapter.notifyDataSetChanged();
        s2.setAdapter(dataAdapter);
        s1.setAdapter(dataAdapter1);
        listview = (ListView) getView().findViewById(R.id.listview);
        // Pass the results into ListViewAdapter.java
        adapter = new ListViewAdapter(getActivity(), arraylist);
        // Set the adapter to the ListView
        listview.setAdapter(adapter);
        // Close the progressdialog
        mProgressDialog.dismiss();
    }

    @Override
    public void onCancelled() {

        super.onCancelled();
        mProgressDialog.dismiss();
        Toast toast = Toast.makeText(getActivity(), "Error connecting to Server", Toast.LENGTH_LONG);
        toast.setGravity(Gravity.TOP, 25, 400);
        toast.show();
    }
}

JSONfunctions.java

public class JSONfunctions {

    public static JSONObject getJSONfromURL(String url) throws Exception {

        InputStream is = null;
        String result = "";
        JSONObject jArray = null;
        // Download JSON data from URL
        try {

            //DefaultHttpClient postClient = new DefaultHttpClient(httpParams);
            HttpClient httpclient = new DefaultHttpClient();
            HttpPost httppost = new HttpPost(url);
            HttpResponse response = httpclient.execute(httppost);
            HttpEntity entity = response.getEntity();
            is = entity.getContent();
        } catch (Exception e) {

            Log.e("log_tag", "Error in http connection " + e.toString());
        }

        // Convert response to string
        try {

            BufferedReader reader = new BufferedReader(new InputStreamReader(is, "iso-8859-1"), 8);
            StringBuilder sb = new StringBuilder();
            String line = null;
            while ((line = reader.readLine()) != null) {

                sb.append(line + "\n");
            }
            is.close();
            result = sb.toString();
        } catch (Exception e) {

            Log.e("log_tag", "Error converting result " + e.toString());
        }
        try {

            jArray = new JSONObject(result);
        } catch (JSONException e) {

            Log.e("log_tag", "Error parsing data " + e.toString());
        }
        return jArray;
    }
}

1 个答案:

答案 0 :(得分:2)

我知道这个问题已发布一年了。但我遇到了同样的问题,并认为我应该留下一些东西。

在讨论here时,我已经结束使用以下内容。

public boolean hasInternetAccess(Context context) {
        if (isNetworkAvailable(context)) {
            try {
                HttpURLConnection urlc = (HttpURLConnection)
                        (new URL("http://clients3.google.com/generate_204")
                                .openConnection());
                urlc.setRequestProperty("User-Agent", "Android");
                urlc.setRequestProperty("Connection", "close");
                urlc.setConnectTimeout(1500);
                urlc.connect();
                return (urlc.getResponseCode() == 204 &&
                        urlc.getContentLength() == 0);
            } catch (IOException e) {
                Log.e("LOGGER", "Error checking internet connection", e);
            }
        } else {
            Log.d("LOGGER", "No network available!");
        }
        return false;
    }

使用以下方法检查互联网连接:

private static boolean isNetworkAvailable(Context context) {
        ConnectivityManager connectivityManager
                = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
        NetworkInfo activeNetworkInfo = connectivityManager.getActiveNetworkInfo();
        return activeNetworkInfo != null;
    }

应该从AsyncTask或与UI线程不同的线程调用该方法。

在AsyncTask中可能如下所示:

protected String doInBackground(String... args) {
        isConnected = hasInternetAccess(mContext);
        return null;
    }