在Android中将EditText输入从一个类传递到另一个类

时间:2013-08-27 15:32:08

标签: java android

我已经看到了更多这样的问题,但是没有对它们有任何意义,或者它们不适用于我的问题,所以就这样了。

我有一个允许您登录的活动,以及使用您的登录凭据发送POST和GET请求等的其他地方。

mainActivity:

public class MainActivity extends Activity
{

    private String username;
    private String password;

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

        final EditText usernameField = (EditText) findViewById(R.id.enterUsername);

        final EditText passwordField = (EditText) findViewById(R.id.enterPassword);

        Button startButton = (Button) findViewById(R.id.startButton);
        startButton.setOnClickListener(new View.OnClickListener()
        {
            public void onClick(View view)
            {
                username = usernameField.getText().toString();
                password = passwordField.getText().toString();
                Intent myIntent = new Intent(view.getContext(), HttpGetPost.class);
                startActivityForResult(myIntent, 0);
            }
        });
    }

    public String getUser() { return this.username; }
    public String getPassword() { return this.password; }
}

HttpGetPost:

public class HttpGetPost extends Activity
{

    private MainActivity mainProxy = new MainActivity();
    private Button postButton;
    private Button getButton;
    private Button getMeasureButton;
    private Button getDevicesButton;
    private String access_token;
    private String refresh_token;
    private String device_list;
    private String expires_in;
    private String getRequest;
    private static final String TAG = "MyActivity";
    private static final String USER_AGENT = "Mozilla/5.0";
    private String clientID = some_id;
    private String clientSecret = some_secret;
    private String user = mainProxy.getUser();
    private String pass = mainProxy.getPassword();

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

        Log.v(TAG, "mainProxy.username: "+user);
        Log.v(TAG, "mainProxy.password: "+pass);

        postButton = (Button) findViewById(R.id.postButton);
        postButton.setOnClickListener(new View.OnClickListener()
        {
            @Override
            public void onClick(View view)
            {
                new sendPost().execute("");
            }
        });
    }

    private class sendPost extends AsyncTask<String, Void, String>
    {
        @Override
        protected String doInBackground(String... params)
        {
            try
            {
                String url = some_url;
                URL obj = new URL(url);
                HttpsURLConnection con = (HttpsURLConnection) obj.openConnection();

                //add request header
                con.setRequestMethod("POST");
                con.setRequestProperty("User-Agent", USER_AGENT);
                con.setRequestProperty("Accept-Language", "en-US,en;q=0.5");

                String urlParameters = "grant_type=password&client_id=" +clientID +"&client_secret="
                    +clientSecret +"&username=" +user +"&password=" +pass;

                // Send post request
                con.setDoOutput(true);
                DataOutputStream wr = new DataOutputStream(con.getOutputStream());
                wr.writeBytes(urlParameters);
                wr.flush();
                wr.close();

                int responseCode = con.getResponseCode();
                Log.v(TAG, "\nSending 'POST' request to URL : " + url);
                Log.v(TAG, "Post parameters : " + urlParameters);
                Log.v(TAG, "Response Code : " + responseCode);

                BufferedReader in = new BufferedReader(
                        new InputStreamReader(con.getInputStream()));
                String inputLine;
                StringBuffer response = new StringBuffer();

                while ((inputLine = in.readLine()) != null) {
                    response.append(inputLine);
                }
                in.close();

                //print result
                Log.v(TAG, response.toString());

                if (responseCode == 200)
                {
                    access_token = response.substring(17, 74);
                    refresh_token = response.substring(93,150);
                    expires_in = response.substring(165, 170);
                    getRequest = "http://api.netatmo.net/api/getuser?access_token=" +access_token + " HTTP/1.1";

                    Log.v(TAG, "access token: " +access_token);
                    Log.v(TAG, "refresh token: " +refresh_token);
                    Log.v(TAG, "expires in: " +expires_in);
                }

            }
            catch(Exception e){
                e.printStackTrace();
            }

            return "";
        }
        protected void onPostExecute(String result) {
            Toast.makeText(getApplicationContext(), "ENDED", Toast.LENGTH_LONG).show();
        }
    }

}

当我在第二个类中打印出用户名和密码时,它们都返回null,POST请求失败。

5 个答案:

答案 0 :(得分:4)

您应该使用意图的putExtra方法将用户名和密码传递给您的活动:

Intent myIntent = new Intent(view.getContext(), HttpGetPost.class);
myIntent.putExtra("username", username);
myIntent.putExtra("password", pasword);
startActivityForResult(myIntent, 0);

在第二个活动中,在onCreate()中(例如在setContentView之后),您可以使用getXXExtras检索它们:

Intent intent = getIntent();

String username = intent.getStringExtra("username");
String password = intent.getStringExtra("password");

答案 1 :(得分:4)

在jbihan的回答中澄清我的意思:

我正在更新你的代码:

第一次修订:

Button startButton = (Button) findViewById(R.id.startButton);
startButton.setOnClickListener(new View.OnClickListener()
{
    public void onClick(View view)
    {
        username = usernameField.getText().toString();
        password = passwordField.getText().toString();
        Intent myIntent = new Intent(view.getContext(), HttpGetPost.class);
        // ADDITION
        myIntent.putExtra("username", username);
        myIntent.putExtra("password", password);
        // END ADDITION
        startActivityForResult(myIntent, 0);
    }
});

第二次修订:

 postButton = (Button) findViewById(R.id.postButton);
 // ADDITION
 final String user = getIntent().getStringExtra("username");
 final String password = getIntent().getStringExtra("password");
 // END ADDITION
 postButton.setOnClickListener(new View.OnClickListener()
 {
     @Override
     public void onClick(View view)
     {
         // EDITED
         new sendPost().execute(user, password);
     }
 });

第三次修订:

private class sendPost extends AsyncTask<String, Void, String>
{
    @Override
    protected String doInBackground(String... params)
    {
         // ADDITION
         String user = params[0];
         String password = params[1];
         // END ADDITION             

         // use them in the request
         // rest of code...

    }
}

请考虑使用“username”和“password”键的常量。

答案 2 :(得分:1)

尝试使用额外内容:

Intent myIntent = new Intent(view.getContext(), HttpGetPost.class);
myIntent.putExtra("username", username);
myIntent.putExtra("password", password);
startActivityForResult(myIntent, 0);

在另一个行为中(你的HttpGetPost)

String user = getIntent().getStringExtra("username");
String password = getIntent().getStringExtra("password");

答案 3 :(得分:1)

这是关于正确使用Intents的一个很好的tutorial

尝试调用HttpGetPost活动:

Intent myIntent = new Intent(this, HttpGetPost.class);
myIntent.putExtra("username", username);
myIntent.putExtra("password", password);
startActivity(myIntent);

使用this,您可以在Intent构造函数中传递正确的Context。将数据放入要发送到活动的Intent中。接下来的一点是不要调用startActivityForResult(),它用于调用Activity,进行一些计算并将结果发送回请求的Activity。

现在从onCreate中的HttpGetPost活动中获取数据,并将其保存到字段中:

getIntent().getExtras().getString("username");
getIntent().getExtras().getString("password");

答案 4 :(得分:1)

您不需要

private MainActivity mainProxy = new MainActivity();

在HttpGetPost中。它将创建一个新的MainActivity,它不是启动HttpGetPost的原始MainActivity。

您可以使用附加功能跨意图发送数据。这是我的解决方案:

将它放在MainActivity中

Intent myIntent = new Intent(view.getContext(), HttpGetPost.class);
myIntent.putExtra(HttpGetPost.KEY_USERNAME, username);
myIntent.putExtra(HttpGetPost.KEY_PASSWORD, password);
startActivityForResult(myIntent, 0);

这是针对HttpGetPost,KEY_USERNAME和KEY_PASSWORD可以用来存储额外的密钥,这样就可以避免拼写错误。

public static final String KEY_USERNAME = "username"; // or whatever you like for key
public static final String KEY_PASSWORD = "password"; // or whatever you like for key

private String user; // instead of private String user = mainProxy.getUser();
private String pass; // instead of private String pass = mainProxy.getPassword();

将其放入onHrepGetPost的onCreate以获取意图

的数据
Intent intent = getIntent();

user = intent.getStringExtra(KEY_USERNAME);
pass = intent.getStringExtra(KEY_PASSWORD);

Here是意图的官方文件。