android - 尝试在空对象引用 2 上调用虚拟方法 'void android.widget.TextView.setText(java.lang.CharSequence)'

标签 android android-activity fragment

我是安卓新手。最近我尝试通过 Activity 在 2 个 fragment 之间进行通信。基本上在这里,我将按下按钮的位置从一个 fragment 发送到另一个由 TextView 组成的 fragment 。但我收到错误: 尝试在空对象引用上调用虚方法“void android.widget.TextView.setText(java.lang.CharSequence)”

我试过值 id 是否被传递。我在日志上打印了值,它被成功打印了。我对这个错误进行了很多搜索并尝试了其他方法;使用方法 rootView 而不是 getView() 但似乎没有任何效果。我可能犯了一个愚蠢的错误,但我真的要挺过去。

主 Activity .java

      package com.example.benchtobasecamp.doublelistfragment;
      import android.support.v4.app.FragmentActivity;
      import android.os.Bundle;
      import android.support.v4.app.FragmentTransaction;
      import android.view.Menu;
      import android.view.MenuItem;

      public class MainActivity extends FragmentActivity implements BlankFragment.OnItemClickListener{

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

@Override
public boolean onCreateOptionsMenu(Menu menu) {
    // Inflate the menu; this adds items to the action bar if it is present.
    getMenuInflater().inflate(R.menu.menu_main, menu);
    return true;
}

@Override
public boolean onOptionsItemSelected(MenuItem item) {
    // Handle action bar item clicks here. The action bar will
    // automatically handle clicks on the Home/Up button, so long
    // as you specify a parent activity in AndroidManifest.xml.
    int id = item.getItemId();

    //noinspection SimplifiableIfStatement
    if (id == R.id.action_settings) {
        return true;
    }

    return super.onOptionsItemSelected(item);
}

 @Override
public void method1(int position)
 {
 ResultFragment rf=new ResultFragment();
 Bundle bundle = new Bundle();
 bundle.putString("value", String.valueOf(position));

 rf.setArguments(bundle);


FragmentTransaction fragmentManager=getSupportFragmentManager().beginTransaction();
fragmentManager.replace(R.id.frame_container,rf);
fragmentManager.addToBackStack(null);
fragmentManager.commit();

 }
}

空白 fragment .jav

    package com.example.benchtobasecamp.doublelistfragment;
    import android.content.Context;
    import android.support.v4.app.ListFragment;
    import android.os.Bundle;
    import android.support.v4.app.Fragment;
    import android.view.LayoutInflater;
    import android.view.View;
    import android.view.ViewGroup;
    import android.widget.AdapterView;
    import android.widget.ArrayAdapter;



    public class BlankFragment extends ListFragment {
OnItemClickListener listener;

public interface OnItemClickListener
{
    public void method1(int position);
}
@Override
public void onActivityCreated(Bundle savedInstanceState)
{
    super.onActivityCreated(savedInstanceState);
    ArrayAdapter<CharSequence> adapter=ArrayAdapter.createFromResource(getActivity(), R.array.Buttons, android.R.layout.simple_list_item_1);
    setListAdapter(adapter);
    getListView().setOnItemClickListener(new AdapterView.OnItemClickListener() {
        @Override
        public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
            switch (position)
            {
                case 0:listener.method1(0);
                    break;
                case 1:listener.method1(1);
                    break;
                case 2:listener.method1(2);
                    break;
            }

        }
    });

}


@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
                         Bundle savedInstanceState) {
    // Inflate the layout for this fragment
    View view= inflater.inflate(R.layout.fragment_blank, container, false);
    return view;
}


@Override
public void onAttach(Context context) {
    super.onAttach(context);
    try{

        listener = (OnItemClickListener) context;
    }
    catch(ClassCastException e) {
        throw new ClassCastException(context.toString() + " must implement MyListFragment.OnItemSelectedListener");
    }
}
}

结果 fragment

    package com.example.benchtobasecamp.doublelistfragment;
    import android.os.Bundle;
    import android.support.v4.app.Fragment;
    import android.util.Log;
    import android.view.LayoutInflater;
    import android.view.View;
    import android.view.ViewGroup;
    import android.widget.TextView;


    public class ResultFragment extends Fragment {

    TextView textView;

public ResultFragment() {
    // Required empty public constructor
}



@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);

    Bundle bundle = this.getArguments();
    String Value = bundle.getString("value");

    //Log.d("You pressed Button",String.valueOf(position+1));

    textView= (TextView) getActivity().findViewById(R.id.textView);
    textView.setText(Value);




}

  }

logcat 显示此错误:

     01-20 11:33:24.084    1923-1923/com.example.benchtobasecamp.doublelistfragment E/AndroidRuntime﹕ FATAL EXCEPTION: main
Process: com.example.benchtobasecamp.doublelistfragment, PID: 1923
java.lang.NullPointerException: Attempt to invoke virtual method 'void android.widget.TextView.setText(java.lang.CharSequence)' on a null object reference
        at com.example.benchtobasecamp.doublelistfragment.ResultFragment.onCreate(ResultFragment.java:34)
        at android.support.v4.app.Fragment.performCreate(Fragment.java:1942)
        at android.support.v4.app.FragmentManagerImpl.moveToState(FragmentManager.java:1040)
        at android.support.v4.app.FragmentManagerImpl.moveToState(FragmentManager.java:1259)
        at android.support.v4.app.BackStackRecord.run(BackStackRecord.java:738)
        at android.support.v4.app.FragmentManagerImpl.execPendingActions(FragmentManager.java:1624)
        at android.support.v4.app.FragmentManagerImpl$1.run(FragmentManager.java:517)
        at android.os.Handler.handleCallback(Handler.java:739)
        at android.os.Handler.dispatchMessage(Handler.java:95)
        at android.os.Looper.loop(Looper.java:148)
        at android.app.ActivityThread.main(ActivityThread.java:5417)
        at java.lang.reflect.Method.invoke(Native Method)
        at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:726)
        at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:616)

最佳答案

它给你 NullPointerException 因为

textView= (TextView) getActivity().findViewById(R.id.textView);

您正试图在 Activity context 上找到 View ,但没有 Id 的 View R.id.textview 与之关联。

因此,您必须通过重写来膨胀 View ,从而在 Fragment 范围内找到 View

获取 View 的代码

public class ResultFragment extends Fragment{
     @Override
     public View onCreateView ( LayoutInflater inflater , ViewGroup container, Bundle savedInstanceState){
        super.onCreateView(inflater,container,savedInstanceState);

        View view=inflater.inflate(R.layout.yourlayout,container,false);
        TextView textView=view.findViewById(R.id.textView);
        textView.setText(content);
        return view;
   }

关于android - 尝试在空对象引用 2 上调用虚拟方法 'void android.widget.TextView.setText(java.lang.CharSequence)',我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34892929/

相关文章:

Android - 从短信时间戳中获取日期时间(以毫秒为单位)

android - 使用向上按钮导航时,不会保留父 Activity 的状态

android - 使用 Fragment 中的 MapView 对象与 Fragment 中的 MapFragment 相比,google maps v2 有什么优点/缺点?

java - Gradle DSL 方法未找到 : testCompile()

java - 使用C++获取Java对象调用Java方法

android - 如何在 java 代码中管理 UI?

android - 在 ListFragment 中显示 ProgressDialog

android - ViewPager 内的 fragment 错误地设置了状态

android - 我无法将视频上传到 YouTube

android - 无法通过本地 HTML 在 Android WebView 上呈现 Facebook 评论