Android将JSON数据传递给另一个活动

时间:2015-06-29 07:51:36

标签: android json

我有这个json数据

{
  "Categories": [
        {
      "description": "", 
      "id": 33, 
      "name": "News", 
      "parent_id": 0, 
      "position": 3, 
      "published_videos": 953, 
      "tag": "news", 
      "total_videos": 953
    }, 
    {
      "description": "", 
      "id": 34, 
      "name": "Health", 
      "parent_id": 0, 
      "position": 22, 
      "published_videos": 17, 
      "tag": "tena", 
      "total_videos": 17
    }, 
    {
      "description": "", 
      "id": 35, 
      "name": "Interview", 
      "parent_id": 0, 
      "position": 23, 
      "published_videos": 271, 
      "tag": "qalemeteyeq", 
      "total_videos": 271
    }, 
    {
      "description": "", 
      "id": 36, 
      "name": "Trailers", 
      "parent_id": 0, 
      "position": 21, 
      "published_videos": 72, 
      "tag": "movie", 
      "total_videos": 72
    }, 
    {
      "description": "", 
      "id": 37, 
      "name": "Technology", 
      "parent_id": 0, 
      "position": 24, 
      "published_videos": 17, 
      "tag": "technology", 
      "total_videos": 17
    }, 
  
      "description": "", 
      "id": 39, 
      "name": "International News", 
      "parent_id": 33, 
      "position": 1, 
      "published_videos": 319, 
      "tag": "international_news", 
      "total_videos": 319
    }, 
   
  ]
}

我解析了这个json文件并将其添加到导航抽屉中。在导航抽屉上我只有每个类别的名称。当用户点击类别时,我想解析另一个json,它列出了回收站视图中的项目。例如我使用这样的: http://mydomain/category/id/videos 我想将id替换为点击的(来自json),并从Internet获取项目列表。 但我不知道如何获取id并通过意图传递它。 是否有某种设计指南我应该用来处理这类问题?

 private String[] getCategoriesJson(String categoriesJsonStr)
                throws JSONException {
            JSONObject categoriesJSON = new JSONObject(categoriesJsonStr);
            JSONArray categoriesArray = categoriesJSON.getJSONArray("Categories");
            String[] resultStrs = new String[categoriesArray.length()+1];
            resultStrs[0] = "Home";
            for (int i=0; i< categoriesArray.length(); i++){
                JSONObject category = categoriesArray.getJSONObject(i);
                String name = category.getString("name");
                Integer categoryId = category.getInt("id");
                //Integer parentId = category.getInt("parent_id");
                resultStrs[i+1] = name;
            }
            for (String s: resultStrs){
                Log.v(LOG_TAG, "Category entry: " + s);
            }

            return resultStrs;
        }

        @Override
        protected String[] doInBackground(String... params) {
            HttpURLConnection urlConnection = null;
            BufferedReader reader = null;
            String categoriesJsonstr = null;

            try {
                URL url = new URL("http://mydomain/categories/");
                urlConnection = (HttpURLConnection) url.openConnection();
                urlConnection.setRequestMethod("GET");
                urlConnection.connect();

                InputStream inputStream = urlConnection.getInputStream();
                StringBuffer buffer =  new StringBuffer();
                if (inputStream == null) {
                    return null;
                }
                reader = new BufferedReader(new InputStreamReader(inputStream));
                String line;
                while((line = reader.readLine()) != null){
                    buffer.append(line + "\n");
                }
                if (buffer.length() == 0) {
                    return null;
                }
                categoriesJsonstr = buffer.toString();
                //Log.v(LOG_TAG, "Categories JSON String: " + categoriesJsonstr);
            }catch (IOException e) {
                Log.e(LOG_TAG, "Error", e);
                return  null;
            }finally {
                if (urlConnection != null){
                    urlConnection.disconnect();
                }
                if (reader != null) {
                    try {
                        reader.close();
                    }catch (final IOException e){
                        Log.e(LOG_TAG, "Error closing stream", e);
                    }
                }
            }

            try {
                return getCategoriesJson(categoriesJsonstr);
            }catch (JSONException e){
                Log.e(LOG_TAG, e.getMessage(), e);
                e.printStackTrace();
            }

            return null;
        }

问题是我可以使用findViewById获取类别的名称。但是我应该在哪里存储每个类别的ID?

2 个答案:

答案 0 :(得分:1)

试试这个。首先你要加载类别。

private JSONArray categoriesJSONArray = new JSONArray();

public class AsyncHttpTaskLoadCategories extends AsyncTask<String, Void, Integer> {

        @Override
        protected String[] doInBackground(String... params) {
            HttpURLConnection urlConnection = null;
            BufferedReader reader = null;
            String categoriesJsonstr = null;

            try {
                URL url = new URL("http://mydomain/categories/");
                urlConnection = (HttpURLConnection) url.openConnection();
                urlConnection.setRequestMethod("GET");
                urlConnection.connect();

                InputStream inputStream = urlConnection.getInputStream();
                StringBuffer buffer =  new StringBuffer();
                if (inputStream == null) {
                    return null;
                }
                reader = new BufferedReader(new InputStreamReader(inputStream));
                String line;
                while((line = reader.readLine()) != null){
                    buffer.append(line + "\n");
                }
                if (buffer.length() == 0) {
                    return null;
                }
                categoriesJsonstr = buffer.toString();
                //Log.v(LOG_TAG, "Categories JSON String: " + categoriesJsonstr);

                //create JSONArray
                categoriesJSONArray = new JSONArray(categoriesJsonstr);

            }catch (Exception e) {
                Log.e(LOG_TAG, "Error", e);
                return  null;
            }finally {
                if (urlConnection != null){
                    urlConnection.disconnect();
                }
                if (reader != null) {
                    try {
                        reader.close();
                    }catch (final IOException e){
                        Log.e(LOG_TAG, "Error closing stream", e);
                    }
                }
            }

        }

        @Override
        protected void onPostExecute(Integer result) {

            //listView NavDrawer
            listViewND = (ListView)rootView.findViewById(R.id.list_view_nav_drawer);
            listViewND.setAdapter(new NavDrawerListAdapter(CONTEXT,categoriesJSONArray));
        }

}

然后加载导航抽屉列表

public class NavDrawerListAdapter extends BaseAdapter implements View.OnClickListener{

    static class ViewHolder {
        public int position;
        public TextView rowCatName;
    }

    private Context context;
    private JSONArray categoriesJSONArray;

    public NavDrawerListAdapter(Context context, JSONArray categoriesJSONArray){
        this.context = context;
        this.categoriesJSONArray = categoriesJSONArray;
    }

    @Override
    public int getCount() {
        return categoriesJSONArray.length();
    }

    @Override
    public Object getItem(int position) {       
        try {
            return categoriesJSONArray.get(position);
        }catch(Exception e){
            return null;
        }
    }

    @Override
    public long getItemId(int position) {
        return position;
    }

    @Override
    public View getView(int position, View convertView, ViewGroup parent) {
        if (convertView == null) {
            LayoutInflater mInflater = (LayoutInflater)
                    context.getSystemService(Activity.LAYOUT_INFLATER_SERVICE);
            convertView = mInflater.inflate(R.layout.drawer_list_item, null);

            ViewHolder viewHolder = new ViewHolder();
            viewHolder.rowCatName = (TextView) convertView.findViewById(R.id.txt_ride_driver_id);


            convertView.setOnClickListener(this);
            convertView.setTag(viewHolder);
        }

        ViewHolder viewHolder = (ViewHolder)convertView.getTag();
        try{
            viewHolder.position = position;
            JSONObject categoriesJSONObj = categoriesJSONArray.getJSONObject(position);
            //get category neme 
            String name = categoriesJSONObj.getString("name");

            viewHolder.rowCatName.setText(name);


        }catch(Exception e){

        }
        return convertView;
    }

    @Override
    public void onClick(View v) {
        ViewHolder viewHolder = (ViewHolder)v.getTag();
        int position = viewHolder.position;
        JSONObject categoriesJSONObj = categoriesJSONArray.getJSONObject(position);
        //get category id 
        int id = categoriesJSONObj.getInt("id");

        //put id in Intent
        //go to next categories 
        //recycler view activity
        Intent i = new Intent(CONTEXT,CLASS);
        i.putExtra("ID",id);
        startActivity(i);

    }

}

这是第二个Activity.Inside onCreate(),获取在前一个意图中传递的id。

public class RecyclerViewActivity extends Activity {

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_list);

        int id = getIntent().getExtras().getInt("id");


    }

}

答案 1 :(得分:0)

根据您的json文件创建模型,如下所示

public class Example extends Serializable {

    @SerializedName("Categories")
    @Expose
    private List<Category> categories = null;

    public List<Category> getCategories() {
    return categories;
    }

    public void setCategories(List<Category> categories) {
    this.categories = categories;
    }
    public class Category extends Serializable {

    @SerializedName("description")
    @Expose
    private String description;
    @SerializedName("id")
    @Expose
    private Integer id;
    @SerializedName("name")
    @Expose
    private String name;
    @SerializedName("parent_id")
    @Expose
    private Integer parentId;
    @SerializedName("position")
    @Expose
    private Integer position;
    @SerializedName("published_videos")
    @Expose
    private Integer publishedVideos;
    @SerializedName("tag")
    @Expose
    private String tag;
    @SerializedName("total_videos")
    @Expose
    private Integer totalVideos;

    public String getDescription() {
    return description;
    }

    public void setDescription(String description) {
    this.description = description;
    }

    public Integer getId() {
    return id;
    }

    public void setId(Integer id) {
    this.id = id;
    }

    public String getName() {
    return name;
    }

    public void setName(String name) {
    this.name = name;
    }

    public Integer getParentId() {
    return parentId;
    }

    public void setParentId(Integer parentId) {
    this.parentId = parentId;
    }

    public Integer getPosition() {
    return position;
    }

    public void setPosition(Integer position) {
    this.position = position;
    }

    public Integer getPublishedVideos() {
    return publishedVideos;
    }

    public void setPublishedVideos(Integer publishedVideos) {
    this.publishedVideos = publishedVideos;
    }

    public String getTag() {
    return tag;
    }

    public void setTag(String tag) {
    this.tag = tag;
    }

    public Integer getTotalVideos() {
    return totalVideos;
    }

    public void setTotalVideos(Integer totalVideos) {
    this.totalVideos = totalVideos;
    }
    public Integer getId() {
    return id;
    }

    public void setId(Integer id) {
    this.id = id;
    }

    public String getName() {
    return name;
    }

    public void setName(String name) {
    this.name = name;
    }

    public Integer getParentId() {
    return parentId;
    }

    public void setParentId(Integer parentId) {
    this.parentId = parentId;
    }

    public Integer getPosition() {
    return position;
    }

    public void setPosition(Integer position) {
    this.position = position;
    }

    public Integer getPublishedVideos() {
    return publishedVideos;
    }

    public void setPublishedVideos(Integer publishedVideos) {
    this.publishedVideos = publishedVideos;
    }

    public String getTag() {
    return tag;
    }

    public void setTag(String tag) {
    this.tag = tag;
    }

    public Integer getTotalVideos() {
    return totalVideos;
    }

    public void setTotalVideos(Integer totalVideos) {
    this.totalVideos = totalVideos;
    }

    }

    public Integer getId() {
    return id;
    }

    public void setId(Integer id) {
    this.id = id;
    }

    public String getName() {
    return name;
    }

    public void setName(String name) {
    this.name = name;
    }

    public Integer getParentId() {
    return parentId;
    }

    public void setParentId(Integer parentId) {
    this.parentId = parentId;
    }

    public Integer getPosition() {
    return position;
    }

    public void setPosition(Integer position) {
    this.position = position;
    }

    public Integer getPublishedVideos() {
    return publishedVideos;
    }

    public void setPublishedVideos(Integer publishedVideos) {
    this.publishedVideos = publishedVideos;
    }

    public String getTag() {
    return tag;
    }

    public void setTag(String tag) {
    this.tag = tag;
    }

    public Integer getTotalVideos() {
    return totalVideos;
    }

    public void setTotalVideos(Integer totalVideos) {
    this.totalVideos = totalVideos;
    }

    }


    }

然后您可以通过以下方式将模型的整个对象发送到另一个活动:

FirstActivity.class

Intent in=new Intent(FirstActivity.class,secondActivity.class);
in.putExtra("MyClass", obj);
startActivity(in);

SecondActivity.class //在第二个Activity中检索对象

getIntent().getSerializableExtra("MyClass")