【问题标题】:java code doesn't work in fragment activityjava代码在片段活动中不起作用
【发布时间】:2014-02-09 14:10:09
【问题描述】:

我尝试在 android 平台上创建一个包含 3 个片段的应用程序

当我尝试在片段类中输入一些 java 代码时,我总是出现这个错误: java.lang.NullPointerException

例如,用一个简单的按钮来改变视图:

package com.test;



import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentTransaction;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.Button;

public class creation extends Fragment {


    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {

         View root = inflater.inflate(R.layout.creation, container, false);

        final Button ok = (Button)getView(). findViewById(R.id.button3);
        ok.setOnClickListener(new OnClickListener() {

            @Override
            public void onClick(View v) {
                // Create new fragment and transaction
                Fragment newFragment = new mesvideos();
                // consider using Java coding conventions (upper char class names!!!)
                FragmentTransaction transaction = getFragmentManager().beginTransaction();

                // Replace whatever is in the fragment_container view with this fragment,
                // and add the transaction to the back stack
                transaction.replace(R.layout.creation, newFragment);
                transaction.addToBackStack(null);

                // Commit the transaction
                transaction.commit(); 


        }
    });
return root ;
}

或者使用VideoView

mVideoView = (VideoView) findViewById(R.id.videoView1);
             mVideoView.setVideoURI(Uri.parse("android.resource://" + getPackageName() +
                        "/" + R.raw.presentation));
             mVideoView.setMediaController(new MediaController(this));
             mVideoView.requestFocus();

【问题讨论】:

  • 粘贴完整的堆栈跟踪(复制logcat中存在错误的部分)
  • 该错误告诉您它发生的确切行。该行中有 99% 的情况是 .. 前面的东西是null。在你的情况下getView()

标签: java android android-fragments android-videoview


【解决方案1】:

不要只是说您遇到 NullPointerException,请指定完整的堆栈跟踪或告诉我们 NPE 发生在您的代码的哪一行。

FWIW,你的

final Button ok = (Button)getView(). findViewById(R.id.button3);

应该是

final Button ok = (Button) root.findViewById(R.id.button3);

我怀疑由于您刚刚创建了根视图并且尚未返回/设置它,getView() 将返回 null

PS。您的班级名称“创作”是非标准的。 Java 类名应该以大写字母开头,如果你的类扩展了 Fragment,那么习惯上让类名以“Fragment”结尾。例如:“CreationFragment”。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-11-06
    • 2020-09-27
    • 2019-09-05
    • 2023-01-20
    • 1970-01-01
    相关资源
    最近更新 更多