Android - 如果在获取 JSON 数据时没有网络连接,则会发生 App Force Close

标签 android json

我正在使用异步任务在后台从网络中获取 json 数据。这很好用,但是当没有网络连接时应用程序强制关闭。

代码如下:

public class MainActivity extends Activity {

    public static final int DIALOG_DOWNLOAD_JSON_PROGRESS = 0;
    public static final int DIALOG_DOWNLOAD_FULL_PHOTO_PROGRESS = 1;
    private ProgressDialog mProgressDialog;

    ArrayList<HashMap<String, Object>> MyArrList;


    @SuppressLint("NewApi")
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        // Permission StrictMode
        if (android.os.Build.VERSION.SDK_INT > 9) {
            StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitAll().build();
            StrictMode.setThreadPolicy(policy);
        }

        // Download JSON File   
        new DownloadJSONFileAsync().execute();

    }


    @Override
    protected Dialog onCreateDialog(int id) {
        switch (id) {
        case DIALOG_DOWNLOAD_JSON_PROGRESS:
            mProgressDialog = new ProgressDialog(this);
            mProgressDialog.setMessage("Downloading.....");
            mProgressDialog.setProgressStyle(ProgressDialog.STYLE_SPINNER);
            mProgressDialog.setCancelable(true);
            mProgressDialog.show();
            return mProgressDialog;
        case DIALOG_DOWNLOAD_FULL_PHOTO_PROGRESS:
            mProgressDialog = new ProgressDialog(this);
            mProgressDialog.setMessage("Downloading.....");
            mProgressDialog.setProgressStyle(ProgressDialog.STYLE_SPINNER);
            mProgressDialog.setCancelable(true);
            mProgressDialog.show();
            return mProgressDialog; 
        default:
            return null;
        }
    }

    // Show All Content
    public void ShowAllContent()
    {
        // listView1
        final ListView lstView1 = (ListView)findViewById(R.id.listView1); 
        lstView1.setAdapter(new ImageAdapter(MainActivity.this,MyArrList));

        // OnClick
        lstView1.setOnItemClickListener(new OnItemClickListener() {
            public void onItemClick(AdapterView<?> parent, View v,
                int position, long id) {
                String strImageName = MyArrList.get(position).get("ImageName").toString();
                String strImagePathFull = MyArrList.get(position).get("ImagePathFull").toString();

                new DownloadFullPhotoFileAsync().execute(strImageName,strImagePathFull); // Download file Full Photo
            }
        });
    }

    // Show Dialog Popup 
    public void showDialogPopup(String strImageName,Bitmap ImageFullPhoto)
    {

        final AlertDialog.Builder imageDialog = new AlertDialog.Builder(this);
        final LayoutInflater inflater = (LayoutInflater) this.getSystemService(LAYOUT_INFLATER_SERVICE);


          View layout = inflater.inflate(R.layout.custom_fullimage_dialog,
                  (ViewGroup) findViewById(R.id.layout_root));
          ImageView image = (ImageView) layout.findViewById(R.id.fullimage);

             try
             {
                image.setImageBitmap(ImageFullPhoto);
             } catch (Exception e) {
                 // When Error
                image.setImageResource(android.R.drawable.ic_menu_report_image);
             }

          imageDialog.setIcon(android.R.drawable.btn_star_big_on);  
          imageDialog.setTitle("View : " + strImageName);
          imageDialog.setView(layout);
          imageDialog.setPositiveButton(android.R.string.ok, new DialogInterface.OnClickListener(){

              public void onClick(DialogInterface dialog, int which) {
                  dialog.dismiss();
              }

          });

          imageDialog.create();
          imageDialog.show(); 

    }


    public class ImageAdapter extends BaseAdapter 
    {
        private Context context;
        private ArrayList<HashMap<String, Object>> MyArr = new ArrayList<HashMap<String, Object>>();

        public ImageAdapter(Context c, ArrayList<HashMap<String, Object>> myArrList) 
        {
            // TODO Auto-generated method stub
            context = c;
            MyArr = myArrList;
        }

        public int getCount() {
            // TODO Auto-generated method stub
            return MyArr.size();
        }

        public Object getItem(int position) {
            // TODO Auto-generated method stub
            return position;
        }

        public long getItemId(int position) {
            // TODO Auto-generated method stub
            return position;
        }
        public View getView(int position, View convertView, ViewGroup parent) {
            // TODO Auto-generated method stub

            LayoutInflater inflater = (LayoutInflater) context
                    .getSystemService(Context.LAYOUT_INFLATER_SERVICE);


            if (convertView == null) {
                convertView = inflater.inflate(R.layout.activity_column, null); 
            }

            // ColImage
            ImageView imageView = (ImageView) convertView.findViewById(R.id.ColImgPath);
            imageView.getLayoutParams().height = 80;
            imageView.getLayoutParams().width = 80;
            imageView.setPadding(5, 5, 5, 5);
            imageView.setScaleType(ImageView.ScaleType.CENTER_CROP);
             try
             {
                 imageView.setImageBitmap((Bitmap)MyArr.get(position).get("ImageThumBitmap"));
             } catch (Exception e) {
                 // When Error
                 imageView.setImageResource(android.R.drawable.ic_menu_report_image);
             }

            // ColImgID
            TextView txtImgID = (TextView) convertView.findViewById(R.id.ColImgID);
            txtImgID.setPadding(10, 0, 0, 0);
            txtImgID.setText("ID : " + MyArr.get(position).get("ImageID").toString());

            // ColImgName
            TextView txtPicName = (TextView) convertView.findViewById(R.id.ColImgName);
            txtPicName.setPadding(50, 0, 0, 0);
            txtPicName.setText("Name : " + MyArr.get(position).get("ImageName").toString());    

            return convertView;

        }

    } 



    // Download JSON in Background
    public class DownloadJSONFileAsync extends AsyncTask<String, Void, Void> {

        protected void onPreExecute() {
            super.onPreExecute();
            showDialog(DIALOG_DOWNLOAD_JSON_PROGRESS);
        }

        @Override
        protected Void doInBackground(String... params) {       
            String url = "http://XXX.com.xxp";

            JSONArray data;
            try {
                data = new JSONArray(getJSONUrl(url));

                MyArrList = new ArrayList<HashMap<String, Object>>();
                HashMap<String, Object> map;

                for(int i = 0; i < data.length(); i++){
                    JSONObject c = data.getJSONObject(i);
                    map = new HashMap<String, Object>();
                    map.put("ImageID", (String)c.getString("ImageID"));
                    map.put("ImageName", (String)c.getString("ImageName"));

                    // Thumbnail Get ImageBitmap To Object
                    map.put("ImagePathThum", (String)c.getString("ImagePath_Thumbnail"));
                    map.put("ImageThumBitmap", (Bitmap)loadBitmap(c.getString("ImagePath_Thumbnail")));

                    // Full (for View Popup)
                    map.put("ImagePathFull", (String)c.getString("ImagePath_FullPhoto"));

                    MyArrList.add(map);
                }


            } catch (JSONException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }

            return null;
        }

        protected void onPostExecute(Void unused) {
            ShowAllContent(); // When Finish Show Content
            dismissDialog(DIALOG_DOWNLOAD_JSON_PROGRESS);
            removeDialog(DIALOG_DOWNLOAD_JSON_PROGRESS);
        }


    }

    // Download Full Photo in Background
    public class DownloadFullPhotoFileAsync extends AsyncTask<String, Void, Void> {

        String strImageName = "";
        String ImageFullPhoto = "";

        Bitmap ImageFullBitmap = null;

        protected void onPreExecute() {
            super.onPreExecute();
            showDialog(DIALOG_DOWNLOAD_FULL_PHOTO_PROGRESS);
        }

        @Override
        protected Void doInBackground(String... params) {
            strImageName = params[0];
            ImageFullPhoto = params[1];

            ImageFullBitmap = (Bitmap)loadBitmap(ImageFullPhoto);
            return null;
        }

        protected void onPostExecute(Void unused) {
            showDialogPopup(strImageName,ImageFullBitmap); // When Finish Show Popup
            dismissDialog(DIALOG_DOWNLOAD_FULL_PHOTO_PROGRESS);
            removeDialog(DIALOG_DOWNLOAD_FULL_PHOTO_PROGRESS);
        }


    }


    /*** Get JSON Code from URL ***/
    public String getJSONUrl(String url) {
        StringBuilder str = new StringBuilder();
        HttpClient client = new DefaultHttpClient();
        HttpGet httpGet = new HttpGet(url);
        try {
            HttpResponse response = client.execute(httpGet);
            StatusLine statusLine = response.getStatusLine();
            int statusCode = statusLine.getStatusCode();
            if (statusCode == 200) { // Download OK
                HttpEntity entity = response.getEntity();
                InputStream content = entity.getContent();
                BufferedReader reader = new BufferedReader(new InputStreamReader(content));
                String line;
                while ((line = reader.readLine()) != null) {
                    str.append(line);
                }
            } else {
                Log.e("Log", "Failed to download file..");
            }
        } catch (ClientProtocolException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return str.toString();
    }


    /***** Get Image Resource from URL (Start) *****/
    private static final String TAG = "Image";
    private static final int IO_BUFFER_SIZE = 4 * 1024;
    public static Bitmap loadBitmap(String url) {
        Bitmap bitmap = null;
        InputStream in = null;
        BufferedOutputStream out = null;

        try {
            in = new BufferedInputStream(new URL(url).openStream(), IO_BUFFER_SIZE);

            final ByteArrayOutputStream dataStream = new ByteArrayOutputStream();
            out = new BufferedOutputStream(dataStream, IO_BUFFER_SIZE);
            copy(in, out);
            out.flush();

            final byte[] data = dataStream.toByteArray();
            BitmapFactory.Options options = new BitmapFactory.Options();
            //options.inSampleSize = 1;

            bitmap = BitmapFactory.decodeByteArray(data, 0, data.length,options);
        } catch (IOException e) {
            Log.e(TAG, "Could not load Bitmap from: " + url);
        } finally {
            closeStream(in);
            closeStream(out);
        }

        return bitmap;
    }

     private static void closeStream(Closeable stream) {
            if (stream != null) {
                try {
                    stream.close();
                } catch (IOException e) {
                    android.util.Log.e(TAG, "Could not close stream", e);
                }
            }
        }

     private static void copy(InputStream in, OutputStream out) throws IOException {
        byte[] b = new byte[IO_BUFFER_SIZE];
        int read;
        while ((read = in.read(b)) != -1) {
            out.write(b, 0, read);
        }
    }
     /***** Get Image Resource from URL (End) *****/

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        getMenuInflater().inflate(R.menu.activity_main, menu);
        return true;
    }

}

最佳答案

您可以在从服务器获取数据之前检查网络连接。我总是这样做:

private void getDataFromInternet() {

    if(InternetConnection.isConnectedToInternet(CurrentActivity.this))
        new MyAsyncTask().execute();
}

在我的接收器类中,我实现了该方法:

public static boolean isConnectedToInternet(Context context) {
        Log.i(TAG, "Checking Internet Connection...");

        boolean found = false;

        try {
            ConnectivityManager cm = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
            NetworkInfo netInfo = cm.getActiveNetworkInfo();
            if (netInfo != null && netInfo.isConnectedOrConnecting()) {             
                found = true;
                internetStatus = 0;
            }

            android.net.NetworkInfo wifi = cm.getNetworkInfo(ConnectivityManager.TYPE_WIFI);
            android.net.NetworkInfo _3g  = cm.getNetworkInfo(ConnectivityManager.TYPE_MOBILE);
            if (wifi.isConnected())
                internetType = "WiFi";

            if (_3g.isConnected()) 
                internetType = "3G";

        } catch (Exception e) {
            Log.e("CheckConnectivity Exception", e.getMessage(), e);
        }

        if(found)
            Log.i(TAG, "Internet Connection found.");
        else
            Log.i(TAG, "Internet Connection not found.");

        return found;
    } 

因此,您始终了解网络连接。

关于Android - 如果在获取 JSON 数据时没有网络连接,则会发生 App Force Close,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12310605/

相关文章:

java - Android 中的 ACTION_TIME_TICK 问题

python - 在 python 中循环遍历 JSON 数组进行比较?

MySQL在数组中按键搜索json值

PHP pdo foreach

android - 如何绘制局部位图圆弧?就像一个圆形进度轮,但带有越来越多显示的位图。

android - Activity Fence 在 Awareness API 中不起作用

java - 在运行时动态输入类文字作为方法参数

python - 如何在 json 格式的字符串中使用 str.format?

java - 如何简化尴尬的并发代码?

Android WebView 内容显示问题