Artenes Nogueira
Artenes Nogueira

Reputation: 1552

How to prevent my android application to collapse when the screen orientation changes in the lock screen?

I found this problem recently. I'm using a Samsung Tab 7'' with Android 4.1 for the tests.

I have a new android application project. Here we have the trash.xml

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent">
<TextView
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:text="@string/hello_world" /> 
</RelativeLayout>

And the Activity that is calling it:

package com.example.trash;

import android.os.Bundle;
import android.app.Activity;

public class MainActivity extends Activity {

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

}

Pretty simple so far. Then I put this code in the MainActivity tab in the AndroidManifest:

android:screenOrientation="portrait"

The problem appeared when I : 1. locked the screen 2. changed orientation of the tablet to landscape 3. then unlocked the screen 4. and for my surprise, instead of returnig to portrait orientation, my application just collapsed beacause of a simple error (Resources$NotFoundException):

06-15 00:12:37.390: E/AndroidRuntime(6452): java.lang.RuntimeException: Unable to start         activity ComponentInfo{com.example.trash/com.example.trash.MainActivity}: android.content.res.Resources$NotFoundException: Resource ID #0x7f030001

What can I do to avoid this problem, instead of making a landscape layout for my application?

Upvotes: 2

Views: 623

Answers (2)

Artenes Nogueira
Artenes Nogueira

Reputation: 1552

1 Your project must target 3.0 or higher;

2 In your activity tab (in the android manifest) you have to add these two lines:

android:screenOrientation="portrait" or android:screenOrientation="landscape"
android:configChanges="orientation|screenSize"

3 In your Activity class, add the folowing method:

@Override
public void onConfigurationChanged(Configuration newConfig) {
super.onConfigurationChanged(newConfig);
setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);  
}   

This works like this. Adding configChanges to your Activity tab, will make the method onConfigurationChanged be called every time the screen changes between landscape and protrait and vice-versa. Then, in the method we use the setRequestOrientation to force the Activity to stay in a certain orientation.

Upvotes: 0

Jordan B.
Jordan B.

Reputation: 143

You could try calling setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT); in your activites onCreate()

Upvotes: 2

Related Questions