简体   繁体   中英

Access a varibale from MainActivity class to another class

I have a JSONObject in my MainActivity under a function and I want to use it outside the function and in another class, how can I do that?

I want to make this variable public , here is the code :

public void ListDrwaer() {
        List<Map<String, String>> productList = new ArrayList<Map<String, String>>();

        try {
            JSONObject jsonResponse = new JSONObject(jsonResult);
            JSONArray jsonMainNode = jsonResponse.optJSONArray("products");

            for (int i = 0; i < jsonMainNode.length(); i++) {
                JSONObject jsonChildNode = jsonMainNode.getJSONObject(i);

            }
          //  System.out.println("*****JARRAY*****" + jsonMainNode.getJSONObject(0));
            List<Map<String, String>> productLista = new ArrayList<Map<String, String>>();
            JSONObject pro1 = jsonMainNode.getJSONObject(1);
            String data = pro1.getString("name");
        //    System.out.println("*****JARRAY*****" + data);


            System.out.println("*****JARRAY*****" + pro1);



        } catch (JSONException e) {
            Toast.makeText(getApplicationContext(), "Error" + e.toString(),
                    Toast.LENGTH_SHORT).show();
        } 

I want to make pro1 (which is JSONObject ) public and use it outside public void and also use it in another class.

Can I do that using put or add?

try code below, it might help..

Intent intent = new Intent(getBaseContext(), SignoutActivity.class);
intent.putExtra("EXTRA_SESSION_ID", sessionId);
startActivity(intent);

You will need to create the variable first outside any method like this

Static JSONObject pro1;

and then acces it simple by using

classname.pro1
  1. you can declare that variable public. just put

    public static JSONObject pro1;

to your class declaration. 2. that is not safe because of: 1. that variable will vanish if your app will be killed and recreated by Android system. 2. you should be carefull when accessing that variable from other threads.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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