简体   繁体   中英

How do I update the Main Activity using getIntent()?

protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    //identify object

    Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
    setSupportActionBar(toolbar);

    DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
    ActionBarDrawerToggle toggle = new ActionBarDrawerToggle(this, drawer, toolbar, R.string.navigation_drawer_open, R.string.navigation_drawer_close);
    drawer.setDrawerListener(toggle);
    toggle.syncState();

    NavigationView navigationView = (NavigationView) findViewById(R.id.nav_view);
    navigationView.setNavigationItemSelectedListener(this);

    **title = (TextView)findViewById(R.id.theTitle);
    Intent intent = getIntent();
    String Title = intent.getExtras().getString("name");
    title.setText(Title);**
}

@SuppressWarnings("StatementWithEmptyBody")
@Override
public boolean onNavigationItemSelected(MenuItem item) {
    // Handle navigation view item clicks here.
    int id = item.getItemId();

    if (id == R.id.nav_camera) {
        // Handle the camera action

    } else if (id == R.id.nav_gallery) {
        Intent intent = new Intent(this, addCounter.class);
        startActivity(intent);

    DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
    drawer.closeDrawer(GravityCompat.START);
    return true;
}

When nav_gallery = true, it brings me to activity2 which has the following code:

    public void addOk(){
    String sendName = name.getText().toString();
    Intent intent = new Intent(this, MainActivity.class);
    intent.putExtra("name", sendName);
    startActivity(intent);
}

I want to send the information from activity2 back to the main activity. Is my getIntent() in the wrong place?

Your getIntent() method is inside the onCreate method. But onCreate is called only once, at creation. And if the MainActivity is still in the stack, there is no reason why onCreate() would be called again.

You should try to insert your code inside onResume() or onStart().

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM