NullPointerException from getExtras()

后端 未结 3 827
青春惊慌失措
青春惊慌失措 2021-01-05 06:50

I\'m creating an intent to transfer data from one activity to another like this :

Intent intent = new Intent(this, ActivityHighScore.class);
    intent.putE         


        
相关标签:
3条回答
  • 2021-01-05 07:04

    The method which you are doing is correct . The null pointer exception is coming because the fragment is not replaced with the right fragment object. Here is the working code Activity class

    Bundle bundle = new Bundle();
    bundle.putString("message", "helloo");
    Home tm = new Home();
    tm.setArguments(bundle);
    fragmentTransaction = getSupportFragmentManager().beginTransaction();
    fragmentTransaction.replace(R.id.frag,tm).commit();
    getSupportActionBar().setTitle("Home");
    item.setChecked(true);
    drawerLayout.closeDrawers();
    

    the code for receiving in fragment

    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState)
    {
        String myValue = getArguments().getString("message");
        Toast.makeText(getActivity(), myValue, Toast.LENGTH_SHORT).show();
        myview = inflater.inflate(R.layout.fragment_home, container, false);
        return myview;
    }
    

    Do let me know if it helps!

    0 讨论(0)
  • 2021-01-05 07:06

    Replace

    Bundle bundle = getIntent().getExtras();
    
        if (!bundle.getString("USERNAME").equals(null) && bundle.getInt("PLAYERMOVES") != 0){
            String username = bundle.getString("USERNAME");
            int playerMoves = bundle.getInt("PLAYERMOVES");
            addHighScore(username, playerMoves);
    
        } 
    

    with

     if (getIntent().getStringExtra("USERNAME") != null && (getIntent().getIntExtra("PLAYERMOVES", 0) != 0){
            String username = bundle.getString("USERNAME");
            int playerMoves = bundle.getInt("PLAYERMOVES");
            addHighScore(username, playerMoves);
    
      } 
    
    0 讨论(0)
  • 2021-01-05 07:15

    Well, I had a similar problem. In my case the NullPointerException happened when I checked if my bundle.getString() was equal to null.

    Here is how I solved it, in my case:

    Intent intent = getIntent();        
    if(intent.hasExtra("nomeUsuario")){
        bd = getIntent().getExtras();
        if(!bd.getString("nomeUsuario").equals(null)){
            nomeUsuario = bd.getString("nomeUsuario");
        }
    }
    
    0 讨论(0)
提交回复
热议问题