【问题标题】:How implement ConnectionException -Android如何实现 ConnectionException -Android
【发布时间】:2013-03-24 11:47:45
【问题描述】:

我正在与 php mysql travez 中的数据库通信以在 ListView 中显示结果,但我正在尝试在 3G 或 WIFI 但应用程序无法连接时实现 ExeptionConnection,返回到以前的 Activity 并显示 Toast。但不是如何在我的代码中实现它,我只能实现 JsonExeption。 这是我的代码:

protected String doInBackground(String... args) {



        List<NameValuePair> params = new ArrayList<NameValuePair>();

        JSONObject json = jParser.makeHttpRequest(url_list_rs, "GET",
                params);



        Log.d("All Products: ", json.toString());

        try {


            int success = json.getInt(TAG_SUCCESS);

            if (success == 1) {

                daftar_rs = json.getJSONArray(TAG_DAFTAR_RS);
                for (int i = 0; i < list_rs.length(); i++) {
                    JSONObject c = list_rs.getJSONObject(i);

        //Process Code
                }
            } else { 

            }
        } catch (JSONException e) {
            e.printStackTrace();
        }

        return null;

    }

其中 url_list_rs 是我的 php 的 url。我可以在哪里实施 ExeptionConnection?任何人都可以帮忙吗?感谢大师!

【问题讨论】:

    标签: android json return connectionexception


    【解决方案1】:

    如果你想创建自己的异常,你可以这样做:

    //create a new Exception class    
    public class ConnectionException extends Exception {
        public ConnectionException(String message){
             super(message);
        }
    }
    

    在你的 makeHttpRequest 方法中

    if(no connection) { //check connection
        throw new ConnectionException ("No connection!");
    } else { ... }
    

    最后,try-catch 块

    try {
        JSONObject json = jParser.makeHttpRequest(url_list_rs, "GET",
                params);
    catch(ConnectionException ex) {
        ex.printStackTrace();
    }
    

    注意:我不确定这是否是最佳做法。

    【讨论】:

      猜你喜欢
      • 2017-05-02
      • 1970-01-01
      • 2016-09-22
      • 2019-12-18
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-11-17
      相关资源
      最近更新 更多