-1

I want to hide some parts of activity if it is not online and show if the network is available layout is

<?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>

the Service class is

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 is

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() {

    }
}

I get stack trace

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)

how can I resolve this issue

Arshad Ali
  • 3,082
  • 12
  • 56
  • 99
  • 1
    Yes, that `View` reference is null, because you can't instantiate an `Activity` like that, and have it work correctly. Furthermore, the `newInstance()` method name should be a clue that that instance wouldn't be the same one that's already running anyway. – Mike M. Mar 16 '17 at 07:59
  • OK but any solution – Arshad Ali Mar 16 '17 at 08:00
  • test `mOnline.setVisibility(View.VISIBLE)` in oncreate – Kiran Benny Joseph Mar 16 '17 at 08:08
  • 2
    Bind the `Service`, or `LocalBroadcastManager`, or some other event bus, or a `singleTop`/`singleInstance` `Activity` and `onNewIntent()`, etc. – Mike M. Mar 16 '17 at 08:10
  • @KiranBennyJoseph mOnline.setVisibility(View.VISIBLE) in oncreate it works fine over there – Arshad Ali Mar 16 '17 at 08:10
  • Possible duplicate of [What is a NullPointerException, and how do I fix it?](http://stackoverflow.com/questions/218384/what-is-a-nullpointerexception-and-how-do-i-fix-it) – David Rawson Mar 16 '17 at 08:18

1 Answers1

0

Try using 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();
}
}

And in service

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;
        }

    }

}
Kiran Benny Joseph
  • 6,755
  • 4
  • 38
  • 57