findviewbyid的nullpointerexcetion

时间:2014-02-02 09:08:10

标签: java android android-fragments imageview

我正在尝试构建一个简单的应用程序,从我的电脑上下载一个png文件对其进行解码并将其设置在按钮按下后开始的新活动的图像视图中。

与网络有关的一切,以及文件的解码似乎都能正常工作,但是当我使用“findviewbyid”时,我似乎遇到了很多错误,(android studio)它建议正确的id但是当我运行它,抛出异常并且应用程序崩溃。

(在android studio中创建一个新活动时,会创建一个占位符片段。我应该在片段的OncreateView中编写代码吗?)

活动xml:

<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:id="@+id/container"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context="com.example.app.show"
tools:ignore="MergeRootFrame" />

片段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"
android:paddingLeft="@dimen/activity_horizontal_margin"
android:paddingRight="@dimen/activity_horizontal_margin"
android:paddingTop="@dimen/activity_vertical_margin"
android:paddingBottom="@dimen/activity_vertical_margin"
tools:context="com.example.app.show$PlaceholderFragment">

<ImageView
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:id="@+id/fromaster"
    android:layout_centerVertical="true"
    android:layout_centerHorizontal="true" />
</RelativeLayout>

java code(onCreate):

public class show extends Activity {

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_show);
    ImageView v;
    v = (ImageView) findViewById(R.id.fromaster);
    byte[] raw;

    if (v == null){Log.d("at view","empty");}

    raw = getIntent().getByteArrayExtra("pic");

    Bitmap bitmap = BitmapFactory.decodeByteArray(raw,0,raw.length);
    if (bitmap == null){
        Toast.makeText(getApplicationContext(),"empty      bitmap",Toast.LENGTH_SHORT).show();
    }
    else{
        try{
            v.setImageBitmap(bitmap);}
        catch (Exception e){
            Log.d("at setting bitmap","error",e);
        }
    }


    if (savedInstanceState == null) {
        getFragmentManager().beginTransaction()
                .add(R.id.container, new PlaceholderFragment())
                .commit();
    }
}

logcat:

02-02 10:48:34.330  21950-21950/com.example.app E/FragmentManager﹕ No view found for id 0x7f080000 (com.example.app:id/container) for fragment PlaceholderFragment{41bd5c38 #0 id=0x7f080000}

编辑:我使用了片段的OncreateView,使用findviewbyid时仍然是个例外:

java代码:

 public View onCreateView(LayoutInflater inflater, ViewGroup container,
            Bundle savedInstanceState) {
        View rootView = inflater.inflate(R.layout.fragment_show, container, false);

        ImageView v = (ImageView) getView().findViewById(R.id.fromaster);
        byte[] raw;

        if (v == null){Log.d("at view","empty");}

        raw = getArguments().getByteArray("pic");

        Bitmap bitmap = BitmapFactory.decodeByteArray(raw,0,raw.length);
        if (bitmap == null){
            Toast.makeText(getActivity().getApplicationContext(),"empty bitmap",Toast.LENGTH_SHORT).show();
        }
        else{
            try{
                v.setImageBitmap(bitmap);}
            catch (Exception e){
                Log.d("at setting bitmap","error",e);
            }
        }

        return rootView;
    }
}

logcat错误:

02-02 11:29:24.335  25479-25479/com.example.app E/AndroidRuntime﹕ FATAL EXCEPTION: main
Process: com.example.app, PID: 25479
java.lang.RuntimeException: Unable to start activity ComponentInfo{com.example.app/com.example.app.show}: java.lang.NullPointerException
        at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2215)
        at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2265)
        at android.app.ActivityThread.access$800(ActivityThread.java:145)
        at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1206)
        at android.os.Handler.dispatchMessage(Handler.java:102)
        at android.os.Looper.loop(Looper.java:136)
        at android.app.ActivityThread.main(ActivityThread.java:5081)
        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:781)
        at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:597)
        at dalvik.system.NativeStart.main(Native Method)
 Caused by: java.lang.NullPointerException
        at com.example.app.show$PlaceholderFragment.onCreateView(show.java:69)
        at android.app.Fragment.performCreateView(Fragment.java:1700)
        at android.app.FragmentManagerImpl.moveToState(FragmentManager.java:890)
        at android.app.FragmentManagerImpl.moveToState(FragmentManager.java:1062)
        at android.app.BackStackRecord.run(BackStackRecord.java:684)
        at android.app.FragmentManagerImpl.execPendingActions(FragmentManager.java:1447)
        at android.app.Activity.performStart(Activity.java:5240)
        at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2178)

1 个答案:

答案 0 :(得分:1)

activity_show.xml没有ImageView

ImageView位于fragment.xmlfindViewById在当前膨胀的布局中查找视图。因此,如果您findViewById返回null,那么您为视图引用了错误的id,或者您没有在xml中提供充气的视图。

我的猜测是你的活动有一个framelayout,它是你添加或替换framents的容器。 ImageView的初始化应该转到Fragment的onCreateView,并且您需要将show活动添加到FrameLayout

编辑:

View rootView = inflater.inflate(R.layout.fragment_show, container, false);
ImageView v = (ImageView) rootView.findViewById(R.id.fromaster);