从另一个班级调用Internet Detect无效

时间:2013-12-12 13:47:33

标签: java android

我正在制作Internet Detector类,所以当互联网关闭时,它会显示一个带有两个选项的Dialog,一个是退出应用程序,另一个是刷新检查互联网的空白。单击刷新时app force关闭。看看代码。

片段类

public void check(){
    DetectConnection dc = new DetectConnection(getActivity());
    if(dc.isConnectedToInternet()==true) {
        String url = "...";
        new DownloadFilesTask().execute(url);
    } else {
        FragmentManager ft = getActivity().getFragmentManager();
        MyAlertDialogWIndow alert = new MyAlertDialogWIndow();
        alert.show(ft, "Alert");
    }
}

MyAlertDialogWIndow类

public class MyAlertDialogWIndow extends DialogFragment {

    Fragment2 fragment2 = new Fragment2();
    DetectConnection detectConnection;
    @Override
    public Dialog onCreateDialog(Bundle savedInstanceState) {
        OnClickListener positiveClick = new OnClickListener() {  
            @Override
            public void onClick(DialogInterface dialog, int which) {   

            fragment2.check();
        }
    };
}

   OnClickListener negativeClick = new OnClickListener() {  
  @Override
 public void onClick(DialogInterface dialog, int which) {


 }
 };

 AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());
 builder.setMessage("Device is not connected to the internet. Check your connection and click refresh");
 builder.setNegativeButton("Exit", negativeClick);
 builder.setPositiveButton("Refresh", positiveClick);
 builder.setTitle("No Connection");
 Dialog dialog = builder.create();
 return dialog;
   }

DetectConnecion类

public class DetectConnection {

private Context _context;

public DetectConnection(Context context){
    this._context = context;
}

public boolean isConnectedToInternet(){
           ConnectivityManager connectivity = (ConnectivityManager)                                           _context.getSystemService(Context.CONNECTIVITY_SERVICE);
      if (connectivity != null)
      {
          NetworkInfo[] info = connectivity.getAllNetworkInfo();
          if (info != null)
              for (int i = 0; i < info.length; i++)
                  if (info[i].getState() == NetworkInfo.State.CONNECTED)
                  {
                      return true;
                  }

      }
      return false;
}
}

错误

com.example.example.DetectConnection.isConnectedToInternet(DetectConnection.java:16)

public class MyAlertDialogWIndow extends DialogFragment

.Fragment2.check(Fragment2.java:93) if(dc.isConnectedToInternet()==true)

完整的logcat

 12-12 14:48:31.445: W/dalvikvm(3211): threadid=1: thread exiting with uncaught    exception
 12-12 14:48:31.450: E/AndroidRuntime(3211): FATAL EXCEPTION: main
 12-12 14:48:31.450: E/AndroidRuntime(3211): java.lang.NullPointerException
 12-12 14:48:31.450: E/AndroidRuntime(3211):at                                                              com.example.example.DetectConnection.isConnectedToInternet(DetectConnection.java:16)
 12-12 14:48:31.450: E/AndroidRuntime(3211):    at com.example.example.Fragment2.check(Fragment2.java:93)
 12-12 14:48:31.450: E/AndroidRuntime(3211):    at com.example.example.MyAlertDialogWIndow$1.onClick(MyAlertDialogWIndow.java:27)
 12-12 14:48:31.450: E/AndroidRuntime(3211):    at com.android.internal.app.AlertController$ButtonHandler.handleMessage(AlertController.java:167)
 12-12 14:48:31.450: E/AndroidRuntime(3211):    at android.os.Handler.dispatchMessage(Handler.java:99)
 12-12 14:48:31.450: E/AndroidRuntime(3211):    at android.os.Looper.loop(Looper.java:137)
 12-12 14:48:31.450: E/AndroidRuntime(3211):    at android.app.ActivityThread.main(ActivityThread.java:4898)
 12-12 14:48:31.450: E/AndroidRuntime(3211):    at java.lang.reflect.Method.invokeNative(Native Method)
 12-12 14:48:31.450: E/AndroidRuntime(3211):    at java.lang.reflect.Method.invoke(Method.java:511)
 12-12 14:48:31.450: E/AndroidRuntime(3211):    at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1006)
 12-12 14:48:31.450: E/AndroidRuntime(3211):    at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:773)
 12-12 14:48:31.450: E/AndroidRuntime(3211):    at dalvik.system.NativeStart.main(Native Method)

3 个答案:

答案 0 :(得分:1)

您确定getActivity()不会返回null吗?这里:

DetectConnection dc = new DetectConnection(getActivity());

我认为这是因为上下文(即活动是null):

ConnectivityManager connectivity = 
   (ConnectivityManager) _context.getSystemService(Context.CONNECTIVITY_SERVICE);

如果您的片段当前未附加到活动,则可能会发生这种情况。

只有其他选项是info[i]等于null - 我觉得这不太可能。

p.s。检查实例this sample

public class MainActivity extends FragmentActivity
                          implements NoticeDialogFragment.NoticeDialogListener{
    ...

    public void showNoticeDialog() {
        // Create an instance of the dialog fragment and show it
        DialogFragment dialog = new NoticeDialogFragment();
        dialog.show(getSupportFragmentManager(), "NoticeDialogFragment");
    }

所以你看到你必须在第一次调用中提供片段管理器。否则getActivity()将是null,这也可以在NPE中发现:

public void check(){
    ...
    } else {
        FragmentManager ft = getActivity().getFragmentManager(); // getActivity() might return null 
        MyAlertDialogWIndow alert = new MyAlertDialogWIndow();
        alert.show(ft, "Alert");
    }

答案 1 :(得分:1)

您的问题是,您在getActivity()上未Fragment附加了Activity

当您按如下方式实例化Fragment课程时

Fragment2 fragment2 = new Fragment2();

它会为null返回getActivity()。我建议不要在Fragment实例化FragmentTransaction,而是先从您计划使用的Activity中调用Fragment,然后先附加Activity

修改

另一种可能更简单的选择是将互联网检测方法作为Fragment而非{{1}}的一部分。这样你就可以做到以下几点:

OnClickListener positiveClick = new OnClickListener() {  
        @Override
        public void onClick(DialogInterface dialog, int which) {   

        ((YourActivityName)getActivity()).check();
    }
};

答案 2 :(得分:0)

看看你的代码,

public boolean isConnectedToInternet(){
    this line can be corrected, using my code below:
    ConnectivityManager connectivity = (ConnectivityManager)

ConnectivityManager connMgr = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo networkInfo = connMgr.getActiveNetworkInfo(); OR
NetworkInfo[] info = connMgr.getAllNetworkInfo();