如何从另一个函数获取java中的hashmap键和值

时间:2014-07-30 10:50:54

标签: java android json hashmap

我有像这样的json解析

public class SecondFragment extends Fragment implements OnClickListener {


// URL to get contacts JSON
private static String contestUrl = "http://api.apps.com/contest";

// JSON Node names
private static final String TAG_ITEM_ID = "id";    
private static final String TAG_URL = "url";    
private static final String TAG_START_DATE = "start_date";    
private static final String TAG_END_DATE = "end_date";   

// contacts JSONArray
JSONArray foods = null;

// Hashmap for ListView
ArrayList<HashMap<String, String>> foodslist;



}

@Override
public void onActivityCreated(Bundle savedInstanceState) {
    // TODO Auto-generated method stub
    super.onActivityCreated(savedInstanceState);

    foodslist = new ArrayList<HashMap<String, String>>();




 // Calling async task to get json
    new GetContacts().execute();

}

/**
 * Async task class to get json by making HTTP call
 * */
private class GetContacts extends AsyncTask<Void, Void, Void> {
    @Override
    protected Void doInBackground(Void... arg0) {
        // Creating service handler class instance
        ServiceHandler sh = new ServiceHandler();

        // Making a request to url and getting response
        String jsonStr = sh.makeServiceCall(contestUrl, ServiceHandler.GET);

        Log.d("Response: ", "> " + jsonStr);

        if (jsonStr != null) {
            try {

                foods = new JSONArray(jsonStr);

                // looping through All Contacts
                for (int i = 0; i < foods.length(); i++) {
                    JSONObject c = foods.getJSONObject(i);

                    String id = c.getString(TAG_ITEM_ID);
                    String name = c.getString(TAG_URL);
                    String email = c.getString(TAG_START_DATE);
                    String address = c.getString(TAG_END_DATE);

                    // tmp hashmap for single contact
                    HashMap<String, String> contact = new HashMap<String, String>();

                    // adding each child node to HashMap key => value
                    contact.put(TAG_ITEM_ID, id);
                    contact.put(TAG_URL, name);
                    contact.put(TAG_START_DATE, email);
                    contact.put(TAG_END_DATE, address);

                    String start_date = (String)contact.get(TAG_ITEM_ID);

                    // adding contact to contact list
                    foodslist.add(contact);
                }
            } catch (JSONException e) {
                e.printStackTrace();
            }
        } else {
            Log.e("ServiceHandler", "Couldn't get any data from the url");
        }

        return null;
    }
}

}

我有两个功能onCreateGetContacts。在onCreate结束时,它会调用GetContacts并调用此json。

我的问题是,如何在Hashmap上获得GetContacts值,以便我可以在onCreate上使用

到目前为止,我得到了这个以获得Hashmap

的值

String start_date = (String)contact.get(TAG_ITEM_ID);

但是,它仅适用于GetContacts。 有人可以帮帮我吗?

先谢谢

3 个答案:

答案 0 :(得分:1)

你有

List<Map<String,String>> foodslist = ...;

填充在循环中。

要获得单个值,请迭代:

for( Map<String,String> item: foodslist ){
   String id = item.get(TAG_ITEM_ID);
   String name = item.get(TAG_URL);
   String email = item.get(TAG_START_DATE);
   String address = item.get(TAG_END_DATE);
}

或者你为保留食物清单的班级写了一个方法:

String getAttr( int i, String tag ){
    return foodslist.get(i).get(tag);
} 

你可以致电

String id = xxx.getAttr( i, TAG_ITEM_ID );

答案 1 :(得分:1)

有几种方法:

<强>路-1: 创建HashMap联系人的实例变量(类级别),然后您可以在包含onCreate和getContacts方法的类中的任何位置使用它。

package stackoverflow.q_25034927;

import java.util.HashMap;
import java.util.Map;

public class PassVariable {
    private static Map<String, String> contact = new HashMap<String, String>();

    public void onCreate() {
        //populate contact object as per your logic
        getContacts();
    }

    private void getContacts() {
        //Use contact object directly which was pre-populby onCreate method.
    }
}

<强>路-2: 将映射传递给getContacts()方法:

package stackoverflow.q_25034927;

import java.util.HashMap;
import java.util.Map;

public class PassVariable {

    public void onCreate() {
        final Map<String, String> contact = new HashMap<String, String>();
        //populate contact object as per your logic.
        getContacts(contact);
    }

    private void getContacts(Map<String, String> contact) {
        //Use contact object which is passed as argument.
    }
}

另一方面,请在命名Java方法或变量时使用cameCasing。 GetContacts不对,把它变成getContacts。

对于电子邮件和地址字段,使用TAG_START_DATE和TAG_END_DATE并不好玩。 : - )

String email = c.getString(TAG_START_DATE);
String address = c.getString(TAG_END_DATE);

要回答下面的#3,在NotInner类中无法访问变量s:

package com.test;

public class Test {
    static String s = "";
}

class NotInner {
    public static void main(String[] args) {
        System.out.println(s); //Compilation error: s cannot be resolved to a variable
    }
}

答案 2 :(得分:0)

所以返回数据......

public List<Map<String, String>> getContacts() {
if (foodslist != null && foodslist.isEmpty()) {
    return foodslist;
}
foodslist = new ArrayList<Map<String, String>>();
try {

foods = new JSONArray(jsonStr);

// looping through All Contacts
for (int i = 0; i < foods.length(); i++) {
   JSONObject c = foods.getJSONObject(i);

   String id = c.getString(TAG_ITEM_ID);
   String name = c.getString(TAG_URL);
   String email = c.getString(TAG_START_DATE);
   String address = c.getString(TAG_END_DATE);

   // tmp hashmap for single contact
   HashMap<String, String> contact = new HashMap<String, String>();

   // adding each child node to HashMap key => value
   contact.put(TAG_ITEM_ID, id);
   contact.put(TAG_URL, name);
   contact.put(TAG_START_DATE, email);
   contact.put(TAG_END_DATE, address);

   // adding contact to contact list
   foodslist.add(contact);
}
return foodslist;
}

虽然我不确定为什么该变量被称为foodslist,如果它应该包含联系人。