Chava Koteswara Rao
Chava Koteswara Rao

Reputation: 33

After pressing back button, not coming to main activity instead closing the app

I have two activities in my project. There is a button in the main activity when I click it, it takes me to second activity. When I press back button there it's not coming to main activity. It checks for internet first and then when I click button It takes me to second activity.


public class MainActivity extends AppCompatActivity {

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


        this.getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,WindowManager.LayoutParams.FLAG_FULLSCREEN);
        try {
            this.getSupportActionBar().hide();
        }catch (Exception e){

        }

        if (isNetworkConnected(this)) {
            Button button = findViewById(R.id.button);
            button.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View view) {
                    Intent activity2Intent = new Intent(getApplicationContext(), playlive.class);
                    startActivity(activity2Intent);

                }
            });
        } else {
            buildDialog(MainActivity.this).show();
        }


    }

    public static boolean isNetworkConnected(Context context) {
        boolean result = false;
        ConnectivityManager cm = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
            if (cm != null) {
                NetworkCapabilities capabilities = cm.getNetworkCapabilities(cm.getActiveNetwork());
                if (capabilities != null) {
                    if (capabilities.hasTransport(NetworkCapabilities.TRANSPORT_WIFI)) {
                        result = true;
                    } else if (capabilities.hasTransport(NetworkCapabilities.TRANSPORT_CELLULAR)) {
                        result = true;
                    }
                }
            }
        } else {
            if (cm != null) {
                NetworkInfo activeNetwork = cm.getActiveNetworkInfo();
                if (activeNetwork != null) {
                    // connected to the internet
                    if (activeNetwork.getType() == ConnectivityManager.TYPE_WIFI) {
                        result = true;
                    } else if (activeNetwork.getType() == ConnectivityManager.TYPE_MOBILE) {
                        result = true;
                    }
                }
            }
        }
        return result;
    }


This is the error code

    Process: com.example.mythrimedia, PID: 3343
    java.lang.RuntimeException: Unable to stop activity {com.example.mythrimedia/com.example.mythrimedia.playlive}: java.lang.NullPointerException: Attempt to invoke virtual method 'void com.google.android.exoplayer2.SimpleExoPlayer.release()' on a null object reference
        at android.app.ActivityThread.callActivityOnStop(ActivityThread.java:4624)
        at android.app.ActivityThread.performStopActivityInner(ActivityThread.java:4594)
        at android.app.ActivityThread.handleStopActivity(ActivityThread.java:4669)
        at android.app.servertransaction.TransactionExecutor.performLifecycleSequence(TransactionExecutor.java:233)
        at android.app.servertransaction.TransactionExecutor.cycleToPath(TransactionExecutor.java:201)
        at android.app.servertransaction.TransactionExecutor.executeLifecycleState(TransactionExecutor.java:173)
        at android.app.servertransaction.TransactionExecutor.execute(TransactionExecutor.java:97)
        at android.app.ActivityThread$H.handleMessage(ActivityThread.java:2016)
        at android.os.Handler.dispatchMessage(Handler.java:107)
        at android.os.Looper.loop(Looper.java:214)
        at android.app.ActivityThread.main(ActivityThread.java:7356)
        at java.lang.reflect.Method.invoke(Native Method)
        at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:492)
        at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:930)
     Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'void com.google.android.exoplayer2.SimpleExoPlayer.release()' on a null object reference
        at com.example.mythrimedia.playlive.onStop(playlive.java:76)
        at android.app.Instrumentation.callActivityOnStop(Instrumentation.java:1466)
        at android.app.Activity.performStop(Activity.java:8018)
        at android.app.ActivityThread.callActivityOnStop(ActivityThread.java:4616)
        at android.app.ActivityThread.performStopActivityInner(ActivityThread.java:4594) 
        at android.app.ActivityThread.handleStopActivity(ActivityThread.java:4669) 
        at android.app.servertransaction.TransactionExecutor.performLifecycleSequence(TransactionExecutor.java:233) 
        at android.app.servertransaction.TransactionExecutor.cycleToPath(TransactionExecutor.java:201) 
        at android.app.servertransaction.TransactionExecutor.executeLifecycleState(TransactionExecutor.java:173) 
        at android.app.servertransaction.TransactionExecutor.execute(TransactionExecutor.java:97) 
        at android.app.ActivityThread$H.handleMessage(ActivityThread.java:2016) 
        at android.os.Handler.dispatchMessage(Handler.java:107) 
        at android.os.Looper.loop(Looper.java:214) 
        at android.app.ActivityThread.main(ActivityThread.java:7356) 
        at java.lang.reflect.Method.invoke(Native Method) 
        at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:492) 
        at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:930) 

second activity


public class playlive extends AppCompatActivity {


    private SimpleExoPlayer player;
    private PlayerView playerView;

    private Uri uri;


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

        this.getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN, WindowManager.LayoutParams.FLAG_FULLSCREEN);
        this.getWindow().setFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON, WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);
        try {
            this.getSupportActionBar().hide();
        } catch (Exception e) {

        }

        if (isNetworkConnected(this)) {
            play();
        } else {
            buildDialog(playlive.this).show();
        }

    }


    private void play() {
        SimpleExoPlayer player = ExoPlayerFactory.newSimpleInstance(this);
        playerView = findViewById(R.id.player_view);
        playerView.setPlayer(player);
        uri = Uri.parse("http://localhost:1935/live/mystream/index.m3u8");

        DataSource.Factory dataSourceFactory =
                    new DefaultHttpDataSourceFactory(Util.getUserAgent(this, "app-name"));
// Create a HLS media source pointing to a playlist uri.
            HlsMediaSource hlsMediaSource =
                    new HlsMediaSource.Factory(dataSourceFactory).createMediaSource(uri);


            player.prepare(hlsMediaSource);
            player.setPlayWhenReady(true);


    }


    public void onStop(){
        super.onStop();
        player.release();
    }

    public void onDestroy(){
        super.onDestroy();
        player.release();
    }

    public static boolean isNetworkConnected(Context context) {
        boolean result = false;
        ConnectivityManager cm = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
            if (cm != null) {
                NetworkCapabilities capabilities = cm.getNetworkCapabilities(cm.getActiveNetwork());
                if (capabilities != null) {
                    if (capabilities.hasTransport(NetworkCapabilities.TRANSPORT_WIFI)) {
                        result = true;
                    } else if (capabilities.hasTransport(NetworkCapabilities.TRANSPORT_CELLULAR)) {
                        result = true;
                    }
                }
            }
        } else {
            if (cm != null) {
                NetworkInfo activeNetwork = cm.getActiveNetworkInfo();
                if (activeNetwork != null) {
                    // connected to the internet
                    if (activeNetwork.getType() == ConnectivityManager.TYPE_WIFI) {
                        result = true;
                    } else if (activeNetwork.getType() == ConnectivityManager.TYPE_MOBILE) {
                        result = true;
                    }
                }
            }
        }
        return result;
    }

    public AlertDialog.Builder buildDialog(Context c) {

        AlertDialog.Builder builder = new AlertDialog.Builder(c);
        builder.setTitle("No Internet Connection");
        builder.setMessage("You need to have Mobile Data or WiFi to Play this. Press ok to Exit");

        builder.setPositiveButton("Ok", new DialogInterface.OnClickListener() {

            @Override
            public void onClick(DialogInterface dialog, int which) {

                finish();
            }
        });

        return builder;
    }


}

Upvotes: 0

Views: 81

Answers (2)

Houssein Zouari
Houssein Zouari

Reputation: 722

add a double check in your 2 methods onDestory and onStop on the secondActivity.

if (player != null) {
player.release;
}

add move it before the line super.onStop(); or super.onDestroy()

Upvotes: 1

Mykhailo Yuzheka
Mykhailo Yuzheka

Reputation: 733

your global variable private SimpleExoPlayer player; is alwaus null

I guess you should init it here

private void play() {
    player = ExoPlayerFactory.newSimpleInstance(this);...

instead of creating new instance

Upvotes: 0

Related Questions