0

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

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

我想将 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)");
        }

    }

片段1.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();
    }

}

片段1.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>

主.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>
4

2 回答 2

1

在java中,字符串必须与equalsor进行比较equalsIgnoreCase

 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);
于 2013-06-15T18:21:20.473 回答
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));
     }

现在它不起作用,因为您试图在错误的位置和错误的时间获取/设置列表数据。阅读有关片段片段/活动生命周期的信息。

于 2013-06-15T18:24:27.470 回答