使用try和catch显示AlertDialog

时间:2018-01-24 04:38:35

标签: java android android-studio try-catch

我想检查我何时连接到服务器并执行此操作,我使用的是我在互联网上找到的代码,我不知道如何实现它,如何显示警告对话框或任何类型的警告当我没有连接。任何帮助,将不胜感激!

CODE:

public boolean isConnectedToServer(String url, int timeout) {
    try {
        URL myUrl = new URL(url);
        URLConnection connection = myUrl.openConnection();
        connection.setConnectTimeout(timeout);
        connection.connect();
        return true;
    } catch (Exception e) {
        // Handle your exceptions
        return false;
    }
}

logcat的:

FATAL EXCEPTION: main
                                                                                    Process: com.example.lupitagarcia.yosoyvallarta, PID: 11573
                                                                                    java.lang.NullPointerException: Attempt to invoke virtual method 'int java.util.ArrayList.size()' on a null object reference
                                                                                        at com.example.lupitagarcia.yosoyvallarta.Reportes.onMapReady(Reportes.java:195)
                                                                                        at com.google.android.gms.maps.MapView$zza$1.zza(Unknown Source)
                                                                                        at com.google.android.gms.maps.internal.zzt$zza.onTransact(Unknown Source)
                                                                                        at android.os.Binder.transact(Binder.java:387)
                                                                                        at er.b(:com.google.android.gms.DynamiteModulesB@11951434:20)
                                                                                        at com.google.android.gms.maps.internal.bf.a(:com.google.android.gms.DynamiteModulesB@11951434:5)
                                                                                        at com.google.maps.api.android.lib6.impl.bc.run(:com.google.android.gms.DynamiteModulesB@11951434:5)
                                                                                        at android.os.Handler.handleCallback(Handler.java:739)
                                                                                        at android.os.Handler.dispatchMessage(Handler.java:95)
                                                                                        at android.os.Looper.loop(Looper.java:148)
                                                                                        at android.app.ActivityThread.main(ActivityThread.java:7406)
                                                                                        at java.lang.reflect.Method.invoke(Native Method)
                                                                                        at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1230)
                                                                                        at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1120)

这是使用PHP从db中检索信息的代码,这里也是catlog发送给我的地方 代码:

       ArrayList<HashMap<String, String>> location = null;
        String url = "http://app/get.php";
        try {

            JSONArray data = new JSONArray(getHttpGet(url));
            location = new ArrayList<HashMap<String, String>>();
            HashMap<String, String> map;

            for (int i = 0; i < data.length(); i++) {
                JSONObject c = data.getJSONObject(i);
                map = new HashMap<String, String>();
                map.put("id", c.getString("id"));
                map.put("campo_latitud", c.getString("campo_latitud"));
                map.put("campo_longitud", c.getString("campo_longitud"));
                map.put("campo_categoria", c.getString("campo_categoria"));
                map.put("campo_estado", c.getString("campo_estado"));
                location.add(map);
            }
        } catch (JSONException e) {

            e.printStackTrace();
        }

        String campouno = "";
        if (!TextUtils.isEmpty(campouno)) {
            double campo_latitud = Double.parseDouble(campouno);
        }
   String campodos = "";
        if (!TextUtils.isEmpty(campodos)) {
            double campo_longitud = Double.parseDouble(campodos);
        }

            for (int i = 0; i < location.size(); i++) {
                if (!TextUtils.isEmpty(location.get(i).get("campo_latitud").toString()) && !TextUtils.isEmpty(location.get(i).get("campo_longitud").toString())) {
                    campo_latitud = Double.parseDouble(location.get(i).get("campo_latitud").toString());
                    campo_longitud = Double.parseDouble(location.get(i).get("campo_longitud").toString());
                }

2 个答案:

答案 0 :(得分:3)

试试这个:

if (isConnectedToServer("http://yourserver.com", 60)) {
   new AlertDialog.Builder(this)
      .setTitle("Connected")
      .setMessage("You are connected to server")
      .create().show();
} else {
   new AlertDialog.Builder(this)
      .setTitle("Not Connected")
      .setMessage("You are not connected to server")
      .create().show();
}

<强>更新

    ArrayList<HashMap<String, String>> location = new ArrayList<HashMap<String, String>>(); //do your instance creation here to avoid nullpointer if your try-catch go to catch.
    String url = "http://app/get.php";
    try {

        JSONArray data = new JSONArray(getHttpGet(url));

答案 1 :(得分:1)

boolean isConnected = isConnectedToServer("Your server", 10);

if(isConnected){
                    new AlertDialog.Builder(this)
                    .setMessage("You are Successfully Connected"
                            + getString(R.string.app_name))
                    .setPositiveButton("OK",
                         new DialogInterface.OnClickListener()
                            {
                                @Override
                                public void onClick(DialogInterface 
                                             dialog, int which) {
                                    dialog.dismiss();
                                }
                            }).show();
}
else{
                    new AlertDialog.Builder(this)
                    .setMessage("Something Went Wrong!!"
                            + getString(R.string.app_name))
                    .setPositiveButton("OK",
                            new DialogInterface.OnClickListener()
                            {
                                @Override
                                public void onClick(DialogInterface 
                                            dialog, int which) {
                                    dialog.dismiss();
                                }
                            }).show();
}