【问题标题】:Implement activity in fragment android在片段android中实现活动
【发布时间】:2016-10-16 03:26:43
【问题描述】:

我在我的项目中使用 NavigationDrawer,我有 MainNavigationFragmentActivity 来管理 2 个片段:HomeFragment 和 SettingsFragment。

现在,我想用 HomeFragment 来实现一个活动(ManufacturerActivity)

我的 HomeFragment 类:

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

我的 ManufacturerActivity 类:(该类将从 URL 获取 json)

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

    }

}

}

如何在 HomeFragment 中实现 ManufacturerActivity 并从 JSON 获取 ListView 数据? 非常感谢!!

【问题讨论】:

  • 您应该将LoadAlbums 移动到它自己的Java 文件中。然后,您可以从 Fragment 执行 AsyncTask。如果你愿意,你也可以关注这个帖子。 stackoverflow.com/questions/12575068/…
  • 其他选项:如果您打算使用 HTTP + JSON,请研究如何使用 Retrofit

标签: android listview fragment


【解决方案1】:

您不能在 Fragment 中实现 Activity。您可以执行以下步骤以获取片段中的数据。

  1. 点击URL获取Activity类中的json数据。
  2. 使用 SharedPrefs 或 Database 或任何其他方法保存该 json 数据。
  3. 现在,在 Fragment 中获取保存的 json 数据并显示在列表中。

【讨论】:

  • SharedPreferences 可能是一个糟糕的选择。为什么不能从 Fragment 调用 AsyncTask 并从那里加载列表?
  • 可以调用,但是如果activity中也需要数据,那么就不需要进行冗余调用了。
  • 嗨 Cricket_007,很高兴再次见到你。我认为你是对的,我已经阅读了 API android 并看到我应该在这种情况下使用 AsyncTask
  • 我想这个问题还不清楚。 Fragment 似乎没有加载到 Activity 中,甚至
  • 我已经获得了带有活动的数据 json,没关系,现在我想通过 Fragment 获取数据活动,这是我的问题
猜你喜欢
  • 1970-01-01
  • 2014-03-05
  • 1970-01-01
  • 2013-11-12
  • 2018-08-26
  • 2012-10-28
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多