androidandroid-intentnullandroid-intentserviceextra

intent.getStringExtra is always "null"


This is how the string is added to intent.putExtra:

    final ListView listView = findViewById(R.id.userListView);
    final ArrayList<String> usernames = new ArrayList<>();

    listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
        @Override
        public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
            Intent intent = new Intent(getApplicationContext(), UserFeedActivity.class);
            String username = usernames.get(i);
            intent.putExtra("username", username.toString() );
            Log.i("test","username: "+username);
            startActivity(intent);

        }
    });

the Log.I gave me: "... I/test: username: Chris2", so I think that the extra is being added correctly

but, on UserFeedActivity class, if I try to read the intent with this code:

    Intent intent = new Intent();
    String username = intent.getStringExtra("username");
    Log.i("test2","username: "+username);

the Log.I gave me: "... I/test2: username: null"

I've also tried

    Bundle bundleEx = intent.getExtras();
    Log.i("trdt3","extras: "+bundleEx);

the Log.I gave me: "... I/test3: extras: null"

Am I doing something wrong or what?


Solution

  • You are creating a brand new intent in the other activity, so it has no extras. In the new activity you need to call getIntent(), like this

    Intent intent = getIntent(); // don't use 'new Intent()' here
    String username = intent.getStringExtra("username");
    Log.i("test3","username: "+username);
    

    Note that calling getStringExtra just calls getExtras() internally, then getString(...), so it is the same as using getIntent().getExtras().getString(...)