NullPointerException When Switching between views - android

Some users are getting this error.
I use a viewgroup to continuously display a banner add.
I then use child views for the program and switch back and forth between views as the user clicks a button.
I can cause a crash by switching back and forth between child views 6 to 10 times.
Here is the layout for the viewgroup:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:myapp="http://schemas.android.com/apk/res/com.company.programname"
xmlns:app="http://schemas.android.com/apk/res/com.adwhirl"
android:orientation="vertical"
android:background="#color/darkslategrey"
android:id="#+id/LinearLayout01"
android:layout_width="fill_parent"
android:layout_height="fill_parent">
<com.adwhirl.AdWhirlLayout
android:id="#+id/adwhirl_layout"
android:gravity="center"
android:layout_width="fill_parent"
android:layout_height="52dp"
/>
</LinearLayout>
Here is the code creating the ViewGroup:
setContentView(R.layout.viewgrouplayout);
llLinLay=(LinearLayout)findViewById(R.id.LinearLayout01);
liInflater=(LayoutInflater)getSystemService(Context.LAYOUT_INFLATER_SERVICE);
Here is the main child layout with irrelevent pieces cut out:
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout
android:id="#+id/MainLayout"
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent">
<Button
android:id="#+id/MainShowAllDesiredButton"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="#id/AnotherButton"
android:layout_toRightOf="#id/AButton"
android:textSize="15sp"
android:text="Show All Desired"
android:onClick="MainDesired"
/>
<ListView
android:id="#+id/ItemTypeList"
android:background="#color/aqua"
android:cacheColorHint="#color/aqua"
android:fastScrollEnabled="true"
android:layout_width="fill_parent"
android:layout_height="160dip"
android:layout_below="#id/SomeItem"
/>
</RelativeLayout>
Here is an example of the code creating a view:
vAllDesired=liInflater.inflate(R.layout.alldesiredlayout,null);
vAllDesired.setId(7);
llLinLay.addView(vAllDesired);
final ListView lvAllDesired = (ListView)findViewById(R.id.AllDesiredList);
laAllDesiredAdapter = new AllDesiredListAdapter(this, alAllDesired);
lvAllCoinsDesired.setAdapter(laAllDesiredAdapter);
ViewGroup.LayoutParams AllDesiredParams = lvAllCoinsDesired.getLayoutParams();
AllDesiredParams.height = AllCoinsDesiredHeight;
lvAllCoinsDesired.setLayoutParams(AllDesiredParams);
FillAllDesiredArray();
Here is an example of the code used to switch between views:
bReturnToMainScreen = (Button) findViewById(R.id.DesiredReturnToMainScreenButton);
bReturnToMainScreen.setOnClickListener(new View.OnClickListener(){
#Override
public void onClick(View V) {
llLinLay.removeView(vAllDesired);
MainWindow();
}
});
Here is the trace from Android Developer website. The line number in the program is not always the same.
java.lang.NullPointerException
at android.webkit.WebView.requestFocus(WebView.java:6113)
at android.view.ViewGroup.onRequestFocusInDescendants(ViewGroup.java:1073)
at android.view.ViewGroup.requestFocus(ViewGroup.java:1029)
at android.view.ViewGroup.onRequestFocusInDescendants(ViewGroup.java:1073)
at android.view.ViewGroup.requestFocus(ViewGroup.java:1029)
at android.view.ViewGroup.onRequestFocusInDescendants(ViewGroup.java:1073)
at android.view.ViewGroup.requestFocus(ViewGroup.java:1029)
at android.view.ViewGroup.onRequestFocusInDescendants(ViewGroup.java:1073)
at android.view.ViewGroup.requestFocus(ViewGroup.java:1029)
at android.view.ViewGroup.onRequestFocusInDescendants(ViewGroup.java:1073)
at android.view.ViewGroup.requestFocus(ViewGroup.java:1029)
at android.view.ViewGroup.onRequestFocusInDescendants(ViewGroup.java:1073)
at android.view.ViewGroup.requestFocus(ViewGroup.java:1032)
at android.view.View.requestFocus(View.java:3559)
at android.view.ViewRoot.clearChildFocus(ViewRoot.java:1586)
at android.view.ViewGroup.clearChildFocus(ViewGroup.java:508)
at android.view.ViewGroup.clearChildFocus(ViewGroup.java:508)
at android.view.ViewGroup.clearChildFocus(ViewGroup.java:508)
at android.view.ViewGroup.clearChildFocus(ViewGroup.java:508)
at android.view.ViewGroup.removeViewInternal(ViewGroup.java:2207)
at android.view.ViewGroup.removeViewInternal(ViewGroup.java:2181)
at android.view.ViewGroup.removeView(ViewGroup.java:2129)
at com.jimbobga.mycoinsus.ProgramName$8.onClick(ProgramName.java:488)
at android.view.View.performClick(View.java:2411)
at android.view.View$PerformClick.run(View.java:8819)
at android.os.Handler.handleCallback(Handler.java:587)
at android.os.Handler.dispatchMessage(Handler.java:92)
at android.os.Looper.loop(Looper.java:123)
at android.app.ActivityThread.main(ActivityThread.java:4627)
at java.lang.reflect.Method.invokeNative(Native Method)
at java.lang.reflect.Method.invoke(Method.java:521)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:868)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:626)
at dalvik.system.NativeStart.main(Native Method)

Just curious, when you're making your calls to findViewById, are they in the OnCreate method or directly where you're inflating the row in the adapter? As it relates to your example here, the findViewById method is only guaranteed to work in the OnCreate method or where the particular row is inflated, so its possible that calling it elsewhere could cause unexpected behavior.

Look at this line:
at com.jimbobga.mycoinsus.ProgramName$8.onClick(ProgramName.java:488)
If this is happening after orientation has changed and views have not been assigned then you have a problem.

I'm experiencing the same issue.
Take a look at this response: Issues With Adwhirl(Admob+Inmobi+..)
Eric from AdMob staff says that it's a problem with the Android framework.
Did you try to surround your OnClick() code with a: try/catch Throwable Exception?

Related

NullPointerException error while adding fragment

I am having problem with implementing barcodefragmentlibv2 into my project. As a name says and from previous experience I know that I can add it into fragment. However, I am still getting NullPointerException error when I am trying to get this fragment to work with my app.
This is a part of a code responsible for barcode fragment:
import android.support.v4.app.Fragment;
//...
public class CameraFragment extends Fragment implements IScanResultHandler {
BarcodeFragment fragment;
public static CameraFragment newInstance() {
CameraFragment fragment = new CameraFragment();
return fragment;
}
public CameraFragment() {
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.include_qrfragment, container, false);
fragment = (BarcodeFragment)getActivity().getSupportFragmentManager().findFragmentById(R.id.sample);
fragment.setScanResultHandler(this);
return view;
}
//...
}
Error appears in line:
fragment.setScanResultHandler(this);
I've also tried replacing
getActivity().getSupportFragmentManager().findFragmentById(R.id.sample);
to
getFragmentManager().findFragmentById(R.id.sample);
but the result is this same.
Below are layout files:
fragment_camera
<FrameLayout 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" tools:context=".CameraFragment">
<include
android:layout_width="match_parent"
android:layout_height="match_parent"
layout="#layout/include_qrfragment" />
<TextView
android:id="#+id/status_view"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="bottom|center_horizontal"
android:layout_margin="15dp"
android:background="#99FFFFFF"
android:gravity="center"
android:padding="10dp"
android:text="#string/msg_default_status"
android:textAppearance="?android:attr/textAppearanceMedium" />
<View
android:layout_width="match_parent"
android:layout_height="match_parent" />
</FrameLayout>
include_qrfragment
<?xml version="1.0" encoding="utf-8"?>
<fragment xmlns:android="http://schemas.android.com/apk/res/android"
android:id="#+id/sample"
android:name="com.abhi.barcode.frag.libv2.BarcodeFragment"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_alignParentTop="true"
android:layout_centerHorizontal="true" />
At the beginning I've mentioned that from my own experience that this is possible. The truth is that I've built app utilizing this feature some time ago using eclipse and now I am using Android Studio - maybe there is a problem?
EDIT 1:
This is the whole error's stack trace:
06-22 23:05:56.804 30578-30578/myapp.com.test E/AndroidRuntime﹕ FATAL EXCEPTION: main
java.lang.NullPointerException
at myapp.com.test.CameraFragment.onCreateView(CameraFragment.java:34)
at android.support.v4.app.Fragment.performCreateView(Fragment.java:1789)
at android.support.v4.app.FragmentManagerImpl.moveToState(FragmentManager.java:955)
at android.support.v4.app.FragmentManagerImpl.moveToState(FragmentManager.java:1138)
at android.support.v4.app.BackStackRecord.run(BackStackRecord.java:740)
at android.support.v4.app.FragmentManagerImpl.execPendingActions(FragmentManager.java:1501)
at android.support.v4.app.FragmentManagerImpl$1.run(FragmentManager.java:458)
at android.os.Handler.handleCallback(Handler.java:587)
at android.os.Handler.dispatchMessage(Handler.java:92)
at android.os.Looper.loop(Looper.java:130)
at android.app.ActivityThread.main(ActivityThread.java:3683)
at java.lang.reflect.Method.invokeNative(Native Method)
at java.lang.reflect.Method.invoke(Method.java:507)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:839)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:597)
at dalvik.system.NativeStart.main(Native Method)
The problem seems to lie in this line:
fragment = (BarcodeFragment)getActivity().getSupportFragmentManager().findFragmentById(R.id.sample);
Your fragment is not yet appended to the activity as getActivity() is null at this point.
Perhaps you should move that particular code to onActivityCreated
You should only inflate the layout at the CreateView, like this:
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
return inflater.inflate(R.layout.your_layout, null);
}
The rest of your code, you should put it in the onActivityCreated as #waqaslam said.
You are getting a null pointer because there is no layout inflated yet.
I have read your responses, and now I am assuming you have tried or moved code of getActivity().getSupportFragmentManager().findFragmentById into onActivityCreated.
The only suspect I see without loading up your project is the GUI ID itself. You named it sample or R.id.sample, which is a suspect in some projects. It is possible that you have another UI element having the same name/ID. If so, that UI cannot be converted to a fragment. My suggestion is to change the name of the ID (with unique name), and use it with findFragmentById().

Accessibility related exception when using StreetViewPanoramaFragment

My app has an StreetViewPanoramaFragment in a framelayout above a SupportMapFragment and I dynamically show the street view when someone clicks a location marker on the map.
In my bug tracking system I saw a lot of crashes related to accessibility and I was able to reproduce the same crash when I turned on 'Talkback' in the accessibility settings.
The exception:
java.lang.RuntimeException: Callbacks must set parent bounds in populateNodeForVirtualViewId()
at iv.a(SourceFile:56)
at iw.a(SourceFile:716)
at hq.a(SourceFile:112)
at hw.createAccessibilityNodeInfo(SourceFile:42)
at android.view.AccessibilityInteractionController$AccessibilityNodePrefetcher.prefetchAccessibilityNodeInfos(AccessibilityInteractionController.java:724)
at android.view.AccessibilityInteractionController.findAccessibilityNodeInfoByAccessibilityIdUiThread(AccessibilityInteractionController.java:147)
at android.view.AccessibilityInteractionController.access$300(AccessibilityInteractionController.java:49)
at android.view.AccessibilityInteractionController$PrivateHandler.handleMessage(AccessibilityInteractionController.java:971)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:136)
at android.app.ActivityThread.main(ActivityThread.java:5140)
at java.lang.reflect.Method.invokeNative(Native Method)
at java.lang.reflect.Method.invoke(Method.java:515)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:795)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:611)
at dalvik.system.NativeStart.main(Native Method)
The relevant layout part:
<FrameLayout
android:id="#+id/places_map_holder"
android:layout_width="match_parent"
android:layout_weight=".45"
android:layout_height="0dp">
<fragment
android:id="#+id/places_map"
android:layout_width="match_parent"
android:layout_height="match_parent"
class="com.google.android.gms.maps.SupportMapFragment"
android:paddingTop="8dp"
android:paddingLeft="8dp"
android:paddingRight="8dp"
android:paddingBottom="32dp"
map:cameraTilt="30" />
<fragment
android:id="#+id/streetviewpanorama"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:visibility="gone"
class="com.google.android.gms.maps.SupportStreetViewPanoramaFragment" />
</FrameLayout>
The show/hide relevant code code:
FragmentTransaction ft = getFragmentManager().beginTransaction();
ft.setCustomAnimations(R.anim.slide_down, R.anim.fade_out,
R.anim.slide_down, R.anim.fade_out);
if (show) {
ft.show(mSvpFragment);
} else {
ft.hide(mSvpFragment);
}
// commit and etc
Has anyone encountered this problem ? Any solution anyone ?
Using attributes
android:accessibilityLiveRegion="none"
android:importantForAccessibility="no"
for StreetViewPanoramaFragment's container (probably will work with the direct applying to the PanoramaFragment or PanoramaView) in addition to hiding the container when talkback enabled works for me.

Android: why is my linearlayout crashing when switching at runtime?

when user presses a button i would like to switch to the 'details' layout which is like this:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:id="#+id/layoutDetails"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical" >
<TextView android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textStyle="bold"
android:textSize="16dp"
android:textColor="#ff0000"
android:text="Category" />
<TextView android:id="#+id/tv_category"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textSize="16dp"
android:layout_marginLeft="10dp" />
</LinearLayout>
and this is how i am trying to switch it:
switch(item.getItemId())
{
case ID_DETAILS:
// show new layout to for details
LinearLayout detailsLayout = (LinearLayout) findViewById(R.id.layoutDetails);
LayoutInflater detailsvi = (LayoutInflater) getSystemService(Context.LAYOUT_INFLATER_SERVICE);
View detailsv = detailsvi.inflate(R.layout.activity_details, null);
// IT CRASHES ON THIS LINE
detailsLayout.addView(detailsv,new LinearLayout.LayoutParams(detailsLayout.getLayoutParams().width, detailsLayout.getLayoutParams().height));
return true;
}
It gives a null pointer exception error!!!
08-09 17:23:47.146: E/AndroidRuntime(1572): FATAL EXCEPTION: main
08-09 17:23:47.146: E/AndroidRuntime(1572): java.lang.NullPointerException
Here is how you solve this:
1) put a breakpoint on the crashline and run in debug mode. You can immediately see if detailsLayout is null or not. If not do step 2 Also check if detailsv is null.
2) details
Object o1 = etailsLayout.getLayoutParams(); // check if this is null.
It has to be one or the other.
Update: Since its detailsLayout is in fact null. It must be that either
1) setContentView was not called prior to requsting detailsLayout, or
2) setContentView was set to a layout that did not define detailsLayout, or
3) setContentView was called correctly but detailsLayout is not correctly id in that layout file.
It must be one of these three.

Views in a RelativeLayout with MapView are null

I have a MapActivity with a mapview. It works fine. Now I want to add a SeekBar onto my MapView. It has to be at the bottom but on the mapview. User will scroll to set the distance. Whatever. My problem is, that any view I am trying to put there is null, when I reach them by findViewById().
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent">
<com.google.android.maps.MapView
xmlns:android="http://schemas.android.com/apk/res/android"
android:id="#+id/mapview"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:clickable="true"
android:apiKey="mykey"/>
<SeekBar
android:id="#+id/DistanceBar"
android:max="2000"
android:progress="2000"
android:layout_alignParentBottom="true"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:padding="14dip"></SeekBar>
</RelativeLayout>
I am trying to reach that like this:
public class MyActivity extends MapActivity implements LocationListener {
...
SeekBar DistanceBar;
...
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
mapView = (MapView) findViewById(R.id.mapview);
DistanceBar = (SeekBar) findViewById(R.id.DistanceBar); //This is afterwards null.
I have made a research everywhere and couldn't find a similar problem. Someone used something very similar. So I ignored that it is null, I didn't call the SeekBar in onCreate(). But the SeekBar hasn't been drawen at all. Can't I add other Views to a mapactivity?
Thanks for any idea!
An IMPORTANT EDIT: The graphical layout viewer shows the SeekBar as it should at the bottom of mapview.
I still get NullPointerException:
ERROR/AndroidRuntime(12738): FATAL EXCEPTION: main
ERROR/AndroidRuntime(12738): java.lang.RuntimeException: Unable to start activity ComponentInfo{com.MyApps.MapLocations/com.MyApps.MapLocations.MyActivity}: java.lang.NullPointerException
ERROR/AndroidRuntime(12738): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2663)
ERROR/AndroidRuntime(12738): at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2679)
ERROR/AndroidRuntime(12738): at android.app.ActivityThread.access$2300(ActivityThread.java:125)
ERROR/AndroidRuntime(12738): at android.app.ActivityThread$H.handleMessage(ActivityThread.java:2033)
ERROR/AndroidRuntime(12738): at android.os.Handler.dispatchMessage(Handler.java:99)
ERROR/AndroidRuntime(12738): at android.os.Looper.loop(Looper.java:123)
ERROR/AndroidRuntime(12738): at android.app.ActivityThread.main(ActivityThread.java:4627)
ERROR/AndroidRuntime(12738): at java.lang.reflect.Method.invokeNative(Native Method)
ERROR/AndroidRuntime(12738): at java.lang.reflect.Method.invoke(Method.java:521)
ERROR/AndroidRuntime(12738): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:871)
ERROR/AndroidRuntime(12738): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:629)
ERROR/AndroidRuntime(12738): at dalvik.system.NativeStart.main(Native Method)
ERROR/AndroidRuntime(12738): Caused by: java.lang.NullPointerException
ERROR/AndroidRuntime(12738): at com.MyApps.MapLocations.MyActivity.setupSeekbar(MyActivity.java:343)
ERROR/AndroidRuntime(12738): at com.MyApps.MapLocations.MyActivity.onCreate(MyActivity.java:89)
ERROR/AndroidRuntime(12738): at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1047)
ERROR/AndroidRuntime(12738): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2627)
ERROR/AndroidRuntime(12738): ... 11 more
Here is the result from HierarchyViewer:
Can't I add other Views to a mapactivity?
Yes, you can.
Clean your project (Project -> Clean from the Eclipse main menu or ant clean at the command line). Then use Hierarchy View to see what is going on. It sounds like either your IDs are off kilter (in which case the clean will help) or perhaps you failed to save the XML or something.
I just have copied the main.xml file as map.xml and deleted main.xml. And it worked. I still don't understand why it happened. Maybe the "main" causes some problem. Maybe MapActivities have defined for themselves a "main" layout which is interrupting my "main" layout. But this was the solution somehow. Thanks a lot for your patience!
IMPORTANT EDIT: I have definitely found the problem. main.xml file remained in layout-normal and layout-normal-long folders without any SeekBar. I forgot to edit those.

TextView inside a LinearLayout, crash with a long string

Using Android, here is part of a layout xml file:
<LinearLayout
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:orientation="vertical"
android:textColor="#191919">
<TextView android:id="#+id/someTextField"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_weight="1"
android:textStyle="bold" />
<TextView android:id="#+id/anotherTextField"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_weight="1" />
</LinearLayout>
I am adding this view (at runtime) to a ViewAnimator like this:
ViewAnimator viewAnimator = (ViewAnimator)findViewById(R.id.viewAnimator);
View newView = View.inflate(this, R.layout.new_view, null);
viewAnimator.addView(newView);
viewAnimator.showNext();
String newValue = "new value for the text field";
findViewById(R.id.deal_view).setVisibility(View.VISIBLE);
TextView someTextField = (TextView)findViewById(R.id.someTextField);
someTextField.setText(newValue);
This seems to be working fine, but when newValue is long enough to take more than 1 line of text in the layout, I am getting a crash:
09-06 21:36:48.208: ERROR/AndroidRuntime(6561): Uncaught handler: thread main exiting due to uncaught exception
09-06 21:36:48.248: ERROR/AndroidRuntime(6561): java.lang.StackOverflowError
09-06 21:36:48.248: ERROR/AndroidRuntime(6561): at android.view.ViewGroup.drawChild(ViewGroup.java:1486)
09-06 21:36:48.248: ERROR/AndroidRuntime(6561): at android.view.ViewGroup.dispatchDraw(ViewGroup.java:1228)
(many more lines like this)
Is this enough information to see what I might be doing wrong? It works perfectly fine when newValue is short enough for one line. I've thought about trying a TableLayout but it seems like this is exactly what a LinearLayout is good for.
Thanks for the help in the comments. I ended up taking the advice here (dropping ViewAnimator directly and using ViewFlipper). Better app, but still the same problem. I dropped one level of LinearLayout containers and it started working fine.
I'm assuming bhatt4982 is right, UI depth was too great.
bhatt4982, post your comment as an answer to get credit for this.

Categories

Resources