【问题标题】:Handle Exception with error dialog in asynctask在异步任务中处理带有错误对话框的异常
【发布时间】:2015-10-22 12:49:20
【问题描述】:

我正在制作一个带有拉重加载功能的 RSS 安卓应用。我想使用 AsyncTask。这是我的代码:

class Refresh extends AsyncTask<String,Void,Void>{

    @Override
    protected Void doInBackground(String... params) {
        try {
            Download(getResources().getString(R.string.link));
        }catch (Exception e){
            createNetErrorDialog();

        }
        return null;
    }

    @Override
    protected void onPostExecute(Void aVoid) {
        super.onPostExecute(aVoid);
        try{
            views();
        }catch (Exception e){
            Toast.makeText(MainActivity.this,
                    "Error",
                    Toast.LENGTH_LONG).show();
            cancel(true);
        }

        lstPost.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position,
                                    long id) {
                Intent intent = new Intent(MainActivity.this, WebviewActivity.class);
                Bundle bundle = new Bundle();

                Document xmlFeed = rssfeed
                        .getRSSFromServer(getResources().getString(R.string.link));
                NodeList nodes = xmlFeed.getElementsByTagName(getResources().getString(R.string.item));
                Element item = (Element) nodes.item(position);
                String summary = rssfeed.getValue(item, key_summary);
                String title = rssfeed.getValue(item, key_title);
                bundle.putString(getResources().getString(R.string.tag_summary), summary);
                bundle.putString(getResources().getString(R.string.tag_title), title);
                intent.putExtras(bundle);
                startActivity(intent);
            }
        });
    }
}




void Download(String url) throws Exception{
    lists.clear();

        Document xmlFeed = rssfeed.getRSSFromServer(url);
        NodeList nodes = xmlFeed.getElementsByTagName("entry");
        for (int i = 0; i < nodes.getLength(); i++) {
            Element item = (Element) nodes.item(i);
            HashMap<String, Object> feed = new HashMap<String, Object>();
            feed.put(key_title, rssfeed.getValue(item, key_title));
            feed.put(key_summary, rssfeed.getValue(item, key_summary));
            feed.put(key_link, rssfeed.getValue(item, key_link));
            //feed.put(key_date, rssfeed.getValue(item, key_date));
            post_lists.add(feed);
            lists.add(feed.get(key_title).toString());
        }

}


void views(){
    lstPost = (ListView) findViewById(R.id.lstPosts);

    adapter = new ArrayAdapter<String>(this,
            android.R.layout.simple_list_item_2, android.R.id.text1, lists) {

        @Override
        public View getView(int position, View convertView, ViewGroup parent) {
            View view = super.getView(position, convertView, parent);
            TextView txt1 = (TextView) view
                    .findViewById(android.R.id.text1);
            TextView txt2 = (TextView) view
                    .findViewById(android.R.id.text2);
            HashMap<String, Object> data = post_lists.get(position);
            txt1.setText(Html.fromHtml(data.get(key_title).toString()));

            if (data.get(key_summary).toString().length() > 125) {

                txt2.setText(Html.fromHtml((data.get(key_summary).toString()).substring(0, 125) + "..."));
            } else {

                txt2.setText(Html.fromHtml(data.get(key_summary).toString()));
            }
            return view;
        }

    };

    TextView dateview=(TextView) findViewById(R.id.date);
    Calendar rightNow = Calendar.getInstance();
    DateFormat formatter = new SimpleDateFormat(getResources().getString(R.string.date_format));

    dateview.setText(getResources().getString(R.string.lastupdate) + formatter.format(rightNow.getTime()));
    lstPost.setAdapter(adapter);
}


protected void createNetErrorDialog() {

    AlertDialog.Builder builder = new AlertDialog.Builder(this);
    builder.setMessage(getResources().getString(R.string.errorbox))
            .setTitle("Unable to connect")
            .setCancelable(false)
            .setPositiveButton("Settings",
                    new DialogInterface.OnClickListener() {
                        public void onClick(DialogInterface dialog, int id) {
                            Intent i = new Intent(Settings.ACTION_WIRELESS_SETTINGS);
                            startActivity(i);
                        }
                    }
            )
            .setNeutralButton("Refresh",
                    new DialogInterface.OnClickListener() {
                        public void onClick(DialogInterface dialog, int id) {
                            new Refresh().execute(getResources().getString(R.string.link));
                        }
                    })
            .setNegativeButton("Cancel",
                    new DialogInterface.OnClickListener() {
                        public void onClick(DialogInterface dialog, int id) {
                            finish();
                        }
                    }
            );
    AlertDialog alert = builder.create();
    alert.show();
}

问题:如果我关闭网络连接,应用程序会退出而不是显示 createNetErrorDialog()。有人能帮帮我吗?

【问题讨论】:

  • 你知道createNetErrorDialog()是否真的被调用了?我不认为你可以在doInBackground() 中显示对话框。你也可以检查你的logcat。您很可能会在那里打印出异常。

标签: java android exception android-asynctask


【解决方案1】:

使用以下方法检查网络是否打开:

 public static boolean isDeviceOnline(Context context) {

    ConnectivityManager connMgr = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
    NetworkInfo networkInfo = connMgr.getActiveNetworkInfo();
    boolean isOnline = (networkInfo != null && networkInfo.isConnected());
    if(!isOnline)
        Toast.makeText(context, " No internet Connection ", Toast.LENGTH_SHORT).show();

    return isOnline;
}

当您需要检查设备是否在线时调用它:

if(isDeviceOnline(context))
{
//call Refresh
}
else
{
//whatever you want
}

我认为异常处理不是一个好习惯。

【讨论】:

  • 谢谢。我现在就试试这个。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2011-04-11
  • 1970-01-01
  • 1970-01-01
  • 2013-04-17
  • 2012-02-07
  • 1970-01-01
  • 2013-02-13
相关资源
最近更新 更多