1

I've seen more questions like this but didn't manage to make any sense of them or they didn't apply to my problem, so here goes.

I have an Activity that allows you to login and another where you send POST and GET requests and so on, using your login credentials.

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

}

When I print out the username and password in the second class, they both return null, and the POST request fails.

OddCore
  • 1,534
  • 6
  • 19
  • 32
  • You could try putting username and password into an array. Then when you go to start the `HttpGetPost` activity you can place the array as an extra in the intent. [Here](http://stackoverflow.com/questions/3848148/sending-arrays-with-intent-putextra) is an example. You can also look in the documentation. – Ryan Smith Aug 27 '13 at 15:35

5 Answers5

4

You should pass the username and password to your activity using the putExtra methods of the intent :

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

In your second activity, in onCreate() (after setContentView for example), you can retrieve them using getXXExtras :

Intent intent = getIntent();

String username = intent.getStringExtra("username");
String password = intent.getStringExtra("password");
jbihan
  • 3,053
  • 2
  • 24
  • 34
  • doInBackground in the HttpGetPost class can't see the two strings (username and password) cause they are in the onCreate method. – OddCore Aug 27 '13 at 15:46
  • Good answer, though it's better practice to use static constants that are visible in both classes as the keys for the `getXXXExtra()` methods instead of string literals. Also you can use the `hasExtra()` method to check if these values actually exist in the intent before assigning the variables to prevent a potential null pointer exception. – Itai Hanski Aug 27 '13 at 15:47
  • @OddCore simply get the values in the `onCreate` method and send them as parameters to the `AsyncTask`: `new sendPost().execute(user,pass);` – Itai Hanski Aug 27 '13 at 15:50
  • @ItaiHanski I am accessing the user and pass variables from within doInBackground of the sendPost class, so it wont let me do "new sendPost().execute(user, pass);" – OddCore Aug 27 '13 at 15:55
  • @OddCore I created an answer to elaborate what I meant, Take a look. – Itai Hanski Aug 27 '13 at 16:07
4

To clarify what I meant in the comment at jbihan's answer:

I'm updating your code:

First revision:

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

Second revision:

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

Third revision:

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...

    }
}

Please consider using constants for "username" and "password" keys.

Itai Hanski
  • 8,540
  • 5
  • 45
  • 65
1

Try to use extras:

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

In the other actvity(your HttpGetPost)

String user = getIntent().getStringExtra("username");
String password = getIntent().getStringExtra("password");
MikeKeepsOnShine
  • 1,730
  • 4
  • 23
  • 35
1

Here is a nice tutorial about the proper use of Intents.

Try this call of the HttpGetPost Activity:

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

With this you pass the right Context in the Intent constructor. Put the data in the Intent which you wanna send to the Activity. The next point is to not call startActivityForResult(), which is used to call an Activity, make some calculation and send the results back to the requesting Activity.

Now get the data out of the Intent in the HttpGetPost Activity like this in your onCreate and save it to a field:

getIntent().getExtras().getString("username");
getIntent().getExtras().getString("password");
Steve Benett
  • 12,843
  • 7
  • 59
  • 79
1

You don't need

private MainActivity mainProxy = new MainActivity();

in HttpGetPost. It will create a new MainActivity, which is not the original one which start HttpGetPost.

You can use extras to send data across intents. Here is my solution:

Put this in MainActivity

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

This is for HttpGetPost, KEY_USERNAME and KEY_PASSWORD can be used to store extra key, so that you can avoid typo.

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

Put this in onCreate of HttpGetPost to get the data from intent

Intent intent = getIntent();

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

Here is the official document for intent.

lindatseng
  • 69
  • 4