启动新活动时抛出NPE

时间:2014-04-02 05:53:04

标签: android nullpointerexception android-activity fragment

我有以下代码,这只是我的应用程序的UI的外壳。它成功加载,但是当在MainActivity中按下“Create Plot”按钮时 - 它应该启动CreatePlotActivity - 应用程序崩溃而不启动下一个活动。相反,NPE会被抛出。这是所有相关文件。注意:CreateOptionsFragment的第33行是list.setAdapter(adapter)

logcat的

04-02 02:33:53.005: E/AndroidRuntime(13555): FATAL EXCEPTION: main
04-02 02:33:53.005: E/AndroidRuntime(13555): java.lang.RuntimeException: Unable to start activity ComponentInfo{com.example.probaddieweaponplotter/com.example.probaddieweaponplotter.CreatePlotActivity}: java.lang.NullPointerException
04-02 02:33:53.005: E/AndroidRuntime(13555):    at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2180)
04-02 02:33:53.005: E/AndroidRuntime(13555):    at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2230)
04-02 02:33:53.005: E/AndroidRuntime(13555):    at android.app.ActivityThread.access$600(ActivityThread.java:141)
04-02 02:33:53.005: E/AndroidRuntime(13555):    at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1234)
04-02 02:33:53.005: E/AndroidRuntime(13555):    at android.os.Handler.dispatchMessage(Handler.java:99)
04-02 02:33:53.005: E/AndroidRuntime(13555):    at android.os.Looper.loop(Looper.java:137)
04-02 02:33:53.005: E/AndroidRuntime(13555):    at android.app.ActivityThread.main(ActivityThread.java:5041)
04-02 02:33:53.005: E/AndroidRuntime(13555):    at java.lang.reflect.Method.invokeNative(Native Method)
04-02 02:33:53.005: E/AndroidRuntime(13555):    at java.lang.reflect.Method.invoke(Method.java:511)
04-02 02:33:53.005: E/AndroidRuntime(13555):    at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:793)
04-02 02:33:53.005: E/AndroidRuntime(13555):    at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:560)
04-02 02:33:53.005: E/AndroidRuntime(13555):    at dalvik.system.NativeStart.main(Native Method)
04-02 02:33:53.005: E/AndroidRuntime(13555): Caused by: java.lang.NullPointerException
04-02 02:33:53.005: E/AndroidRuntime(13555):    at com.example.probaddieweaponplotter.PlotOptionsListFragment.onActivityCreated(PlotOptionsListFragment.java:33)
04-02 02:33:53.005: E/AndroidRuntime(13555):    at android.app.Fragment.performActivityCreated(Fragment.java:1703)
04-02 02:33:53.005: E/AndroidRuntime(13555):    at android.app.FragmentManagerImpl.moveToState(FragmentManager.java:903)
04-02 02:33:53.005: E/AndroidRuntime(13555):    at android.app.FragmentManagerImpl.moveToState(FragmentManager.java:1057)
04-02 02:33:53.005: E/AndroidRuntime(13555):    at android.app.FragmentManagerImpl.moveToState(FragmentManager.java:1039)
04-02 02:33:53.005: E/AndroidRuntime(13555):    at android.app.FragmentManagerImpl.dispatchActivityCreated(FragmentManager.java:1840)
04-02 02:33:53.005: E/AndroidRuntime(13555):    at android.app.Activity.performCreate(Activity.java:5107)
04-02 02:33:53.005: E/AndroidRuntime(13555):    at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1080)
04-02 02:33:53.005: E/AndroidRuntime(13555):    at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2144)
04-02 02:33:53.005: E/AndroidRuntime(13555):    ... 11 more

MainActivity.java

package com.example.probaddieweaponplotter;

import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;

public class MainActivity extends Activity implements OnClickListener {

    Button button;

    @Override
    protected void onCreate(Bundle savedInstanceState) {        
        super.onCreate(savedInstanceState);     
        setContentView(R.layout.activity_main);     
        button = (Button) findViewById(R.id.button_create_plot);
        button.setOnClickListener(this);
    }

    @Override
    public void onClick(View v) {                   
        Intent intent = new Intent(this, CreatePlotActivity.class);
        startActivity(intent);
    }
}

CreatePlotActivity.java

package com.example.probaddieweaponplotter;

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

public class CreatePlotActivity extends Activity {

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

PlotOptionsListFragment.java

package com.example.probaddieweaponplotter;

import java.util.ArrayList;

import android.app.Fragment;
import android.content.Context;
import android.content.res.Resources;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.ListView;
import android.widget.TextView;

public class PlotOptionsListFragment extends Fragment { 

    ListView listView;  

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
            Bundle savedInstanceState) {            
        return inflater.inflate(R.layout.fragment_plot_options_list,
                container, false);


    }   

    @Override
    public void onActivityCreated(Bundle savedInstanceState) {
        // TODO Auto-generated method stub
        super.onActivityCreated(savedInstanceState);
        listView = (ListView) getActivity().findViewById(R.id.plot_options_listView);       
        MyAdapter adapter = new MyAdapter(getActivity());
        listView.setAdapter(adapter);           
    }

}

class MyAdapter extends BaseAdapter {

    ArrayList<PlotOptionsListItem> list;
    Context context;

    public MyAdapter(Context context) {
        // TODO Auto-generated constructor stub
        this.context = context;
        list = new ArrayList<PlotOptionsListItem>();

        Resources res = context.getResources();
        String[] items = res.getStringArray(R.array.plot_options_list_items);
        String[] descriptions = res.getStringArray(R.array.plot_options_list_descriptions);

        for (int i = 0; i < items.length; i++) {
            list.add(new PlotOptionsListItem(items[i], descriptions[i]));
        }
    }

    @Override
    public int getCount() {
        // TODO Auto-generated method stub
        return list.size();
    }

    @Override
    public Object getItem(int position) {
        // TODO Auto-generated method stub
        return list.get(position);
    }

    @Override
    public long getItemId(int position) {
        // TODO Auto-generated method stub
        return position;
    }

    @Override
    public View getView(int position, View convertView, ViewGroup parent) {
        // TODO Auto-generated method stub
        LayoutInflater inflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
        View row = inflater.inflate(R.layout.plot_options_list_single_item, parent, false);
        TextView item = (TextView) row.findViewById(R.id.plot_options_list_item_text);
        TextView description = (TextView) row.findViewById(R.id.plot_options_list_desc_text);

        PlotOptionsListItem temp = list.get(position);

        item.setText(temp.getItem());
        description.setText(temp.getDescription());

        return row;
    }

}

class PlotOptionsListItem {

    private String item;
    private String description;

    public PlotOptionsListItem(String item, String description) {
        // TODO Auto-generated constructor stub
        this.setItem(item);
        this.setDescription(description);
    }

    public String getItem() {
        return item;
    }

    public void setItem(String item) {
        this.item = item;
    }

    public String getDescription() {
        return description;
    }

    public void setDescription(String description) {
        this.description = description;
    }
}

activity_main.xml中

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"   
    android:id="@+id/container"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:gravity="center"
    android:orientation="vertical" >

    <ImageView
           android:contentDescription="@string/activity_main_cover_image_desc"
           android:id="@+id/imageView1"
           android:layout_weight="1"
           android:layout_width="match_parent"
           android:layout_height="match_parent"       
           android:layout_margin="@dimen/activity_horizontal_margin"
           android:src="@drawable/ic_launcher" />

    <RelativeLayout android:id="@+id/activity_main_button_layout"
        android:layout_weight="1"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:orientation="vertical">

        <Button
            android:id="@+id/button_create_plot"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:layout_alignParentTop="true"
            android:layout_marginLeft="@dimen/activity_horizontal_margin"
            android:layout_marginRight="@dimen/activity_horizontal_margin"
            android:layout_marginTop="@dimen/activity_horizontal_margin_half"
            android:layout_marginBottom="@dimen/activity_horizontal_margin"
            android:layout_centerHorizontal="true"
            android:text="@string/button_create_plot" />

        <Button
            android:id="@+id/button_view_gallery"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"            
            android:layout_below="@+id/button_create_plot"
            android:layout_marginLeft="@dimen/activity_horizontal_margin"
            android:layout_marginRight="@dimen/activity_horizontal_margin"
            android:text="@string/button_view_gallery" />

        <Button
            android:id="@+id/button_help_faq"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"            
            android:layout_below="@+id/button_view_gallery"
            android:layout_marginLeft="@dimen/activity_horizontal_margin"
            android:layout_marginRight="@dimen/activity_horizontal_margin"
            android:text="@string/button_help_faq" />

        <Button
            android:id="@+id/button_advanced_settings"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"            
            android:layout_below="@+id/button_help_faq"
            android:layout_marginLeft="@dimen/activity_horizontal_margin"
            android:layout_marginRight="@dimen/activity_horizontal_margin"
            android:text="@string/button_advanced_settings" />

    </RelativeLayout>

</LinearLayout>

activity_create_plot.xml

<?xml version="1.0" encoding="utf-8"?>
<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" >

    <fragment
        android:id="@+id/fragment_plot_options_list"
        android:name="com.example.probaddieweaponplotter.PlotOptionsListFragment"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_alignParentBottom="true"
        android:layout_alignParentTop="true"
        android:layout_centerHorizontal="true" />

    <fragment
        android:id="@+id/fragment_generate_plot_button"
        android:name="com.example.probaddieweaponplotter.GeneratePlotButtonFragment"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_alignParentBottom="true"
        android:layout_centerHorizontal="true"
        tools:layout="@layout/fragment_plot_options_detail" />

</RelativeLayout>

fragment_plot_options_list.xml

<?xml version="1.0" encoding="utf-8"?>
<ListView xmlns:android="http://schemas.android.com/apk/res/android"   
    android:layout_width="match_parent"
    android:id="@+id/plot_options_listView"
    android:layout_height="match_parent"
    android:orientation="vertical" >          
</ListView>

plot_options_list_single_item.xml

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent" >

    <TextView
        android:id="@+id/plot_options_list_item_text"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignParentLeft="true"
        android:layout_alignParentTop="true"
        android:text=""
        android:textAppearance="?android:attr/textAppearanceMedium" />

    <TextView
        android:id="@+id/plot_options_list_desc_text"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignParentLeft="true"
        android:layout_below="@+id/plot_options_list_item_text"
        android:text=""
        android:textAppearance="?android:attr/textAppearanceSmall" />

</RelativeLayout>

最后,我的AndroidManifest.xml

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.example.probaddieweaponplotter"
    android:versionCode="1"
    android:versionName="1.0" >

    <uses-sdk
        android:minSdkVersion="11"
        android:targetSdkVersion="19" />

    <application
        android:allowBackup="true"
        android:icon="@drawable/ic_launcher"
        android:label="@string/app_name" >
        <activity
            android:name="com.example.probaddieweaponplotter.MainActivity"
            android:label="@string/app_name" >
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />

                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
        <activity
            android:name="com.example.probaddieweaponplotter.CreatePlotActivity"
            android:label="@string/title_activity_create_plot"
            android:parentActivityName="com.example.probaddieweaponplotter.MainActivity" >
            <meta-data
                android:name="android.support.PARENT_ACTIVITY"
                android:value="com.example.probaddieweaponplotter.MainActivity" />
        </activity>
    </application>

</manifest>

3 个答案:

答案 0 :(得分:1)

试试这个..

@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
        Bundle savedInstanceState) {        
    View v =  inflater.inflate(R.layout.fragment_plot_options_list,
            container, false);
    listView = (ListView) v.findViewById(R.id.plot_options_listView);     
    return v;


}   

@Override
public void onActivityCreated(Bundle savedInstanceState) {
    // TODO Auto-generated method stub
    super.onActivityCreated(savedInstanceState);

    MyAdapter adapter = new MyAdapter(getActivity());
    listView.setAdapter(adapter);           
}

答案 1 :(得分:0)

ListView属于Fragment布局。因此,请getView()中的onActivityCreated初始化ListView

您可以使用getActivity()初始化Fragment中的Activity视图,而这不是您想要的。

更改此

listView = (ListView) getActivity().findViewById(R.id.plot_options_listView);       

listView = (ListView) getView().findViewById(R.id.plot_options_listView);       

答案 2 :(得分:0)

以为你应该知道原因:

您的listview片段的布局为R.layout.fragment_plot_options_list

在返回夸大的布局之前,您需要findViewById来自fragment_plot_options_list.xml

 return inflater.inflate(R.layout.fragment_plot_options_list,
                container, false);  

致电时

 listView = (ListView) getActivity().findViewById(R.id.plot_options_listView);  
onActivityCreated

,就像在没有调用setContentView()的情况下在活动中调用相同的内容,这样您就可以获得NPE。