将一些值从一个活动传递给一个片段,然后传递给NullPointerException

时间:2018-01-28 14:58:47

标签: java android fragment bundle

我想将一些值从一个活动传递给一个片段。已经看到很多答案,但没有解决我的问题

活动

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

片段

Bundle bundle1 = new Bundle();
    bundle1.putString("baros",baros);
    bundle1.putString("upsos",upsos);
    bundle1.putString("sex",sex);
    CalculatorFragment calculatorFragment = new CalculatorFragment();
    calculatorFragment.setArguments(bundle1);

java.lang.NullPointerException:尝试在空对象引用上调用虚方法'java.lang.Object android.os.Bundle.get(java.lang.String)'

问题在于:String name =(String)bundle.get(“sex”);

谢谢!

2 个答案:

答案 0 :(得分:0)

    //noinspection SimplifiableIfStatement
    if (id == R.id.action_settings) {

    }
    else if(id == R.id.firstMenu){
        fragment = new ArxikoFragment();
    }
    else if(id == R.id.calcsMenu){
         fragment = new CalculatorFragment();
    }else if(id == R.id.dietMenu){
           fragment = new DietFragment();
    }else if(id == R.id.tipsMenu){
            fragment = new TipsFragment();
    }else if(id == R.id.stoixeiaMenu){
            fragment = new StoixeiaFragment();
    }else if(id == R.id.logoutMenu){
        Intent myIntent = new Intent(StartActivity.this, MainActivity.class);
        StartActivity.this.startActivity(myIntent);
        super.onBackPressed();
    }


    if(fragment != null){
        android.support.v4.app.FragmentManager fragmentManager = getSupportFragmentManager();
        android.support.v4.app.FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction();
        fragmentTransaction.replace(R.id.navigationLayout,fragment);
        fragmentTransaction.commit();
    }
    return super.onOptionsItemSelected(item);
}

答案 1 :(得分:0)

你可以通过``

从片段中的活动中获取变量
 MainActivity ob1 = (MainActivity) getActivity();
 string var1=ob1.sex;