我试着寻找其他问题,但似乎没有任何效果。尝试将存储在sUsername中的值从活动Username.java传递给MainActivity.java(用户名)。
这是Username.java:
public class Username extends ActionBarActivity implements View.OnClickListener {
EditText eUsername;
Button login;
String sUsername;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_username);
eUsername = (EditText) findViewById (R.id.username);
sUsername = eUsername.getText().toString();
login = (Button)findViewById(R.id.login);
login.setOnClickListener(this);
}
private void loginClick() {
Intent intent = new Intent(this, MainActivity.class );
intent.putExtra("containsUsername", sUsername); //first argument is the name of the string being passed
startActivity(intent);
}
public void onClick (View v) {
switch (v.getId()) {
case R.id.login:
loginClick();
break;
}
}
这是MainActivity.java
public class MainActivity extends ActionBarActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Intent intent = getIntent();
Bundle bundle = intent.getExtras();
String username = bundle.getString("containsUsername");
WebView listOfSongs = (WebView) findViewById (R.id.webview);
String url = "http://ws.audioscrobbler.com/2.0/?method=user.gettoptracks&user="+username+"&api_key=68f82cd7b37e7b23800c2025066531c9&format=json";
listOfSongs.loadUrl(url);
}
答案 0 :(得分:1)
你的loginCheck方法应该是这样的:
private void loginClick() {
sUsername = eUsername.getText().toString();
Intent intent = new Intent(this, MainActivity.class );
intent.putExtra("containsUsername", sUsername); //first argument is the name of the string being
startActivity(intent);
}
在创建时,您的edittext可能为空。
答案 1 :(得分:1)
请检查您的edittext是否为空。长期更改方法单击。
private void loginClick(){
if(!sUsername.isEmpty()) {
Intent intent = new Intent(this, MainActivity.class );
intent.putExtra("containsUsername", sUsername);
startActivity(intent);
} else {
Toast.makeText(Username.this, "Please enter username.", Toast.LENGTH_LONG).show();
}
}