使用意图从活动传递变量

阿米特·阿南德(Amit Anand)

我想从一个活动向另一个活动发送一个值(“ sessionId”)。我已经为此使用了intent,但是我不知道如何访问该变量,以便可以在Intent中使用它。

这是我的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);
    }       
}

在这里,sendMessage()我不能使用sessionId,因为它声明为doInBackground()is protected

我的OOP有点虚弱。请帮忙。

非常

要在不同方法之间访问类中的变量,只需使变量成为类变量即可。

之间活动,是指将数据发送文章。

Activity1向Activity2发送消息的基本示例:

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

要获取发送的变量,请在Activity2中使用getStringExtra(String):

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

本文收集自互联网,转载请注明来源。

如有侵权,请联系[email protected] 删除。

编辑于
0

我来说两句

0条评论
登录后参与评论

相关文章

来自分类Dev

为什么要使用意图创建活动?

来自分类Dev

使用意图在活动之间传递数据

来自分类Dev

如何使用意图打开“添加Google帐户”活动?

来自分类Dev

使用意图将数据结果返回到父活动

来自分类Dev

使用void传递变量*

来自分类Dev

使用意图将价值从一项活动传递到另一项活动

来自分类Dev

使用意图更新UI

来自分类Dev

android setOnItemClickListener不能使用意图来传递数据

来自分类Dev

在OncheckedChanged内部使用意图

来自分类Dev

使用意图传递数组

来自分类Dev

使用意图在活动之间导航

来自分类Dev

使用意图启动应用

来自分类Dev

如何使用意图在此处传递信息

来自分类Dev

在类中使用意图,不会扩展活动

来自分类Dev

如何使用意图回去

来自分类Dev

以意图启动AlertDialog并使用意图传递数据?

来自分类Dev

使用意图传递可包裹对象时出错

来自分类Dev

使用意图控制其他活动

来自分类Dev

使用意图将数据从clicklistener发送到活动

来自分类Dev

使用委托传递变量

来自分类Dev

android setOnItemClickListener不能使用意图来传递数据

来自分类Dev

Android:使用意图开始任何活动

来自分类Dev

使用意图与多个活动进行应用程序通信

来自分类Dev

如何使用意图传递对象列表?

来自分类Dev

无法使用意图将从RelativeLayout创建的图像传递给新活动

来自分类Dev

使用意图将数组列表从一个活动传递到另一个活动时,未经检查的强制转换错误

来自分类Dev

使用意图传递来自其他活动的数据并显示在列表视图中

来自分类Dev

使用意图传递文件路径,但是如何在另一个活动中获取每个文件的路径?

来自分类Dev

Android Java - 使用意图将值传递给第二个活动

Related 相关文章

热门标签

归档