While rotating device a onActivityCreated() of previous class is always called - android

I am new to android.I have one problem.I am using fragments.My application has 5 tabs.My application stopped unexpectedly after one particular tab then moves to another tab and rotates the current view.By debugging I got the error.Error is that while rotating current view control goes to onActivtyCreated() of previous class.
datetext.setText(TimeFormater.FormatDate(dateString));
This line gives the null pointer exception.Control always goes to the code given below.
public class ScheduleDailyView extends SherlockFragment{public void onActivityCreated(Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
nextbutn = (Button)getActivity().findViewById(R.id.buttonnext);
prebutn = (Button)getActivity().findViewById(R.id.buttonpre);
listview = (ListView)getActivity().findViewById(R.id.lv_schedule_listView);
datetext = (TextView)getActivity().findViewById(R.id.textscheduleviewdate);
dateString = TimeFormater.DateToString(Schedule.currentDate.getTime());
ArrayList<ViewScheduleDTO> scheduleList =scheduleDaily.readschedules(dateString,doctor_id);
datetext.setText(TimeFormater.FormatDate(dateString));
rowitems = scheduleDaily.getScheduleRowList(dateString,scheduleList);
listview.setAdapter(new ScheduleCustomView(appContext, rowitems));
if(userType.equals(UserTypeEnum.Admin.getDisplayName()) || userType.equals(UserTypeEnum.Doctor.getDisplayName()))
listview.setOnItemLongClickListener(this);
listview.setOnItemClickListener(this);
nextbutn.setOnClickListener(this);
prebutn.setOnClickListener(this);
}}

Try this... add this line in your manifest.xml
<activity android:name="Your Activity Name"
android:configChanges="keyboard|keyboardHidden|orientation|screenLayout|uiMode|screenSize|smallestScreenSize" android:windowSoftInputMode="adjustPan"/>

Whenever device screen is rotated the present activity is recreated. In which orientation you want your application to be.. You can fix it in by declaring it in manifest file.... If it is in both orientations the go through the following link :
Handling Runtime Changes
Hope this will help you....

Check the orientation in Manifest.xml file. Changing from portrait to landscape or vice versa might help.

Related

How to change screen orientation, without creating a new activity on android?

I do not know if the title is correct, here is what happens.
I have an application which works differently on a phone and on a tablet, on a phone it shows as portrait on a tablet it shows as landscape.
To achieve this I created a class called CoreActivity which is extended by all my activities and does the following:
public class CoreActivity extends Activity {
protected boolean _landscape = false;
public boolean isPhone() {
int layoutSize = getScreenLayoutSize();
return (layoutSize == Configuration.SCREENLAYOUT_SIZE_SMALL || layoutSize == Configuration.SCREENLAYOUT_SIZE_NORMAL);
}
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
if (isPhone() && !_landscape) {
this.setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
} else {
this.setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE);
}
}
protected int getScreenLayoutSize() {
return (getResources().getConfiguration().screenLayout & Configuration.SCREENLAYOUT_SIZE_MASK);
}
}
My problem occurs when I wish to show a screen on a phone setup on landscape mode, to do this I use the following:
#Override
protected void onCreate(Bundle savedInstanceState) {
_landscape = true
super.onCreate(savedInstanceState);
}
The problem is, that on a phone, if the user is holding the phone on portrait mode (as one would, since most of the application is in portrait mode) then the activity gets created and destroyed and then recreated. But if they are holding it on landscape mode, then it is only created once.
My problem occurs because on the onCreate method I launch the threads that load data, and I also show fragments.
Is there a way to avoid this problem? is there a way to launch an activity from the start on portrait mode and not change it, or have it not create twice?
Thanks in advance for any help you can provide
Recreating occurs just because you are forcing to, by calling setRequestedOrientation probably in order to set screen orientation. However you don't need to check and change it by code. You can do it via xml file. You can set different xml files depending on the screen size. But it is little bit hack so there is no guarantee in the future.
On the manifest file you can force by:
<activity
android:name="com.my.example.MyActivity"
android:screenOrientation="landscape"/> // or portrait
So as far as I understand you want to force portrait for small sizes and landscape(or sensor) for larger screen sizes. But above configuration applies for all screen sizes. Here is the tricky part: landscape portrait sensor etc. are all integers defined here.
As you might guess you can write android:screenOrientation=0 instead of landscape. What we know from beginning lessons of android, we can define integers in xml files then their values might vary on screen size. So..
You should first create different integers.xml files for different screen sizes. i.e.:
values
- integers.xml
values-large
- integers.xml
for values/integers.xml:
<?xml version="1.0" encoding="utf-8"?>
<resources>
<integer name="orientation">1</integer> // 1 for portrait
</resources>
for values-large/integers.xml:
<?xml version="1.0" encoding="utf-8"?>
<resources>
<integer name="orientation">0</integer> // 0 for landscape
</resources>
and finally you you have to manipulate manifest file by:
<activity
android:name="com.my.example.MyActivity"
android:screenOrientation="#integer/orientation"/> // read constant from xml files
You can also use sensor , fullSensor, nosensor, locked, behind, reverseLandscape, reversePortait options too. But I am warning you, this is a hack solution.
Well, I found a solution to this issue, just declare:
android:screenOrientation="locked"
on every activity having this issue in the manifest.
And keep using setRequestedOrientation() programatically to define if landscape or portrait orientation within onCreate() method,
It will work! ;)
If all your activites must have the same orientation on a device, you can start your application with a splash screen activity, set the orientation like in your current code and forward to your CoreActivity or any other activity in your App.
In your AndroidManifest.xml set
<activity
android:name=".CoreActivity"
android:screenOrientation="behind"/>
This will use the same orientation as the activity that's immediately beneath it in the activity stack.
Did you try adding android:configChanges="keyboard|keyboardHidden|orientation" to the <activity>-Tag inside of your AndroidManifest.xml?
This should prevent the system from restarting the Activity, but I am not sure whether this will actually work when forcing the orientation programatically. It's worth a shot though.
try this in your manifest.xml...
this will stop the recalling the onCreate() multiple time while orientation changes...
android:configChanges="keyboardHidden|orientation|screenSize"
You dont need to handle this manually. Android has built it support for different screen sizes
check this link
http://developer.android.com/training/multiscreen/screensizes.html

Android:stop refresh Activity when page move onto portrait to landscape mood

I want to stop activity refresh when I move on to portrait mood to landscape mood and I also want load file layout-land when it move to portrait to landscape mood without any refreshment the activity.
I use <activity android:name=".Login"
android:configChanges="orientation|screenSize">
but,In this method when I move onto portrait to landscape mood ,It does not load the file from layout-land folder. what should I do for this? please someone help me.
Call method setContentView(R.layout.main) in onConfigurationChanged()
#Override
public void onConfigurationChanged(Configuration newConfig) {
super.onConfigurationChanged(newConfig);
///in case you have some EditTexts , save their input before setting the new layout.
emailForConfigChanges = emailTextBox.getText().toString().trim();
passwordForConfigChanges = passwordTextBox.getText().toString().trim();
setContentView(R.layout.main);
//Now set the values back to the EditTexts .
}
You just have to add this method to your activity as it handles all the orientation changes if you have declared "orientation" in your manifest.
EDIT : And if EditTexts lose their values on rotation, get their values before calling setContentView() in onConfigurationChanged(). See the edit above.
I handled this problem only by addding android:configChanges="keyboardHidden|orientation"
hope this will help you.

TextView's text disappearing when device rotated

I am writing a phone dialer app for android. I created a layout for keypad, which contains a TextView and 10 buttons. Buttons are as keys for 10 digits(0 to 9) and TextView is for displaying the number according to keys pressed.
In my app, i am appending the text ("0" or "1", etc.) to the TextView for each button pressed. If i pressed the buttons 1, 2, 3 then the text on TextView is 123.
The problem is, let's take the screen is in landscape mode and TextView contains 123, if i turn it, in portrait mode no text on TextView.
Please Help Me Regarding this.
What #jeet recommended didn't work for me. I had to add "screenSize". This is the line you should add in your manifest.xml in the <activity> node of your activity:
android:configChanges="keyboardHidden|orientation|screenSize"
Thus, the complete node may look like this:
<activity
android:name=".YourActivity"
android:label="#string/app_name"
android:configChanges="keyboardHidden|orientation|screenSize"
android:theme="#style/AppTheme.NoActionBar">
Please check on orientation change, on create method is called, which requires all the views to be created again, so you need to use one of the following methods:
use onSavedInstance method and save the states of components/views to bundle.
Just use following flag true in your manifest file in activity tag android:configChanges="keyboardHidden|orientation". like below:
<activity android:name=".SampleActivity" android:label="#string/app_name"
android:configChanges="keyboardHidden|orientation">
...
</activity>
The reason for this is due to Android basically destroying the activity and creating it again every time you rotate the device. This is mainly to allow for different layouts based on portrait/landscape mode.
The best way to handle this is to store whatever data you need to keep within the Activity Bundle, by responding to the onSavedInstance event (called just before Android destroys the activity), and then reapplying those in the standard onCreate event.
Although you can add "orientation" to the configChanges property, keep in mind that you're basically telling Android that you're going to be handling everything relating to orientation change yourself - including changing layout, etc.
To preserve a TextView's text, you can simply set the TextView's freezesText property to true.
As in:
<TextView
...
android:freezesText="true"
.../>
This is the accepted answer here:
Restoring state of TextView after screen rotation?
If someone is still having troubles... this did the trick for me
public class BranjeKP extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_branje_kp);
//...
}
#Override
protected void onSaveInstanceState(Bundle out) {
super.onSaveInstanceState(out);
out.putString("TVNazivPod", TVNazivPodatka.getText().toString());
out.putString("TVEnotaMere", TVEnotaMere.getText().toString());
}
#Override
protected void onRestoreInstanceState(Bundle in) {
super.onRestoreInstanceState(in);
TVNazivPodatka.setText(in.getString("TVNazivPod"));
TVEnotaMere.setText(in.getString("TVEnotaMere"));
}
You basically save any values you want before rotation (that's when onSaveInstanceState is called) into a Bundle and after rotation (onRestoreInstanceState) you just pull all values out from Bundle.
Just to clarify, TVNazivPodatka and TVEnotaMere are TextView widgets.
...with a help from
How to prevent custom views from losing state across screen orientation changes

Don't reload application when orientation changes

I simply need nothing to change when the screen is rotated. My app displays a random image when it first loads and rotating the device should not select another random image.
How can I (simply) make this behavior stop?
There are generally three ways to do this:
As some of the answers suggested, you could distinguish the cases of your activity being created for the first time and being restored from savedInstanceState. This is done by overriding onSaveInstanceState and checking the parameter of onCreate.
You could lock the activity in one orientation by adding android:screenOrientation="portrait" (or "landscape") to <activity> in your manifest.
You could tell the system that you meant to handle screen changes for yourself by specifying android:configChanges="orientation|screenSize" in the <activity> tag. This way the activity will not be recreated, but will receive a callback instead (which you can ignore as it's not useful for you).
Personally I'd go with (3). Of course if locking the app to one of the orientations is fine with you, you can also go with (2).
Xion's answer was close, but #3 (android:configChanes="orientation") won't work unless the application has an API level of 12 or lower.
In API level 13 or above, the screen size changes when the orientation changes, so this still causes the activity to be destroyed and started when orientation changes.
Simply add the "screenSize" attribute like I did below:
<activity
android:name=".YourActivityName"
android:configChanges="orientation|screenSize">
</activity>
Now, when you change orientation (and screen size changes), the activity keeps its state and onConfigurationChanged() is called. This will keep whatever is on the screen (ie: webpage in a Webview) when the orientation changes.
Learned this from this site:
http://developer.android.com/guide/topics/manifest/activity-element.html
Also, this is apparently a bad practice so read the link below about Handling Runtime Changes:
http://developer.android.com/guide/topics/resources/runtime-changes.html
You just have to go to the AndroidManifest.xml and inside or in your activities labels, you have to type this line of code as someone up there said:
android:configChanges="orientation|screenSize"
So, you'll have something like this:
<activity android:name="ActivityMenu"
android:configChanges="orientation|screenSize">
</activity>
Hope it works!
<activity android:name="com.example.abc"
android:configChanges="orientation|screenSize"></activity>
Just add android:configChanges="orientation|screenSize" in activity tab of manifest file.
So, Activity won't restart when orientation change.
It's my experience that it's actually better to just deal with the orientation changes properly instead of trying to shoehorn a non-default behavior.
You should save the image that's currently being displayed in onSaveInstanceState() and restore it properly when your application runs through onCreate() again.
This solution is by far the best working one. In your manifest file add
<activity
android:configChanges="keyboardHidden|orientation|screenSize"
android:name="your activity name"
android:label="#string/app_name"
android:screenOrientation="landscape">
</activity
And in your activity class add the following code
#Override
public void onConfigurationChanged(Configuration newConfig)
{
super.onConfigurationChanged(newConfig);
if (newConfig.orientation == Configuration.ORIENTATION_PORTRAIT) {
//your code
} else if (newConfig.orientation == Configuration.ORIENTATION_LANDSCAPE) {
//your code
}
}
In manifiest file add to each activity this. This will help
android:configChanges = "orientation|keyboard|keyboardHidden|screenLayout|screenSize"
add android:configChanges="keyboardHidden|orientation|screenSize" for all the app activities tags in manifest.
Just add this to your AndroidManifest.xml
<activity android:screenOrientation="landscape">
I mean, there is an activity tag, add this as another parameter. In case if you need portrait orientation, change landscape to portrait. Hope this helps.
just use : android:configChanges="keyboardHidden|orientation"
As Pacerier mentioned,
android:configChanges="orientation|screenSize"
All above answers are not working for me. So, i have fixed by mentioning the label with screenOrientation like below. Now everything fine
<activity android:name=".activity.VideoWebViewActivity"
android:label="#string/app_name"
android:configChanges="orientation|screenSize"/>
http://animeshrivastava.blogspot.in/2017/08/activity-lifecycle-oncreate-beating_3.html
#Override
protected void onSaveInstanceState(Bundle b)
{
super.onSaveInstanceState(b);
String str="Screen Change="+String.valueOf(screenChange)+"....";
Toast.makeText(ctx,str+"You are changing orientation...",Toast.LENGTH_SHORT).show();
screenChange=true;
}
Prevent Activity to recreated
Most common solution to dealing with orientation changes by setting the android:configChanges flag on your Activity in AndroidManifest.xml. Using this attribute your Activities won’t be recreated and all your views and data will still be there after orientation change.
<activity
android:name="com.example.test.activity.MainActivity"
android:configChanges="orientation|screenSize|keyboardHidden"/>
this is work for me😊😊😊
Save the image details in your onPause() or onStop() and use it in the onCreate(Bundle savedInstanceState) to restore the image.
EDIT:
More info on the actual process is detailed here http://developer.android.com/reference/android/app/Activity.html#ActivityLifecycle as it is different in Honeycomb than previous Android versions.
I dont know if the a best solution, but i describe it here:
First of all, you need certificate with you class Application of your app is in your manifest of this:
<application
android:name=".App"
...
Second, in my class App i did like this:
public class App extends Application {
public static boolean isOrientationChanged = false;
#Override
public void onCreate() {
super.onCreate();
}
#Override
public void onConfigurationChanged(#NotNull Configuration newConfig) {
super.onConfigurationChanged(newConfig);
if (newConfig.orientation == Configuration.ORIENTATION_LANDSCAPE ||
newConfig.orientation == Configuration.ORIENTATION_PORTRAIT) {
isOrientationChanged = true;
}
}
}
Third, you need to set a flag to Orientation Change, in my case, I always set it when the previous activity within the app navigation is called, so only calling once when the later activity is created.
isOrientationChanged = false;
So every time I change the orientation of my screen in that context, I set it every time it changes this setting, it checks if there is a change in orientation, if so, it validates it based on the value of that flag.
Basically, I had to use it whenever I made an asynchronous retrofit request, which he called every moment that changed orientation, constantly crashing the application:
if (!isOrientationChanged) {
presenter.retrieveAddress(this, idClient, TYPE_ADDRESS);
}
I don't know if it's the most elegant and beautiful solution, but at least here it's functional :)
Add this code after the onCreate ,method in your activity containing the WebView
#Override
protected void onSaveInstanceState(Bundle outState) {
super.onSaveInstanceState(outState);
}
#Override
protected void onRestoreInstanceState(Bundle state) {
super.onRestoreInstanceState(state);
}

Android Orientation Change

My tabbed app does not redisplay the view with an orientation change.
I added
android:configChanges="keyboardHidden|orientation"
to the main tab activity and to each activity in the manifest.
I added to each activity this method:
public void onConfigurationChanged(Configuration newConfig) {
super.onConfigurationChanged(newConfig);
setContentView(R.layout.active_alt);
mColorLegendBtn = (Button) findViewById(R.id.colorbtn);
mStatusView = (TextView) findViewById(R.id.celltitle1);
TextView mStatusView1 = (TextView) findViewById(R.id.celltitle2);
mStatusView1.setText(mStatusView1.getText()+"testcase1");
mStatusView.setText(mStatusView.getText()+"testcase");
initUI();
}
public void initUI() {
l1 = (ListView) findViewById(R.id.ListView01);
EfficientAdapter efficientAdapter = new EfficientAdapter(mContext);
l1.setAdapter(null);
l1.setAdapter(efficientAdapter);
}
On launch, the tabs, list, button and textview are displayed correctly.
When I change the orientation in the emulator, only the tabs are displayed none of the other widgets, the screen is black.
What am I missing?
I had exactly this problem. After much trial and error, I eventually solved it by making a one-line change to the manifest.
The trick is to add
android:configChanges="orientation|keyboardHidden"
to your TabActivity's entry in the manifest. Leave all the child activities alone. Don't even bother implementing onConfigurationChanged(), not even in the TabActivity.
I don't know how or why this seems to work, but the effect is the layout is refreshed, and both the tabs and the child activity content are redrawn correctly in the new orientation.
With success I found that the best way to have screen changes with most control is to make your layout xml for landscape mode in a seperate xml like so:
res/layout-land/youractivity.xml
using /layout/ and /layout-land/ for your layouts as well as Graham Borland answer is golden.
<activity android:name=".MainActivity"
android:label="#string/app_name"
android:screenOrientation="unspecified"
android:launchMode="standard"
android:configChanges="orientation|keyboardHidden"
>
the above snippet is what made mine work. :)
ohh I do believe the "unspecified" is what allows the system to do what it thinks is best...
Good luck!
In Mono for Android with a target API greater then 13 I found that the line which would go inside the namespace but outside the Activity class:
[Activity (Label = "Viewer", ConfigurationChanges = ConfigChanges.Orientation|ConfigChanges.ScreenSize)]
lead to the triggering of OnConfigurationChanged() even though changing the manifest had not.
Could it just be that your layout doesn't work in the landscape/portrait mode? Try starting you app after rotating, check if that gives the same results. If so: fix your layout :D

Categories

Resources