从onClick()传递时无法为全局变量赋值

时间:2015-11-19 08:06:41

标签: java android

我正在尝试将数据传递给onClick内的变量形式。  它返回null。然后我将使用该变量将其传递给方法。我对android编程比较陌生,这已经困扰了我几个小时。这是我的代码:

MainActivity.java

    public class MainActivity extends Activity {

 ConnectionClass connectionClass;
 EditText edtuserid,edtpass;
 Button btnlogin;
 ProgressBar pbbar;

 public String name = "";
 String userid;
 String password;

 Override
 protected void onCreate(Bundle savedInstanceState) {
 super.onCreate(savedInstanceState);
 setContentView(R.layout.activity_main);
 connectionClass = new ConnectionClass();
 edtuserid = (EditText) findViewById(R.id.edtuserid);
 edtpass = (EditText) findViewById(R.id.edtpass);
 btnlogin = (Button) findViewById(R.id.btnlogin);
 pbbar = (ProgressBar) findViewById(R.id.pbbar);
 pbbar.setVisibility(View.GONE);


btnlogin.setOnClickListener(new View.OnClickListener() {
 @Override
     public void onClick(View v) {
     userid = edtuserid.getText().toString();
     password = edtpass.getText().toString();

     name = userid;


 }
 });
 }

 }

public String getMyData() {

    String test4 = name;
    return test4;

 }
}

1 个答案:

答案 0 :(得分:0)

尝试使用共享偏好设置......

btnlogin.setOnClickListener(new View.OnClickListener() {
@Override
 public void onClick(View v) {
 userid = edtuserid.getText().toString();
 password = edtpass.getText().toString();

SharedPreferences pref = getApplicationContext().getSharedPreferences("MyPref", MODE_PRIVATE); 
Editor editor = pref.edit();
editor.putString("name_from_main", userid );  // Saving string

// Save the changes in SharedPreferences
editor.commit(); // commit changes


}
});

//在您的片段中使用此

 SharedPreferences pref = getApplicationContext().getSharedPreferences("MyPref", MODE_PRIVATE); 
 Editor editor = pref.edit();
String name_from_main = pref.getString("name_from_main", null);