在null对象引用上的java.lang.String android.os.Bundle.getString(java.lang.String)'

时间:2017-04-04 11:59:30

标签: java android fragment

我正在尝试将数据从PageAdapter发送到片段两天,但根本没有成功。 我正在使用Bundle,并发送如下:

     protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_ficha__completa);

        Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
        setSupportActionBar(toolbar);
        // Create the adapter that will return a fragment for each of the three
        // primary sections of the activity.
        mSectionsPagerAdapter = new SectionsPagerAdapter(getSupportFragmentManager()); 
        // Set up the ViewPager with the sections adapter.
        mViewPager = (ViewPager) findViewById(R.id.container);
        mViewPager.setAdapter(mSectionsPagerAdapter);

        nome="Chimpanze";

        try {
            Bundle bundle = new Bundle();
            bundle.putString("Nome_animal",nome);
            Imagem_Animal imagem = new Imagem_Animal();
            imagem.setArguments(bundle);
        } catch (Exception e) {
            Log.d(TAG_LOG,"Erro de bundle: "+e.getLocalizedMessage());
        }
    }

我的片段是这样的:

public class Imagem_Animal extends Fragment {
    ImageView imagem_p;
    static final String TAG ="Fragmento";
    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        // Inflate the layout for this fragment
        View Layout_imagem = inflater.inflate(R.layout.fragment_imagem__animal, container, false);
        imagem_p = (ImageView) Layout_imagem.findViewById(R.id.imagem);
        try {
            String nomeAnimal = getArguments().getString("Nome_animal");
        } catch (Exception e){
            Log.d(TAG, "getStirng :"+e.getMessage());
        }
        return Layout_imagem;
    }
}
  

Log:getString:尝试在空对象引用上调用虚方法'java.lang.String android.os.BaseBundle.getString(java.lang.String)'

有人可以帮我吗?

非常感谢

2 个答案:

答案 0 :(得分:1)

如果片段在MainAtivity实际上pagerAdapter所在的位置。那么您可以访问Imagem_Animal Fragment内的字段

((MainActivity) getActivity()).nome

而不是将其传递到捆绑包中。

答案 1 :(得分:0)

在您的片段中创建如下所示的函数。

 public void someFunctionName(String data){

 }
Pager适配器中的

执行以下操作。

@Override
public Fragment getItem(int position) {
    Imagem_Animal ani= new Imagem_Animal();
    ani.someFunctionName("yourdata");
    return ani;
}

这就是全部