试图在扩展片段的活动中添加元素的问题

时间:2014-01-29 14:59:12

标签: android listview fragment android-listfragment

我正在构建一个基本应用程序,它在列表视图中显示数据库中的数据。哪个工作正常,我决定使用导航抽屉添加一个滑动菜单哪个使用扩展到片段的活动所以我一直在改变我的所有类扩展片段所以他们可以添加到新的导航菜单。 我的问题是:在我的一个班级 AllBarsActivity 中我添加了一个显示数据库数据的列表,为此, AllBarsActivity 扩展 ListActivity 。 我的导航系统使用扩展到片段的类,我这样做,所以现在我收到错误。我的问题是如何在片段中添加列表视图。 在尝试添加幻灯片菜单导航抽屉之前,这是我之前的内容:

    public class AllBarsActivity extends ListActivity {



        // Progress Dialog
        private ProgressDialog pDialog;
     // might have to change json import///////////
        // Creating JSON Parser object
        JSONParser jParser = new JSONParser();

        ArrayList<HashMap<String, String>> barsList;


    // url to get all products list
    private static String url_all_bars = "http://www.milamboltd.freeserver.me/android_login_api/get_all_bars.php";

    // JSON Node names
    private static final String TAG_SUCCESS = "success";
    private static final String TAG_BARS = "bars";
    private static final String TAG_PID = "pid";
    private static final String TAG_ARTIST = "artist";
    private static final String TAG_TITLE = "title";
    private static final String TAG_DESCRIPTION = "description";
    private static final String TAG_CREATED_AT= "created_at";
    private static final String TAG_UPLOADEDBY = "uploadedBy";


    String userLoggedIn;
    private static String KEY_EMAIL = "email";






    // bars JSONArray
    JSONArray bars = null;

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

     // getting bar details from intent
        Intent i = getIntent();

        // getting bar id (pid) from intent
        userLoggedIn = i.getStringExtra(KEY_EMAIL);

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

        // Loading bars in Background Thread
        new LoadAllBars().execute();

        // Get listview
        ListView lv = getListView();

        // on seleting single bar
        // launching Edit bar Screen
        lv.setOnItemClickListener(new OnItemClickListener() {



               @Override
                public void onItemClick(AdapterView<?> parent, View view,
                        int position, long id) {
                    // getting values from selected ListItem
                    String pid = ((TextView) view.findViewById(R.id.pid)).getText()
                            .toString();

    //                // Starting new intent
    //                Intent in = new Intent(getApplicationContext(),
    //                        EditBarActivity.class);
    //                // sending pid to next activity
    //                in.putExtra(TAG_PID, pid);
    // 
                    // starting new activity and expecting some response back
                  //  startActivityForResult(in, 100);
                }
            });

        }


    // Response from Edit Bar Activity
    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        // if result code 100
        if (resultCode == 100) {
            // if result code 100 is received
            // means user edited/deleted bar
            // reload this screen again
            Intent intent = getIntent();
            finish();
            startActivity(intent);
        }

    }

    /**
     * Background Async Task to Load all bar by making HTTP Request
     * */
    class LoadAllBars extends AsyncTask<String, String, String> {

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

        /**
         * getting All bars from url
         * */
        protected String doInBackground(String... args) {
            // Building Parameters
            List<NameValuePair> params = new ArrayList<NameValuePair>();
            // getting JSON string from URL
            JSONObject json = jParser.makeHttpRequest(url_all_bars, "GET", params);

            // Check your log cat for JSON reponse
           Log.d("All Bars: ", json.toString());

            try {
                // Checking for SUCCESS TAG
                int success = json.getInt(TAG_SUCCESS);

                if (success == 1) {
                    // bars found
                    // Getting Array of bars
                    bars = json.getJSONArray(TAG_BARS);

                    // looping through All bars
                    for (int i = 0; i < bars.length(); i++) {
                        JSONObject c = bars.getJSONObject(i);

                        // Storing each json item in variable
                        String id = c.getString(TAG_PID);
                        String artist = c.getString(TAG_ARTIST);
                        String title = c.getString(TAG_TITLE);
                        String uploadedBy = c.getString(TAG_UPLOADEDBY);
                        String description = c.getString(TAG_DESCRIPTION);
                        String created_at = c.getString(TAG_CREATED_AT);

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

                        // adding each child node to HashMap key => value
                        map.put(TAG_PID, id);
                        map.put(TAG_ARTIST, artist);
                        map.put(TAG_TITLE, title);
                        map.put(TAG_UPLOADEDBY, uploadedBy);
                        map.put(TAG_DESCRIPTION, description);
                        map.put(TAG_CREATED_AT, created_at);





                        // adding HashList to ArrayList
                        barsList.add(map);
                    }
                } else {
                    // no bars found
                    // Launch Add New bar Activity
                    Intent i = new Intent(getApplicationContext(),
                            NewBarActivity.class);
                    // Closing all previous activities
                    i.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
                    startActivity(i);
                }
            } 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 bars
            pDialog.dismiss();
            // updating UI from Background Thread
            runOnUiThread(new Runnable() {
                public void run() {
                    /**
                     * Updating parsed JSON data into ListView
                     * */
                      ListAdapter adapter = new SimpleAdapter(
                              AllBarsActivity.this, barsList,
                              R.layout.list_item, new String[] { TAG_PID,
                                      TAG_TITLE,TAG_ARTIST,TAG_DESCRIPTION,TAG_UPLOADEDBY},


>                     new int[] { R.id.pid, R.id.title,R.id.artist, R.id.description,R.id.created_at });
>                       // updating listview
>                       setListAdapter(adapter);
>                   }
>               });
>    
>           }
>    
>       }   }

,这是我尝试将其转换为的片段类:

public class WhatsHotFragment extends Fragment {


     // Progress Dialog
    private ProgressDialog pDialog;
 // might have to change json import///////////
    // Creating JSON Parser object
    JSONParser jParser = new JSONParser();

    ArrayList<HashMap<String, String>> barsList;
// url to get all products list
private static String url_all_bars = "http://www.milamboltd.freeserver.me/android_login_api/get_all_bars.php";

// JSON Node names
private static final String TAG_SUCCESS = "success";
private static final String TAG_BARS = "bars";
private static final String TAG_PID = "pid";
private static final String TAG_ARTIST = "artist";
private static final String TAG_TITLE = "title";
private static final String TAG_DESCRIPTION = "description";
private static final String TAG_CREATED_AT= "created_at";
private static final String TAG_UPLOADEDBY = "uploadedBy";

String userLoggedIn;
private static String KEY_EMAIL = "email";

// bars JSONArray
JSONArray bars = null;

public WhatsHotFragment(){}


@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,


           Bundle savedInstanceState) {

        View rootView = inflater.inflate(R.layout.fragment_whats_hot, container, false);

        // getting bar details from intent
        Intent i = getActivity().getIntent();

        // getting bar id (pid) from intent
        userLoggedIn = i.getStringExtra(KEY_EMAIL);

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

        // Loading bars in Background Thread
        new LoadAllBars().execute();

        // Get listview
        ListView lv = getListView();

        // on seleting single bar
        // launching Edit bar Screen
        lv.setOnItemClickListener(new OnItemClickListener() {

            @Override
            public void onItemClick(AdapterView<?> parent, View view,
                    int position, long id) {
                // getting values from selected ListItem
                String pid = ((TextView) view.findViewById(R.id.pid)).getText()
                        .toString();

//                // Starting new intent
//                Intent in = new Intent(getApplicationContext(),
//                        EditBarActivity.class);
//                // sending pid to next activity
//                in.putExtra(TAG_PID, pid);
// 
                // starting new activity and expecting some response back
              //  startActivityForResult(in, 100);
            }
        });


        return rootView;
    }

    /**
     * Background Async Task to Load all bar by making HTTP Request
     * */
    class LoadAllBars extends AsyncTask<String, String, String> {

        /**
         * Before starting background thread Show Progress Dialog
         * */
        @Override
        protected void onPreExecute() {
            super.onPreExecute();
            pDialog = new ProgressDialog(getActivity());
            pDialog.setMessage("Loading bars. Please wait...");
            pDialog.setIndeterminate(false);
            pDialog.setCancelable(false);
            pDialog.show();
        }

        /**
         * getting All bars from url
         * */
        protected String doInBackground(String... args) {
            // Building Parameters
            List<NameValuePair> params = new ArrayList<NameValuePair>();
            // getting JSON string from URL
            JSONObject json = jParser.makeHttpRequest(url_all_bars, "GET", params);

            // Check your log cat for JSON reponse
           Log.d("All Bars: ", json.toString());

            try {
                // Checking for SUCCESS TAG
                int success = json.getInt(TAG_SUCCESS);

                if (success == 1) {
                    // bars found
                    // Getting Array of bars
                    bars = json.getJSONArray(TAG_BARS);



// looping through All bars
                for (int i = 0; i < bars.length(); i++) {
                    JSONObject c = bars.getJSONObject(i);

                    // Storing each json item in variable
                    String id = c.getString(TAG_PID);
                    String artist = c.getString(TAG_ARTIST);
                    String title = c.getString(TAG_TITLE);
                    String uploadedBy = c.getString(TAG_UPLOADEDBY);
                    String description = c.getString(TAG_DESCRIPTION);
                    String created_at = c.getString(TAG_CREATED_AT);

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

                    // adding each child node to HashMap key => value
                    map.put(TAG_PID, id);
                    map.put(TAG_ARTIST, artist);
                    map.put(TAG_TITLE, title);
                    map.put(TAG_UPLOADEDBY, uploadedBy);
                    map.put(TAG_DESCRIPTION, description);
                    map.put(TAG_CREATED_AT, created_at);





                    // adding HashList to ArrayList
                    barsList.add(map);
                }
            } else {
                // no bars found
                // Launch Add New bar Activity
                Intent i = new Intent(getActivity(),
                        NewBarFragment.class);
                // Closing all previous activities
                i.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
                startActivity(i);
            }
        } 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 bars
        pDialog.dismiss();
        // updating UI from Background Thread
        runOnUiThread(new Runnable() {
            public void run() {
                /**
                 * Updating parsed JSON data into ListView
                 * */
                  ListAdapter adapter = new SimpleAdapter(
                          AllBarsActivity.this, barsList,
                          R.layout.list_item, new String[] { TAG_PID,
                                  TAG_TITLE,TAG_ARTIST,TAG_DESCRIPTION,TAG_UPLOADEDBY},
                          new int[] { R.id.pid, R.id.title,R.id.artist, R.id.description,R.id.created_at });
                  // updating listview
                  setListAdapter(adapter);
              }
          });

      }

  }
}

我在这些代码行上出错: 1.它说方法getListView()未定义类型  WhatsHotFragment

 // Get listview
    ListView lv = getListView();
  1. 它表示方法 runOnUiThread(new Runnable(){})未定义  输入WhatsHotFragment.LoadAllBars。
  2. - 并且在范围

    中无法访问AllBarsActivity类型的封闭实例
    protected void onPostExecute(String file_url) {
                // dismiss the dialog after getting all bars
                pDialog.dismiss();
                // updating UI from Background Thread
                runOnUiThread(new Runnable() {
                    public void run() {
                        /**
                         * Updating parsed JSON data into ListView
                         * */                   
                          ListAdapter adapter = new SimpleAdapter(
                                  AllBarsActivity.this, barsList,
                                  R.layout.list_item, new String[] { TAG_PID,
                                          TAG_TITLE,TAG_ARTIST,TAG_DESCRIPTION,TAG_UPLOADEDBY},
                                  new int[] { R.id.pid, R.id.title,R.id.artist, R.id.description,R.id.created_at });
                          // updating listview
                          setListAdapter(adapter);
                      }
                  });
    
       edit:
    

    我添加了一个公共void void oncreated来添加listview但是它的内容视图尚未创建。

    'public void onActivityCreated (Bundle savedInstanceState){
    
    
        ListView lv = getListView();
    
    }
    '
    

1 个答案:

答案 0 :(得分:0)

您可以扩展ListFragment而不是Fragment,您可以使用ListActivity中的列表功能。

http://developer.android.com/reference/android/app/ListFragment.html

如果您在片段内使用runOnUiThread,请先调用getActivity()。

getActivity().runOnUiThread(new Runnable())