将JSON数组数据放在Hashmap中并通过Intent Extra传递它

时间:2014-08-26 12:39:39

标签: java android json android-intent arrays

在我的应用程序中,我通过执行find" findviewByid成功实现了通过Intent将JSON对象传递给新活动。"

现在这是一个餐厅查找应用程序,每个餐厅都有几张菜单照片。我正在遍布stackoverflow找到它,但无法实现。

这是我的JSON文件的一部分:

[
{
login_id: "6",

name: "Urban Spice",

location: "banani",

latitude: "23.790327",

longitude: "90.409007",

address: "House- 119, Road-11, Block-E, Banani",
rating: "4.00",

costfortwopeople: "0",

openingclosingtime: "",

type: "restaurant,ice cream parlour",

perks: "kids zone,home delivery,catering",

cuisine: "indian,indonesian",

phone: "01777899901,2,3,9862672",

image: - [

"http://www.petuuk.com/restaurant_images/img_2146.jpg",

"http://www.petuuk.com/restaurant_images/img_2147.jpg"
],

menu: - [

"http://www.petuuk.com/restaurant_images/.jpg",
"http://www.petuuk.com/restaurant_images/.jpg",
"http://www.petuuk.com/restaurant_images/.jpg",
"http://www.petuuk.com/restaurant_images/.jpg",
"http://www.petuuk.com/restaurant_images/.jpg",
"http://www.petuuk.com/restaurant_images/.jpg",
"http://www.petuuk.com/restaurant_images/.jpg",
"http://www.petuuk.com/restaurant_images/.jpg"
]
},

 {

login_id: "7",

name: "The Sky Room Dining",

location: "banani",

latitude: "23.793972",

longitude: "90.403190",

address: "ABC House, 12th Floor, 8 Kemal Ataturk Avenue, Banani",

rating: "4.00",

costfortwopeople: "0",

openingclosingtime: "",

type: "restaurant",

perks: "rooftop view,catering",

cuisine: "thai,indian",

phone: "01675019211,9822017",

image: - [
"http://www.petuuk.com/restaurant_images/img_2204.jpg",
"http://www.petuuk.com/restaurant_images/img_2205.jpg",
"http://www.petuuk.com/restaurant_images/img_2206.jpg"
],  etc..................................................................

我很难检索JSON数组"菜单"和"图像"从上面的JSON输出。我能够检索其他JSON对象,例如login_id,name,location等。

我想在这里实现的主要目标是,在Listview中加载所有数据,用户可以在其中搜索餐馆,然后当用户点击特定餐馆时,所有加载的数据都应该进入&# 34; Intent.putExtra"在新活动中查看完整的餐厅资料视图。

这些是我的" SeachAll"我需要帮助的活动。这是用于从JSON文件中检索数据的for循环。我需要帮助来检索"图像"和"菜单"然后将它放入我的hashmap。

 protected String doInBackground(String... arg) {
        //building parameters
        List<NameValuePair> params = new ArrayList<NameValuePair>();

        //Getting JSON from URL
        String json = jsonParser.makeHttpRequest(URL_RESTAURANT_LIST, "GET", params);

        //Log Cat Response Check
        Log.d("Areas JSON: ", "> " + json);

        try {
            restaurants = new JSONArray(json);

            if (restaurants != null) {
                //loop through all restaurants
                for (int i = 0; i < restaurants.length(); i++) {
                    JSONObject c = restaurants.getJSONObject(i);

                    //Storing each json  object in the variable.
                    String id = c.getString(TAG_ID);
                    String name = c.getString(TAG_NAME);
                    String location = c.getString(TAG_LOCATION);
                    String rating = c.getString(TAG_RATING);`  HashMap<String, String>  map = new HashMap<String, String>();

                    //adding each child node to Hashmap key
                    map.put(TAG_ID, id);
                    map.put(TAG_NAME, name);
                    map.put(TAG_LOCATION, location);
                    map.put(TAG_RATING, rating);


                    //adding HashList to ArrayList
                    restaurant_list.add(map);
                }

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

这是我的onItemClick。需要帮助来放置数组,我不知道是否可以传递json数组就像我在下面做的json对象一样。

ListView lv = getListView();
    lv.setOnItemClickListener(new AdapterView.OnItemClickListener() {
        @Override
        public void onItemClick(AdapterView<?> parent, View view, int position, long id) {

            Intent intent = new Intent(getApplicationContext(), RestaurantProfile.class);
            String loginId = ((TextView) view.
                    findViewById(R.id.login_id)).
                    getText().toString();

            String res_name = ((TextView) view.
                    findViewById(R.id.restaurant_name)).
                    getText().toString();


            intent.putExtra(TAG_ID, loginId);
            intent.putExtra(TAG_NAME, res_name);

            startActivity(intent);


        }
    });

所以简而言之,我需要帮助两件事,

1。检索JSON数组&#34;图像&#34;和&#34;菜单&#34;来自JSON文件的URLS并将其放在Hashmap中。

2。将此数据放入我的Intent以传递给新活动。

这是我的完整代码&#34; SearchAll&#34;活性。

public class SearchAll extends ListActivity {

ConnectionDetector cd;
AlertDialogManager alert = new AlertDialogManager();

//Progress Dialog
private ProgressDialog pDialog;

//make json parser Object
JSONParser jsonParser = new JSONParser();

ArrayList<HashMap<String, String>> restaurant_list;

//Restaurant Json array
JSONArray restaurants = null;

private static final String URL_RESTAURANT_LIST 
  = "http://www.petuuk.com/android/allRestaurantList2.php";

//all JSON Node Names
private static final String TAG_ID = "login_id";
private static final String TAG_NAME = "name";
private static final String TAG_LOCATION = "location";
private static final String TAG_LAT = "lattitude";
private static final String TAG_LONG = "longitude";
private static final String TAG_ADDRESS = "address";
private static final String TAG_COST_2 = "costfortwopeople";
private static final String TAG_TYPE = "type";
private static final String TAG_PERKS = "perks";
private static final String TAG_CUISINE = "cuisne";
private static final String TAG_PHONE = "phone";
private static final String TAG_RATING = "rating";
private static final String TAG_IMAGE = "image";
private static final String TAG_MENU = "menu";
private static final String TAG_TIMING = "openingclosingtime";

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_search_all);

    cd = new ConnectionDetector(getApplicationContext());

    //Check for Internet Connection
    if (!cd.isConnectingToInternet()) {
        //Internet connection not present
        alert.showAlertDialog(SearchAll.this, "Internet Connection Error",
                "Please Check Your Internet Connection", false);
        //stop executing code by return
        return;
    }

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



    //get ListView
    ListView lv = getListView();
    lv.setOnItemClickListener(new AdapterView.OnItemClickListener() {
        @Override
   public void onItemClick(AdapterView<?> parent, View view, int position, long id) {

      Intent intent = new Intent(getApplicationContext(), RestaurantProfile.class);
            String loginId = ((TextView) view.
                    findViewById(R.id.login_id)).
                    getText().toString();

            String res_name = ((TextView) view.
                    findViewById(R.id.restaurant_name)).
                    getText().toString();


            intent.putExtra(TAG_ID, loginId);
            intent.putExtra(TAG_NAME, res_name);

            startActivity(intent);


        }
    });

    lv.setOnScrollListener(new EndlessScrollListener() {
        @Override
        public void onLoadMore(int page, int totalItemsCount) {

        }
    });

    new LoadRestaurants().execute();



}


class LoadRestaurants extends AsyncTask<String, String, String> {

    //Show Progress Dialog
    @Override
    protected void onPreExecute() {
        super.onPreExecute();
        pDialog = new ProgressDialog(SearchAll.this);
        pDialog.setMessage("Loading All Restaurants...");
        pDialog.setIndeterminate(false);
        pDialog.setCancelable(false);
        pDialog.show();
    }

    protected String doInBackground(String... arg) {
        //building parameters
        List<NameValuePair> params = new ArrayList<NameValuePair>();

        //Getting JSON from URL
        String json = jsonParser.makeHttpRequest(URL_RESTAURANT_LIST, "GET", params);

        //Log Cat Response Check
        Log.d("Areas JSON: ", "> " + json);

        try {
            restaurants = new JSONArray(json);

            if (restaurants != null) {
                //loop through all restaurants
                for (int i = 0; i < restaurants.length(); i++) {
                    JSONObject c = restaurants.getJSONObject(i);

                    //Storing each json  object in the variable.
                    String id = c.getString(TAG_ID);
                    String name = c.getString(TAG_NAME);
                    String location = c.getString(TAG_LOCATION);
                    String rating = c.getString(TAG_RATING);
                    String address = c.getString(TAG_ADDRESS);
                    String latitude = c.getString(TAG_LAT);
                    String longitude = c.getString(TAG_LONG);
                    String costfor2 = c.getString(TAG_COST_2);
                    String timing = c.getString(TAG_TIMING);
                    String type = c.getString(TAG_TYPE);
                    String perks = c.getString(TAG_PERKS);
                    String cuisine = c.getString(TAG_CUISINE);
                    String phone = c.getString(TAG_PHONE);


                    JSONArray menuArray = c.getJSONArray("menu");
                    JSONArray imagesArray = c.getJSONArray("image");


                    //Creating New Hashmap
                    HashMap<String, String>  map = new HashMap<String, String>();

                    //adding each child node to Hashmap key
                    map.put(TAG_ID, id);
                    map.put(TAG_NAME, name);
                    map.put(TAG_LOCATION, location);
                    map.put(TAG_RATING, rating);
                    for(int m=0;m<menuArray.length();++m){
                        map.put("MENU_" + m,menuArray.getString(m));
                    }//menu for loop
                    map.put("TOTAL_MENU", menuArray.length());


              //      map.put(TAG_MENU, String.valueOf(menu));

                    //adding HashList to ArrayList
                    restaurant_list.add(map);
                }

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

        return null;
    }

    protected void onPostExecute(String file_url) {

        //dismiss the dialog
        pDialog.dismiss();


        //Updating UI from the Background Thread
        runOnUiThread(new Runnable() {
            @Override
            public void run() {

                ListAdapter adapter = new SimpleAdapter(
                        SearchAll.this, restaurant_list,
                        R.layout.listview_restaurants, new String[]{
                        TAG_ID, TAG_NAME, TAG_LOCATION, TAG_RATING}, new int[]{
                  R.id.login_id, R.id.restaurant_name, R.id.location,  R.id.rating});

                setListAdapter(adapter);


            }
        });


    }
}

}

2 个答案:

答案 0 :(得分:0)

不确定这正是您所需要的,但您可能会从中获得一些想法

首先,要从餐厅获取图像和菜单数组,您需要这个

在for循环中,你得到json对象(c)

JSONObject c = restaurants.getJSONObject(i);
JsonArray menuArray = c.getJsonArray("menu");
JsonArray imagesArray = c.getJsonArray("image");

你可以使用for循环

在menuArray和imagesArray项之间循环
imagesArray.getString(index);

现在,由于您已将地图声明为< String, String >,因此无法在一个字符串中指定多个值(图像或菜单项),

所以要么你找到另一种方法来构建你的数据, 或创建另外2个地图,menuPam,将餐馆ID作为键的imageMap,以及作为菜单和图像条目值的String。

在读取餐馆对象的for循环中:

for (int i = 0; i < restaurants.length(); i++) {
    :
    :
    map.put(TAG_ID, id);
    map.put(TAG_NAME, name);
    :
    :

    JsonArray menuArray = c.getJsonArray("menu");
    for(int m=0;m<menuArray.length();++m){
        menuMap.add(id,menuArray.getString(m));
    }//menu for loop

    //another for loop for imageArray...
}//end of restaurants loop

但是你必须将menuMap和imageMap添加到一个名为menus,images ...的数组列表中。

为什么不创建一个对象来保存关于餐馆的所有信息

class restaurant{
private String name="", id =""....
//setters and getters ...

String menuItems[] = null;
String imageItems[] = null;

//setters getters for the arrays.
}

}

修改 这个sol不需要新的地图,只需将图像和菜单添加到同一个地图中 使用动态密钥名称

for(int m=0;m<menuArray.length();++m){
    map.add("MENU_" + m,menuArray.getString(m));
}//menu for loop
map.add("TOTAL_MENU", Integer.toString(menuArray.length()));

您可以使用上面的代码,将菜单项添加到地图中 和图像一样,“IMAGE _”+ m 和TOTAL_IMAGES

现在在目标活动中,循环读取所有IMAGE_n和MENU_n 从0到TOTAL_IMAGES,以及TOTAL_MENU

答案 1 :(得分:0)

简而言之,您不能将所有数据从一个活动传递到另一个活动。您应该将餐馆ID传递给新的活动,并使用该ID来提取餐馆的数据。

您应该将您的餐厅列表视为MVC架构中的模型(部分)。它应该与您的活动(控制器)分开。模型是您的数据专家,它将您的数据保存在内存,文件或数据库中,并且它在任何特定活动的生命周期中都存在。您不能将模型从一个活动传递到另一个活动。创建一个Activity后,它会抓取Model(如果Model是Singleton)或者Model被注入到该Activity中(依赖注入,我更喜欢的框架是Dagger)。然后,Activity可以从Model中请求任何特定数据并呈现其View。它还可以观察模型中的任何进一步变化并相应地更新其视图。