-2

I have this json data

{
  "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
    }, 
   
  ]
}

And I parsed this json file and added it to a navigation drawer. On the navigation drawer all I have is the name of each categories. When a user clicked on the categories there is another json that I wanted to parse which lists the items in a recycler view. For example I am using like this: http://mydomain/category/id/videos I want to replace the id with the one that is clicked(from the json) and get the list of items from the Internet. But I don't know how to get the id and pass it through an intent. Is there some kind of design guideline I should use to handle such kind of issues?

 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;
        }

The problem is I can get the name of the category using findViewById. But where shall I store the id of each categories?

Caffeinatedwolf
  • 1,217
  • 3
  • 20
  • 26

2 Answers2

1

try this.First you are loading categories.

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));
        }

}

Then load navigation drawer list

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);

    }

}

This is the second Activity.Inside the onCreate() ,get the id which was passed in the previous intent.

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");


    }

}
Tharanga
  • 377
  • 3
  • 8
  • 18
0

Make a model as per your json file as below and

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;
    }

    }


    }

then you can send whole object of model to another activity by:

FirstActivity.class

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

SecondActivity.class // To retrieve object in second Activity

getIntent().getSerializableExtra("MyClass")
Android Geek
  • 596
  • 8
  • 14