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

时间:2016-01-20 06:25:17

标签: android android-activity fragment

我是android新手。最近我尝试通过活动在2个片段之间进行通信基本上我在这里将按钮的位置从一个片段发送到另一个由文本视图组成的片段。但是我得到了错误: 尝试调用虚方法' void android.widget.TextView.setText(java.lang.CharSequence)'在空对象引用上

如果值id甚至被传递,我试过了。我在Log上打印了值,并且已成功打印。我已经对这个错误进行了大量搜索并尝试了替代方案;使用方法, rootView 而不是 getView(),但似乎没有任何结果。我可能犯了一个愚蠢的错误,但我真的要完成这个。

MainActivity.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();

 }
}

BlankFragment.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");
    }
}
}

ResultFragment

    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)

2 个答案:

答案 0 :(得分:2)

它正在为您提供NullPointerException,因为

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

您正试图在Activity context上找到该视图,并且没有Id的视图 R.id.textview与之相关联。

因此,您必须通过覆盖

来扩展视图,从而在Fragment范围内找到视图

以下是获取视图的代码

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;
   }

答案 1 :(得分:0)

下面:

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

getActivity()返回容器Activity上下文,如果我们使用getActivity()来调用findViewById方法,则意味着从Activity布局而不是Fragment访问视图

要使用Fragment布局使用onCreateView访问视图,方法与BlankFragment片段中的ding一样。

覆盖onCreateView片段中的BlankFragment方法:

@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
                         Bundle savedInstanceState) {
    // Inflate the layout for this fragment
    View view= inflater.inflate(
         R.layout.<pass layout id which contains TextView with textView  id>, 
        container, false);
    TextView textView= (TextView) view.findViewById(R.id.textView);
     Bundle bundle = this.getArguments();
     String Value = bundle.getString("value");
     textView.setText(Value);
    return view;
}