【问题标题】:Pass an EditText input from one class to another in Android在 Android 中将 EditText 输入从一个类传递到另一个类
【发布时间】:2013-08-30 10:59:27
【问题描述】:

我看到了更多这样的问题,但没有设法理解它们,或者它们不适用于我的问题,所以就这样吧。

我有一个 Activity 允许您使用您的登录凭据登录和另一个您发送 POST 和 GET 请求等的地方。

主活动:

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请求失败。

【问题讨论】:

  • 您可以尝试将用户名和密码放入数组中。然后,当您开始 HttpGetPost 活动时,您可以将数组作为额外内容放置在意图中。 Here 就是一个例子。您也可以查看文档。

标签: java android


【解决方案1】:

为了澄清我在 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...

    }
}

请考虑为“用户名”和“密码”键使用常量。

【讨论】:

    【解决方案2】:

    您应该使用意图的 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");
    

    【讨论】:

    • HttpGetPost 类中的 doInBackground 看不到这两个字符串(用户名和密码),因为它们在 onCreate 方法中。
    • 很好的答案,尽管使用两个类中可见的静态常量作为 getXXXExtra() 方法的键而不是字符串文字是更好的做法。您还可以在分配变量之前使用hasExtra() 方法检查这些值是否确实存在于意图中,以防止潜在的空指针异常。
    • @OddCore 只需获取onCreate 方法中的值并将它们作为参数发送到AsyncTasknew sendPost().execute(user,pass);
    • @ItaiHanski 我正在访问用户并从 sendPost 类的 doInBackground 中传递变量,所以它不会让我执行“new sendPost().execute(user, pass);”
    • @OddCore 我创建了一个答案来详细说明我的意思,看看。
    【解决方案3】:

    尝试使用附加功能:

    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");
    

    【讨论】:

    • 感谢您的回答,您帮助我理解了问题:)
    【解决方案4】:

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

    试试这个 HttpGetPost Activity 调用:

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

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

    现在像这样在 onCreate 中从 HttpGetPost Activity 中的 Intent 中获取数据并将其保存到字段中:

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

    【讨论】:

    • 谢谢你的回答,你帮助我理解了问题:)
    【解决方案5】:

    你不需要

    private MainActivity mainProxy = new MainActivity();
    

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

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

    把这个放到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可以用来存储额外的key,这样可以避免拼写错误。

    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();
    

    把这个放在 HttpGetPost 的 onCreate 中,从 Intent 中获取数据

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

    Here是intent的官方文档。

    【讨论】:

      猜你喜欢
      • 2021-03-21
      • 1970-01-01
      • 1970-01-01
      • 2011-08-26
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多