简体   繁体   English

使用Intent从Activity传递变量

[英]Using Intent to pass variable from Activity

I want to send a value("sessionId") from one activity to another. 我想从一个活动向另一个活动发送一个值(“sessionId”)。 I have used intent for that but I don't know how to access that variable so that I can use it in Intent. 我已经使用了intent,但我不知道如何访问该变量,以便我可以在Intent中使用它。

This is my java file:- 这是我的java文件: -

public class Login extends Activity {

      //URL to get JSON Array
      private static String url = "http://*************/webservice.php?operation=getchallenge&username=admin";

      //JSON Node Names
      private static final String TAG_RESULT = "result";
      private static final String TAG_TOKEN = "token";

      // contacts JSONArray
      JSONArray contacts = null;

      String token = null;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.login);

        if (android.os.Build.VERSION.SDK_INT > 9) {
            StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitAll().build();
            StrictMode.setThreadPolicy(policy);
        }


        new AsyncTask<Void, Void, Void>() {

            @SuppressWarnings("unused")
            JSONObject result;

            @Override
            protected Void doInBackground(Void... params) {

                // Creating new JSON Parser
                JSONParser jParser = new JSONParser();

                // Getting JSON from URL
                JSONObject json = jParser.getJSONFromUrl(url);

                try {
                    // Getting JSON Array
                    result = json.getJSONObject(TAG_RESULT);
                      JSONObject json_result = json.getJSONObject(TAG_RESULT);

                    // Storing  JSON item in a Variable
                    token = json_result.getString(TAG_TOKEN);

                    //Importing TextView

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

                String username="admin";
                String accesskeyvalue = "**************";
                String accessKey=md5(token + accesskeyvalue);

        String data = null;

            try {
                data = URLEncoder.encode("username", "UTF-8")
                        + "=" + URLEncoder.encode(username, "UTF-8");
                data += "&" + URLEncoder.encode("accessKey", "UTF-8") + "="
                        + URLEncoder.encode(accessKey, "UTF-8");
            } catch (UnsupportedEncodingException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            } 
        String text = "";
        BufferedReader reader=null;
        System.out.println(data);

        // Send data
        try
        {

            // Defined URL  where to send data
            URL url = new URL("http://***************/webservice.php?operation=login");

         // Send POST data request
          URLConnection conn = url.openConnection();
          conn.setDoOutput(true);
          OutputStreamWriter wr = new OutputStreamWriter(conn.getOutputStream());
          wr.write( data );
          wr.flush();    

        // Get the server response    
        reader = new BufferedReader(new InputStreamReader(conn.getInputStream()));
        StringBuilder sb = new StringBuilder();
        String line = null;

        // Read Server Response
        while((line = reader.readLine()) != null)
            {
                   // Append server response in string
                   sb.append(line + "\n");
            }


            text = sb.toString();
        }
        catch(Exception ex)
        {

        }
        finally
        {
            try
            {

                reader.close();
            }

            catch(Exception ex) {}
        }

        // Show response
        System.out.println(text);
        String sessionid = text.substring(41, 62);
        System.out.println(sessionid);



    return null;    
    }
            @Override
            protected void onPostExecute(Void aVoid) {
                super.onPostExecute(aVoid);          
               }

         }.execute();

    } 

    public String md5(String s) 
    {
    MessageDigest digest;
        try 
            {
                digest = MessageDigest.getInstance("MD5");
                digest.update(s.getBytes(),0,s.length());
                String hash = new BigInteger(1, digest.digest()).toString(16);
                return hash;
            } 
        catch (NoSuchAlgorithmException e) 
            {
                e.printStackTrace();
            }
        return "";
    }

    public void sendMessage(View view) 
    {
       Intent intent = new Intent(Login.this, Quote1.class);
       intent.putExtra("sessionId", sessionId);
       startActivity(intent);
    }       
}

Here in sendMessage() I am not able to use sessionId as it is declared in doInBackground() which is protected . sendMessage()我无法使用sessionId,因为它在protected doInBackground()声明。

I am bit weak in OOP. 我在OOP中有点弱。 Please help. 请帮忙。

To access variables within a class between different methods simply make the variable a class variable. 要在不同方法之间访问类中的变量,只需将变量设为类变量即可。

To send data between activities refer to this article. 之间活动,是指将数据发送文章。

Basic example of Activity1 sending message to Activity2: Activity1向Activity2发送消息的基本示例:

Activity1: 活动1:

//Static String to identify the send parameter, without this this you have to set the exact same string twice.
public final static String SESSION_ID = "com.example.your.long.appname.SESSION_ID";

//sendMessage method is called for some reason in your class that you define (e.g user onClick)
public void sendMessage(View view) {
    //Create an Intent
    Intent intent = new Intent(this, Activity2.class);
    //put the sessionID as extra intent.
    intent.putExtra(SESSION_ID, sessionID);
    //Start Activity2 with the intent.
    startActivity(intent);
}

And to get the variable sent, use getStringExtra(String) for example in Activity2: 要获取发送的变量,请在Activity2中使用getStringExtra(String):

//Get the intent
Intent intent = getIntent();
//Get the message
String message = intent.getStringExtra(Activity1.SESSION_ID);

you can put your sessionId variable as a class variable in Login class as you did for TAG_RESULT, TAG_TOKEN etc... 您可以将您的sessionId变量作为类变量放在Login类中,就像您对TAG_RESULT,TAG_TOKEN等所做的那样...

Then, because your asyncTask is declared inline this Login class, you cann access it (and change its value) from it (the AsyncTask) and also access it's value in sendMessage method of the Login class. 然后,因为您的asyncTask被声明为内联此Login类,您可以从它(AsyncTask)访问它(并更改其值),并在Login类的sendMessage方法中访问它的值。

I would also recommand (for better readability) to put you AsyncTask as another class (inner class of LoginClass). 我还建议(为了更好的可读性)将AsyncTask作为另一个类(LoginClass的内部类)。 Code will be more readable. 代码将更具可读性。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM