-2

I'm using NavigationDrawer in my project, I have MainNavigationFragmentActivity to manage 2 fragments : HomeFragment and SettingsFragment.

Now, I want to use HomeFragment to implement a activity (ManufacturerActivity)

my HomeFragment class:

public class HomeFragment extends Fragment {
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
                         Bundle savedInstanceState) {
    // Inflate the layout for this fragment
    View view = inflater.inflate(R.layout.test1, container, false);

    GridView gridView = (GridView) view.findViewById(R.id.gridview);
    gridView.setAdapter(new MyAdapter(getActivity()));

    return view;
    } 
}

my ManufacturerActivity class: (this class will get json from URL)

public class ManufacturerActivity extends ListActivity {

// Connection detector
ConnectionDetector cd;

// Alert dialog manager
AlertDialogManager alert = new AlertDialogManager();

// Progress Dialog
private ProgressDialog pDialog;

// Creating JSON Parser object
JSONParser jsonParser = new JSONParser();

ArrayList<HashMap<String, String>> albumsList;

// albums JSONArray
JSONArray albums = null;

// albums JSON url
private static final String URL_ALBUMS = "my URL";

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

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

    cd = new ConnectionDetector(getApplicationContext());

    // Check for internet connection
    if (!cd.isConnectingToInternet()) {
        // Internet Connection is not present
        alert.showAlertDialog(ManufacturerActivity.this, "Internet Connection Error",
                "Please connect to working Internet connection", false);
        // stop executing code by return
        return;
    }

    // Hashmap for ListView
    albumsList = new ArrayList<HashMap<String, String>>();

    // Loading Albums JSON in Background Thread
    new LoadCars().execute();

    // get listview
    ListView lv = getListView();

    /**
     * Listview item click listener
     * TrackListActivity will be lauched by passing album id
     * */
    lv.setOnItemClickListener(new android.widget.AdapterView.OnItemClickListener() {
        @Override
        public void onItemClick(AdapterView<?> arg0, View view, int arg2,
                                long arg3) {
            // on selecting a single album
            // TrackListActivity will be launched to show tracks inside the album
            Intent i = new Intent(getApplicationContext(), CategoryCarActivity.class);

            // send album id to tracklist activity to get list of songs under that album
            String album_id = ((TextView) view.findViewById(R.id.album_id)).getText().toString();
            i.putExtra("album_id", album_id);

            startActivity(i);
        }
    });
}

/**
 * Background Async Task to Load all Albums by making http request
 * */
class LoadCars extends AsyncTask<String, String, String> {

    /**
     * Before starting background thread Show Progress Dialog
     * */
    @Override
    protected void onPreExecute() {
        super.onPreExecute();
        pDialog = new ProgressDialog(ManufacturerActivity.this);
        pDialog.setMessage("Listing Albums ...");
        pDialog.setIndeterminate(false);
        pDialog.setCancelable(false);
        pDialog.show();
    }

    /**
     * getting Albums JSON
     * */
    protected String doInBackground(String... args) {
        // Building Parameters
        List<NameValuePair> params = new ArrayList<NameValuePair>();

        // getting JSON string from URL
        String json = jsonParser.makeHttpRequest(URL_ALBUMS, "GET",
                params);

        // Check your log cat for JSON reponse
        Log.d("Albums JSON: ", "> " + json);

        try {
            albums = new JSONArray(json);
            if (albums != null) {
                // looping through All albums
                for (int i = 0; i < albums.length(); i++) {
                    JSONObject c = albums.getJSONObject(i);

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

                    // 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_SONGS_COUNT, songs_count);

                    // adding HashList to ArrayList
                    albumsList.add(map);
                }
            }else{
                Log.d("Albums: ", "null");
            }

        } catch (JSONException e) {
            e.printStackTrace();
        }

        return null;
    }

    /**
     * After completing background task Dismiss the progress dialog
     * **/
    protected void onPostExecute(String file_url) {
        // dismiss the dialog after getting all albums
        pDialog.dismiss();
        // updating UI from Background Thread
        runOnUiThread(new Runnable() {
            public void run() {
                /**
                 * Updating parsed JSON data into ListView
                 * */
                ListAdapter adapter = new SimpleAdapter(
                        ManufacturerActivity.this, albumsList,
                        R.layout.list_item_manufacturers, new String[] { TAG_ID,
                        TAG_NAME }, new int[] {
                        R.id.album_id, R.id.album_name });

                // updating listview
                setListAdapter(adapter);
            }
        });

    }

}

}

How I can implement ManufacturerActivity in HomeFragment and get ListView data from JSON? Thank so much !!

luongkhanh
  • 1,753
  • 2
  • 16
  • 30
  • You should move `LoadAlbums` into it own Java file. Then, you can execute the AsyncTask from the Fragment. You can also follow this post, if you want. http://stackoverflow.com/questions/12575068/how-to-get-the-result-of-onpostexecute-to-main-activity-because-asynctask-is-a – OneCricketeer Oct 16 '16 at 03:43
  • Other option: Do some research on how to use Retrofit if you are going to be using HTTP + JSON – OneCricketeer Oct 16 '16 at 03:47

1 Answers1

0

You can't implement Activity in Fragment. You can do below steps to get data in fragment.

  1. Get the json data in Activity class by hitting URL.
  2. Save that json data using SharedPrefs or Database or any other method.
  3. Now, in Fragment get that saved json data and display in list.
Sanjeet
  • 2,385
  • 1
  • 13
  • 22
  • SharedPreferences probably is a poor choice. Why can't the AsyncTask be called from the Fragment and load the list from there? – OneCricketeer Oct 16 '16 at 03:41
  • It can be called, but if the data is needed in activity also then there is no need of making redundant calls. – Sanjeet Oct 16 '16 at 03:43
  • Hi Cricket_007, nice to meet you again. I think you are correct, I have read API android and see that I should be use AsyncTask for this case – luongkhanh Oct 16 '16 at 03:44
  • I suppose the question is unclear. The Fragment does not appear to be loaded in the Activity, even – OneCricketeer Oct 16 '16 at 03:45
  • I have get data json with activity and it's ok, now I want to get data activity via Fragment, that's my question – luongkhanh Oct 16 '16 at 03:46