2017-03-16 33 views
-1

我想隱藏活動的一些地方,如果不在線,並顯示網絡是否可用佈局服務爲套管怪異NullPointerException異常,甚至認爲不爲空

<?xml version="1.0" encoding="utf-8"?> 
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android" 
    xmlns:tools="http://schemas.android.com/tools" 
    xmlns:app="http://schemas.android.com/apk/res-auto" 
    android:layout_width="match_parent" 
    android:background="@color/gray" 
    android:layout_height="match_parent" 
    tools:context=".MainActivity"> 

    <RelativeLayout 
     android:visibility="gone" 
     android:id="@+id/online" 
     android:layout_width="match_parent" 
     android:layout_height="match_parent"> 

     <android.support.v7.widget.RecyclerView 
      android:id="@+id/message_rv" 
      android:layout_width="match_parent" 
      android:layout_height="match_parent" 
      android:layout_above="@+id/chat_input_view" /> 


     <org.slabs.fc.chatapp.utils.ChatTextInputView 
      android:id="@+id/chat_input_view" 
      app:actionMenu="@menu/input_actions" 
      android:layout_width="match_parent" 
      android:layout_alignParentBottom="true" 
      android:layout_height="wrap_content" /> 

    </RelativeLayout> 

    <FrameLayout 
     android:id="@+id/not_online" 
     android:layout_width="match_parent" 
     android:layout_height="match_parent" 
     > 

     <ImageView 
      android:src="@drawable/sad_cloud" 
      android:layout_width="100dp" 
      android:layout_height="100dp" 
      android:layout_gravity="center" 
      android:layout_marginBottom="80dp" /> 

     <TextView 
      android:layout_width="wrap_content" 
      android:layout_height="wrap_content" 
      android:text="No network" 
      android:layout_marginTop="50dp" 
      android:layout_gravity="center|center" 
      android:textStyle="bold" 
      android:textSize="30dp" /> 

    </FrameLayout> 

</RelativeLayout> 

服務類

public class ConnectionService extends Service { 

    // Constant 

    public static String TAG_ACTIVITY_NAME = "activity_name"; 

    private int interval; 

    private String activity_name; 

    private Timer mTimer = null; 

    ConnectionServiceCallback mConnectionServiceCallback; 

    @Override 
    public IBinder onBind(Intent intent) { 
     return null; 
    } 

    public interface ConnectionServiceCallback { 
     void hasInternetConnection(); 
     void hasNoInternetConnection(); 
    } 


    @Override 
    public int onStartCommand(Intent intent, int flags, int startId) { 
     Log.e("SERVICE", "Started..."); 

     interval = 10; 

     activity_name = intent.getStringExtra(TAG_ACTIVITY_NAME); 

     try { 
      Log.e("ACTIVITY_NAME", "Is " + activity_name); 
      mConnectionServiceCallback = (ConnectionServiceCallback) Class.forName(activity_name).newInstance(); 
     } catch (InstantiationException e) { 
      e.printStackTrace(); 
     } catch (IllegalAccessException e) { 
      e.printStackTrace(); 
     } catch (ClassNotFoundException e) { 
      e.printStackTrace(); 
     } 

     mTimer = new Timer(); 
     mTimer.scheduleAtFixedRate(new CheckForConnection(), 0, interval * 1000); 

     return super.onStartCommand(intent, flags, startId); 
    } 

    class CheckForConnection extends TimerTask { 
     @Override 
     public void run() { 
      isOnline(); 
     } 
    } 

    @Override 
    public void onDestroy() { 
     mTimer.cancel(); 
     super.onDestroy(); 
     Log.e("SERVICE", "Destroyed..."); 
    } 

    public boolean isOnline() { 
     Log.e("SERVICE", "isOnline..."); 
     ConnectivityManager cm = 
       (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE); 
     NetworkInfo netInfo = cm.getActiveNetworkInfo(); 
     if (netInfo != null && netInfo.isConnectedOrConnecting()){ 
      mConnectionServiceCallback.hasInternetConnection(); 
      Log.e("SERVICE", "isOnline is TRUE..."); 
      return true; 
     } else { 
      mConnectionServiceCallback.hasNoInternetConnection(); 
      Log.e("SERVICE", "isOnline is FALSE..."); 

      return false; 
     } 

    } 

} 

MainActivity是

public class MainActivity extends AppCompatActivity implements ConnectionService.ConnectionServiceCallback{ 

    Intent intentServeice = null; 
    private FrameLayout mNotOnline; 
    private RelativeLayout mOnline; 

    @Override 
    protected void onCreate(Bundle savedInstanceState) { 
     super.onCreate(savedInstanceState); 
     setContentView(R.layout.activity_main); 

     mNotOnline = (FrameLayout) findViewById(R.id.not_online); // mNotOnline is initialized 
     mOnline = (RelativeLayout) findViewById(R.id.online);  // mOnline is initialized 

     intentServeice = new Intent(this, ConnectionService.class); 
     intentServeice.putExtra(ConnectionService.TAG_ACTIVITY_NAME, MainActivity.this.getClass().getName()); 
     startService(intentServeice); 

    } 

    // Callback methods of ConnectionService.ConnectionServiceCallback interface 

    @Override 
    public void hasInternetConnection() { 
     mOnline.setVisibility(View.VISIBLE); // Line number 433 of MainActivity getting NPE 
     mNotOnline.setVisibility(View.GONE); // 
    } 

    @Override 
    public void hasNoInternetConnection() { 

    } 
} 

我得到堆棧跟蹤

03-16 11:49:08.602 28449-28527/ve.we.re.app E/AndroidRuntime: FATAL EXCEPTION: Timer-0 
Process: ve.we.re.app, PID: 28449 
java.lang.NullPointerException: Attempt to invoke virtual method 'void android.widget.RelativeLayout.setVisibility(int)' on a null object reference 
    at ve.we.re.app.MainActivity.hasInternetConnection(MainActivity.java:433) 
    at ve.we.re.app.service.ConnectionService.isOnline(ConnectionService.java:116) 
    at ve.we.re.app.service.ConnectionService$CheckForConnection.run(ConnectionService.java:71) 
    at java.util.Timer$TimerImpl.run(Timer.java:284) 

我怎麼能解決這個問題

+1

是的,'View'引用是空的,因爲你不能像這樣實例化一個Activity,並使其正確工作。此外,'newInstance()'方法名應該是一個線索,即該實例不會是已經運行的那個實例。 –

+0

好的,但任何解決方案 –

+0

測試'mOnline.setVisibility(View.VISIBLE)'在創建 –

回答

0

嘗試使用BroadcastReceiver

public class MainActivity extends AppCompatActivity{ 
    MyReceiver myReceiver; 
    Intent intentServeice = null; 
    private FrameLayout mNotOnline; 
    private RelativeLayout mOnline; 

    @Override 
    protected void onCreate(Bundle savedInstanceState) { 
     super.onCreate(savedInstanceState); 
     setContentView(R.layout.activity_main); 

     mNotOnline = (FrameLayout) findViewById(R.id.not_online); // mNotOnline is initialized 
     mOnline = (RelativeLayout) findViewById(R.id.online);  // mOnline is initialized 
     myReceiver = new MyReceiver(); 
     IntentFilter intentFilter = new IntentFilter(); 
     intentFilter.addAction(ConnectionService.MY_ACTION); 
    registerReceiver(myReceiver, intentFilter); 
     intentServeice = new Intent(this, ConnectionService.class); 
     intentServeice.putExtra(ConnectionService.TAG_ACTIVITY_NAME, MainActivity.this.getClass().getName()); 
     startService(intentServeice); 

    } 

private class MyReceiver extends BroadcastReceiver{ 

@Override 
public void onReceive(Context arg0, Intent arg1) { 
    // TODO Auto-generated method stub 

    boolean hasInternet = arg1.getBooleanExtra("Internet", false); //handle this 

    if(hasInternet){ 
    mOnline.setVisibility(View.VISIBLE); 
     mNotOnline.setVisibility(View.GONE); 
    } 

} 

} 
@Override 
protected void onStop() { 
// TODO Auto-generated method stub 
unregisterReceiver(myReceiver); 
super.onStop(); 
} 
} 

而且在服務

public class ConnectionService extends Service { 

    // Constant 
    final static String MY_ACTION = "MY_ACTION"; 
    public static String TAG_ACTIVITY_NAME = "activity_name"; 

    private int interval; 

    private String activity_name; 

    private Timer mTimer = null; 



    @Override 
    public IBinder onBind(Intent intent) { 
     return null; 
    } 




    @Override 
    public int onStartCommand(Intent intent, int flags, int startId) { 
     Log.e("SERVICE", "Started..."); 

     interval = 10; 

     activity_name = intent.getStringExtra(TAG_ACTIVITY_NAME); 

     try { 
      Log.e("ACTIVITY_NAME", "Is " + activity_name); 

     } catch (InstantiationException e) { 
      e.printStackTrace(); 
     } catch (IllegalAccessException e) { 
      e.printStackTrace(); 
     } catch (ClassNotFoundException e) { 
      e.printStackTrace(); 
     } 

     mTimer = new Timer(); 
     mTimer.scheduleAtFixedRate(new CheckForConnection(), 0, interval * 1000); 

     return super.onStartCommand(intent, flags, startId); 
    } 

    class CheckForConnection extends TimerTask { 
     @Override 
     public void run() { 
      Intent intent = new Intent(); 
      intent.setAction(MY_ACTION); 
      intent.putExtra("Internet", isOnline()); 
      sendBroadcast(intent); 

     } 
    } 

    @Override 
    public void onDestroy() { 
     mTimer.cancel(); 
     super.onDestroy(); 
     Log.e("SERVICE", "Destroyed..."); 
    } 

    public boolean isOnline() { 
     Log.e("SERVICE", "isOnline..."); 
     ConnectivityManager cm = 
       (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE); 
     NetworkInfo netInfo = cm.getActiveNetworkInfo(); 
     if (netInfo != null && netInfo.isConnectedOrConnecting()){ 

      Log.e("SERVICE", "isOnline is TRUE..."); 
      return true; 
     } else { 

      Log.e("SERVICE", "isOnline is FALSE..."); 

      return false; 
     } 

    } 

}