简体   繁体   中英

Getting data from an Intent

I am doing a project (Android app) for uni and after a bit of help I have a login screen as per the code below:

//Do once the "Login" button is clicked
public void onClick(View view)
{
    //get the users name and password
    EditText editName = (EditText) findViewById(R.id.txtUserName);
    String name = editName.getText().toString();
    //EditText editPassword = (EditText) findViewById(R.id.txtUserPassword);
    //String password = editPassword.getText().toString();

    //create an Intent object and pass it the name and password
    Intent intent = new Intent(this, UserLoggedInScreen.class);
    intent.putExtra("userName", name);
    //intent.putExtra("userPassword", password);
    startActivity(intent);
}

I have commented out the the password bit for now just to get the username bit working. The aim is to click the button and put the text input into textUserName by the user into the String name. Then pass that through to activity UserLoggedInScreen.

Then in UserLoggedInScreen collect the data:

public class UserLoggedInScreen extends Activity
{
TextView welcomeUser;

@Override
protected void onCreate(Bundle savedInstanceState) 
{
    super.onCreate(savedInstanceState);
    setContentView(R.layout.userloggedinscreen);

    //get the Intent Object from LapMasterActivity
    Intent intent = getIntent();

    //get the data from the Intent Object
    String userName = intent.getStringExtra("userName");
    //String userPassword = intent.getStringExtra("userPassword");

    welcomeUser = (TextView) findViewById(R.id.txtUserName);
    welcomeUser.setText(userName);
}

When I try running it and clicking the button in the opening activity I get the usual "Unfortunately UserLoggedInScreen has stopped working".

I think this bit might be the error:

welcomeUser = (TextView) findViewById(R.id.txtUserName);

I tried changing txtUserName to userName but that didn't help either.

Thanks.

您是否在AndroidManifast中进行了第二类活动........

<activity android:name="UserLoggedInScreen"></activity>

First Thing As Bappy said Register Your activity so that it can be detected at runtime.

<activity android:name="UserLoggedInScreen">
</activity>

Second thing

welcomeUser = (TextView) findViewById(R.id.txtUserName);

EditText editName = (EditText) findViewById(R.id.txtUserName);

You are using same id, are you doing it intentionally??

Pleas Check id of TextView of UserLoggedInScreen .

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