NullPointerException when starting ListActivity - android

I'm working for hours on an error I get, when I want to start a ListActivity.
Short workaround about what I want to do:
I have a main application with a normal menu, from which I want to start a setting list where the user can add specific settings.
I'm trying to start the ListView like this:
startActivity(new Intent(this, FileManagerSettings.class));
Then in the on Create method I got the error:
userSettings = deserializeObject();
if(userSettings.isEmpty())
{
userSettings.add(new SettingItem("Camera", android.os.Environment.DIRECTORY_DCIM, false));
}
super.onCreate(icicle);
Context mContext = this.getApplicationContext();
settingsList = (ListView)findViewById(R.id.list_settings);
settingsList.setAdapter(new CustomSettingsAdapter(mContext, userSettings));
The last line causes the error. For better understanding here the Constructor of the adapter class:
public CustomSettingsAdapter(Context context, ArrayList<SettingItem> sitems)
{
settingsArrayList = sitems;
mInflater = LayoutInflater.from(context);
}
And here is the error from the logcat: (Sorry, don't know how to format it right)
04-01 11:07:26.756: ERROR/AndroidRuntime(375): FATAL EXCEPTION: main
04-01 11:07:26.756: ERROR/AndroidRuntime(375): java.lang.RuntimeException: Unable to start activity ComponentInfo{org.openintents.filemanager/org.openintents.filemanager.FileManagerSettings}: java.lang.NullPointerException
04-01 11:07:26.756: ERROR/AndroidRuntime(375): Caused by: java.lang.NullPointerException
04-01 11:07:26.756: ERROR/AndroidRuntime(375): at org.openintents.filemanager.FileManagerSettings.onCreate(FileManagerSettings.java:43)
In my thinking the error is caused because the LayoutInflater of the context is null... But I don't know how to get the LayoutInflater then and even don't know if this is really the error...
edit: error log with using setContentView():
04-01 12:06:56.315: ERROR/AndroidRuntime(669): FATAL EXCEPTION: main
04-01 12:06:56.315: ERROR/AndroidRuntime(669): java.lang.RuntimeException: Unable to start activity ComponentInfo{org.openintents.filemanager/org.openintents.filemanager.FileManagerSettings}: java.lang.RuntimeException: Your content must have a ListView whose id attribute is 'android.R.id.list'
this is the xml-File:
<LinearLayout android:layout_width="fill_parent"
android:id="#+id/list"
android:layout_height="fill_parent"
xmlns:android="http://schemas.android.com/apk/res/android">
<TextView android:id="#+id/settings_list_title"
android:layout_height="wrap_content"
android:layout_width="fill_parent"
android:text="#string/settings_header"
android:textAppearance="?android:attr/textAppearanceMedium"
android:gravity="center" />
<ListView android:id="#+id/list"
android:layout_width="wrap_content"
android:layout_height="wrap_content" />
</LinearLayout>

findViewById() only returns a valid reference to a View if the layout of the Activty has been set. Looking at the code you have pasted in to your question, it does not appear that you are making a call to
setContentView(R.layout.whatever_your_layout_file_id);
Your variable settingsList, would then be a null reference

Related

NullPointerException when using a ListView

I'm struggling to find the cause of a certain NullPointerException that's being thrown when I try to start a specific activity.
LogCat output:
12-11 13:29:28.211: E/AndroidRuntime(701): Caused by: java.lang.NullPointerException
12-11 13:29:28.211: E/AndroidRuntime(701): at android.content.res.AssetManager.getResourceTextArray(AssetManager.java:214)
12-11 13:29:28.211: E/AndroidRuntime(701): at android.content.res.Resources.getTextArray(Resources.java:361)
12-11 13:29:28.211: E/AndroidRuntime(701): at android.content.res.TypedArray.getTextArray(TypedArray.java:628)
12-11 13:29:28.211: E/AndroidRuntime(701): at android.widget.ListView.<init>(ListView.java:168)
12-11 13:29:28.211: E/AndroidRuntime(701): at android.widget.ListView.<init>(ListView.java:159)
12-11 13:29:28.211: E/AndroidRuntime(701): ... 25 more
onCreate() method of the activity in question:
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.display);
}
XML for the layout "display" that my activity is trying to load:
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:baselineAligned="false" >
<ListView
android:id="#+id/weekdayListView"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_weight="1" >
</ListView>
<ListView
android:id="#+id/timeSlotListView"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_weight="3"
android:entries="#layout/item_layout" >
</ListView>
</LinearLayout>
Other than what's in onCreate(), my activity doesn't do anything else. Since there's no code to populate the listviews (there was but I commented it out in trying to find the root of the problem), when the activity starts it should just be a blank screen.
When I comment out the section in the XML file relating to weekdayListView, the activity loads just fine, so I have to assume there's a problem with how I've set up the XML. The only difference I can see between the two is that I don't explicitly set the android:entries attribute, but if I understand it correctly, in this case it should just use the default.
I've been stuck on this for a while now so any help is greatly appreciated. I tried to provide as much information as I thought was relevant but if there's anything else I forgot to include, let me know.
Your android:entries attribute points to a layout when it should rather point to a string array resource.
Create a string array in your strings.xml, e.g.
<string-array name="vals">
<item>Foo</item>
<item>Bar</item>
</string-array>
and then use
android:entries="#string/vals"

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.

Android listview with header

I would like my screen to have a listview with a header.
In my XML file, I have a listview and just above it there is an imageview, which is being used as the header.
When I run this I get an error. I have gone through dozens of tutorials and I can't see what I am doing wrong. I have searched Stackoverflow and all tried the solutions but had no joy. Can anybody help me please?
Note: I am using Actionbarsherlock, so my class extends SherlockListActivity. I have tried this with ListActivity and get the same problem. I have also tried running without instantiating the image to see if the listview loads itself, and still I get the same error.
Please see my XML and code below:
My XML
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:orientation="vertical" >
<ImageView
android:id="#+id/headerimage"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:src="#drawable/header" >
</ImageView>
<ListView
android:id="#+id/mylist"
android:layout_width="match_parent"
android:layout_height="wrap_content" >
</ListView>
My code:
public class MainActivity extends SherlockListActivity {
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
ImageView header = (ImageView) findViewById(R.id.headerimage);
ListView listView = (ListView) findViewById(R.id.mylist);
String[] values = new String[] { "Android", "iPhone", "WindowsMobile",
"Blackberry", "WebOS", "Ubuntu", "Windows7", "Max OS X",
"Linux", "OS/2" };
ArrayAdapter<String> adapter = new ArrayAdapter<String>(this,
android.R.layout.simple_list_item_1, android.R.id.text1, values);
listView.addHeaderView(header);
listView.setAdapter(adapter);
}
Error log
E/AndroidRuntime(10642): FATAL EXCEPTION: main
E/AndroidRuntime(10642): java.lang.RuntimeException: Unable to start activity ComponentInfo{ttj.android.t3w/ttj.android.t3w.MainActivity}: java.lang.NullPointerException
E/AndroidRuntime(10642): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:1968)
E/AndroidRuntime(10642): at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:1993)
E/AndroidRuntime(10642): at android.app.ActivityThread.access$600(ActivityThread.java:127)
E/AndroidRuntime(10642): at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1159)
E/AndroidRuntime(10642): at android.os.Handler.dispatchMessage(Handler.java:99)
E/AndroidRuntime(10642): at android.os.Looper.loop(Looper.java:137)
E/AndroidRuntime(10642): at android.app.ActivityThread.main(ActivityThread.java:4507)
E/AndroidRuntime(10642): at java.lang.reflect.Method.invokeNative(Native Method)
E/AndroidRuntime(10642): at java.lang.reflect.Method.invoke(Method.java:511)
E/AndroidRuntime(10642): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:790)
E/AndroidRuntime(10642): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:557)
E/AndroidRuntime(10642): at dalvik.system.NativeStart.main(Native Method)
E/AndroidRuntime(10642): Caused by: java.lang.NullPointerException
E/AndroidRuntime(10642): at ttj.android.t3w.MainActivity.onCreate(MainActivity.java:40)
E/AndroidRuntime(10642): at android.app.Activity.performCreate(Activity.java:4465)
E/AndroidRuntime(10642): at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1052)
E/AndroidRuntime(10642): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:1932)
E/AndroidRuntime(10642): ... 11 more
Set header and set footer take an inflated layout. That means creating a seperate layout for the header and inflating it. Similar to set content view but the inflation does not happen automatically. One side not here but aparently you need to set the header and footer before setting the list adapter. When I get a minute I will try to post some code.
cstrutton is right. You're not calling setConentView
You should call setContentView(R.layout.xmlfilename) right after the call to super.onCreate(savedInstanceState);
Where xmlfilename is the name of your layout file
setContentView(id) should be used with list activities, and an activity incorporating a ListView ought to extend ListActivity or ListFragment (or an appropriate subclass).
In your comment to cstrutton, you state:
When I use setcontentview I get the following error:
E/AndroidRuntime(17767): Caused by: java.lang.RuntimeException: Your
content must have a ListView whose id attribute is 'android.R.id.list'
This is because your ListView has an incorrect id - in a ListActivity, there should be a maximum of one ListView represented in the associated layout file, and its id should be #android:id/list (presumably so that Android knows where the ListView is, though I'm unsure why it can't detect it from the element tag, perhaps for performance reasons it's just simpler to require a specific ID).
Change #+id/list to #android:id/list. (see this question for why it's #android:id rather than #+id)
I suppose there are other reasons to use a class extending ListActivity and a lot of them will be for convenience methods, but I suspect many are for optimisations.
Onwards and upwards!
FIXED.
The activity should NOT extend ListActivity. I changed it to Activity and the problem has gone.

NullPointerException When Switching between views

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?

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.

Categories

Resources