luongkhanh luongkhanh - 1 year ago 64
JSON Question

Combine Activity and fragment into a class android

I want to ask,
I have 2 classes:

1. an activity class (to get data from json)
2. a fragment class (not to do something)

and I want to get data from json of activity via fragment class.
Can be combine Activity and Fragment in a class ? and how to do ?

I combined activity and fragment in a Fragment class, I have used a GridView to get data and display
JSON, execute the AsyncTask in the this Fragment

This is my code after updated 25/10:

public class FeedBackFragment extends Fragment {

ProgressDialog pDialog;
JSONParser jsonParser = new JSONParser();

// ALL JSON node names
private static final String TAG_ID = "id";
private static final String TAG_NAME = "name";
private static final String TAG_ICONNAME = "iconName";
// private static final String TAG_CARS_COUNT = "cars_count";

MyAdapter adapter;
ArrayList<HashMap<String, String>> manufacturersList = new ArrayList<>();
JSONArray manufacturers = null;

// manufacturers JSON url
private static final String URL_MANUFACTURERS = "";

public FeedBackFragment() {
// Required empty public constructor

public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
View view = inflater.inflate(R.layout.feedback_gridview_manufacturer, container, false);

GridView gridView = (GridView) view.findViewById(;
// gridView.setAdapter(new MyAdapter(getActivity(), manufacturersList));

adapter = new MyAdapter(getActivity(), manufacturersList);

gridView.setOnItemClickListener(new android.widget.AdapterView.OnItemClickListener() {
public void onItemClick(AdapterView<?> arg0, View view, int arg2, long arg3) {
// on selecting a single manufacturer
// CategoryCarActivity will be launched to show category car inside the manufacturer
Intent i = new Intent(getActivity(), CategoryCarActivity.class);

// send manufacturer id to activity to get list of cars under that manufacturer
String manufacturer_id = ((TextView) view.findViewById(;
i.putExtra("manufacturer_id", manufacturer_id);


return view;

public void onActivityCreated(Bundle savedInstanceState) {
// TODO Auto-generated method stub

// manufacturersList = new ArrayList<>();
new LoadAllManufacturers().execute();

class LoadAllManufacturers extends AsyncTask<String, String, String> {
* Before starting background thread Show Progress Dialog
* */
protected void onPreExecute() {
pDialog = new ProgressDialog(getActivity());
pDialog.setMessage("Loading manufacturers. Please wait...");
* getting All products from url
* */
protected String doInBackground(String... args) {
// Building Parameters
List<NameValuePair> params = new ArrayList<NameValuePair>();
// getting JSON string from URL
String json = jsonParser.makeHttpRequest(URL_MANUFACTURERS, "GET", params);
// Check your log cat for JSON reponse
Log.d("Manufacturers JSON: ", "> " + json);
try {
manufacturers = new JSONArray(json);

if (manufacturers != null) {
// looping through All Manufacturers
for (int i = 0; i < manufacturers.length(); i++) {
JSONObject c = manufacturers.getJSONObject(i);

// Storing each json item values in variable
String id = c.getString(TAG_ID);
String name = c.getString(TAG_NAME);
String iconName = c.getString(TAG_ICONNAME);
//String cars_count = c.getString(TAG_CARS_COUNT);

// creating new HashMap
HashMap<String, String> map = new HashMap<String, String>();

// adding each child node to HashMap key => value
map.put(TAG_ID, id);
map.put(TAG_NAME, name);
map.put(TAG_ICONNAME, iconName);
// map.put(TAG_CARS_COUNT, cars_count);

// adding HashList to ArrayList
Log.d("Manufacturers: ", "null");

} catch (JSONException e) {

return null;
* After completing background task Dismiss the progress dialog
* **/
protected void onPostExecute(String s) {

// dismiss the dialog after getting all manufacturers
if (pDialog.isShowing())

private class MyAdapter extends BaseAdapter
ArrayList<HashMap<String, String>> manufacturersList = new ArrayList<>();
// List<POJOManufacturer> listData = null;
LayoutInflater inflater;
Context context;

public MyAdapter(Context context, ArrayList<HashMap<String, String>> arrayList)
// this.context = context;
this.manufacturersList = arrayList;
inflater = LayoutInflater.from(context);

public int getCount() {
if (manufacturersList != null)
return manufacturersList.size();
return 0;

public Object getItem(int i)
if (manufacturersList != null)
return manufacturersList.get(i);
return null;

public long getItemId(int i)
if (manufacturersList != null)
return manufacturersList.get(i).hashCode();
return 0;

public View getView(int i, View convertView, ViewGroup viewGroup)
ViewHolder holder;
if (convertView == null)
convertView = inflater.inflate(R.layout.gridview_item, null);
holder = new ViewHolder(); = (TextView) convertView.findViewById(;
holder.iconName = (ImageView) convertView.findViewById(;

else {

holder = (ViewHolder) convertView.getTag();

HashMap<String,String> map = manufacturersList.get(i);;
// holder.iconName.setImageResource(this.manufacturersList.get(i).image);

return convertView;

public class ViewHolder
TextView name;
ImageView iconName;

private class POJOManufacturer
private String name;
private int image;
public void setName(String name)
{ = name;
public String getName()
return name;
public void setImage(int imageId)
this.image = imageId;
public int getImage()
return image;

I have updated and added: manufacturerList = new ArrayList<>. everything seem is better, and it happen some issues in getView() method,
I have try and it's only display with 7 empty items in gridview, and not display content and image

cause at line:

HashMap<String,String> map = manufacturersList.get(i);

So How fill data from Adapter into Gridview?

Answer Source

constructor ManufacturerFragment in class ManufacturerFragment cannot be applied to given types;

gridView.setAdapter() takes an adapter, not a Fragment

And new ManufacturerFragment() doesn't accept an Context.

I am not really sure why you think you need to create a new ManufacturerFragment within the Fragment class you already are in. Did you mean to do gridView.setAdapter(new MyAdapter(getActivity()))?

Also, your manufacturersList needs to be loaded into that adapter, so you'll need to figure that out.

And you need to use getActivity() instead of getActivity().getApplicationContext() in most places.

Then, you should only call new LoadAllManufacturers().execute(); in either onCreateView or onActivityCreated, not both. Otherwise, you're running two AsyncTasks.

Then, onPostExecute already runs on the UI thread, no need to use getActivity().runOnUiThread(new Runnable() {...

Once you do figure out how to put that ArrayList into the Adapter class, you'll want to call adapter.notifyDataSetChanged() within onPostExecute to tell the adapter to refresh the data, thereby updating the GridView to display the data.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download