Android:在Activity和Fragments之间传递HashMap

时间:2013-06-15 18:18:02

标签: android json android-fragments

我是Android开发的新手,我在应用程序开发中遇到了停顿。我希望有人可以帮助我。

我有一个名为JSONActivity的活动,在JSONActivity中,我从网址中提取JSON数据,并将其存储到3个HashMaps中,具体取决于数据类型。

我想将HashMap传递给3个不同的片段。我将从一个片段开始,但我似乎无法传递数据。

有人可以指出我做错了什么,以及我能做些什么来解决它?

我可以确保json提取工作正常,因为可以使用Toast

呈现数据

JSONActivity.java

package com.example.json;

import android.os.Bundle;
import java.io.BufferedReader;
import java.io.IOException;
import android.app.Activity;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.HashMap;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.StatusLine;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;
import org.json.JSONArray;
import org.json.JSONObject;
import android.util.Log;
import android.os.AsyncTask;


public class JSONActivity extends Activity {

    HashMap<Integer,String> imageList = new HashMap<Integer,String>();
    HashMap<Integer,String> textList = new HashMap<Integer,String>();
    HashMap<Integer,String> otherList = new HashMap<Integer,String>();
    private static final String ID = "id";
    private static final String TYPE = "type";
    private static final String DATA = "data";

    public String readJSONFeed(String URL) {
        StringBuilder stringBuilder = new StringBuilder();
        HttpClient client = new DefaultHttpClient();
        HttpGet httpGet = new HttpGet(URL);
        try {
            HttpResponse response = client.execute(httpGet);
            StatusLine statusLine = response.getStatusLine();
            int statusCode = statusLine.getStatusCode();
            if (statusCode == 200) {
                HttpEntity entity = response.getEntity();
                InputStream content = entity.getContent();
                BufferedReader reader = new BufferedReader(
                        new InputStreamReader(content));
                String line;
                while ((line = reader.readLine()) != null) {
                    stringBuilder.append(line);
                }
            } else {
                Log.e("JSON", "Failed to download file");
            }
        } catch (ClientProtocolException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return stringBuilder.toString();

    }

    private class ReadJSONFeedTask extends AsyncTask<String, Void, String> {
        protected String doInBackground(String... urls) {
            return readJSONFeed(urls[0]);
        }

        protected void onPostExecute(String result) {

            try {
                JSONArray jsonArray = new JSONArray(result);
                Log.i("JSON", "Number of json items: " +
                        jsonArray.length());
                //---print out the content of the json feed---
                for (int i = 0; i < jsonArray.length(); i++) {
                    JSONObject jsonObject = jsonArray.getJSONObject(i);
                    int id = jsonObject.getInt(ID);
                    String type = jsonObject.getString(TYPE);
                    String data = jsonObject.getString(DATA);

                if(type.equals("text"))
                    textList.put(id,data);
                else if(type.equals("other"))
                    otherList.put(id,data);
                else if(type.equals("image"))
                    imageList.put(id,data);


                    // Toast.makeText(getBaseContext(), jsonObject.getString("type") +
                    //      " - " + jsonObject.getString("data"), Toast.LENGTH_SHORT).show();
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }
        /** Called when the activity is first created. */
        @Override
        public void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);

            setContentView(R.layout.main);
            new ReadJSONFeedTask().execute(
                    "sample url (not shown in this post)");
        }

    }

Fragment1.java:

package com.example.json;


import java.util.HashMap;
import android.os.Bundle;
import android.support.v4.app.ListFragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.ListView;
import android.widget.Toast;

public class fragment1 extends ListFragment {
    @SuppressWarnings("unchecked")
    public HashMap<Integer,String> textList = 
            (HashMap<Integer, String>) getArguments().getSerializable("textList");
    public String[] vals = new String[textList.size()];

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
            Bundle savedInstanceState) {
        for(int i = 0; i < textList.size(); i++)
            vals[i] = (String)textList.values().toArray()[i];

        return inflater.inflate(R.layout.fragment1, container, false);
    }

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setListAdapter(new ArrayAdapter<String>(getActivity(),
                android.R.layout.simple_list_item_1, vals));
    }

    public void onListItemClick(ListView parent, View v, int position, long id)
    {
        Toast.makeText(getActivity(),
                "You have selected " + vals[position], Toast.LENGTH_SHORT).show();
    }

}

fragment1.xml:

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:orientation="vertical" >

    <ListView
        android:id="@id/android:list"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:layout_weight="1"
        android:drawSelectorOnTop="false" />

</LinearLayout>

main.xml中

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:orientation="horizontal" >

    <fragment
        android:id="@+id/fragment1"
        android:name="com.example.json.Fragment1"
        android:layout_width="0dp"
        android:layout_height="200dp"
        android:layout_weight="0.5" />

    <fragment
        android:id="@+id/fragment2"
        android:name="com.example.json.Fragment1"
        android:layout_width="0dp"
        android:layout_height="300dp"
        android:layout_weight="0.5" />

</LinearLayout>

2 个答案:

答案 0 :(得分:1)

在java中,必须将字符串与equalsequalsIgnoreCase

进行比较
 if(type.equals("text"))
    textList.put(id,data);
 else if(type.equals("other")) 
    otherList.put(id,data);
 else if(type.equals("image")) 
    imageList.put(id,data);

答案 1 :(得分:1)

您需要在片段中定义一个setter方法,该方法将设置片段的HashMap属性并将其显示给用户。在完成解析json数据之后,请调用它:

((Fragment1) getSupportFragmentManager.findFragmentById(R.id.fragment1)).setAndDisplayJSONDataMethod(valuesToShow);

setAndDisplayJSONDataMethod方法将是这样的:

     public void setAndDisplayJSONDataMethod(HashMap<Integer, String> valuesToShow) {
     String[] vals = new String[textList.size()];
     for(int i = 0; i < textList.size(); i++)
         vals[i] = (String)valuesToShow.values().toArray()[i];
         setListAdapter(new ArrayAdapter<String>(getActivity(),
                android.R.layout.simple_list_item_1, vals));
     }

现在它不起作用,因为你试图在错误的地方和错误的时间内获取/设置列表数据。阅读FragmentsFragments / Actvities生命周期。