java - 如何使用适配器填充ListView

标签 java android android-fragments android-listview android-asynctask

我知道这是一个非常简单的问题,但我是 Android 开发的新手,所以请放轻松。
我遇到的问题是在我的主要 Activity 中的 fragment 之一(特别是 AsyncTask)。 AsyncTask 将数据发送到 php 脚本,然后 PHP 脚本以 json 格式返回相应数据。然后对其进行处理并保存到 jsonlist 数组中。直到执行后一切正常,数据被下载、处理等。但是,当程序到达执行后时,问题开始出现。基本上我无法列出从 jsonlist 到 listview 的所有数据

    //setting up an array
    ArrayList<HashMap<String, String>> jsonlist = new ArrayList<HashMap<String, String>>();
    //creating list view variable
    ListView listview;
    //Define work in progress dialog
    private ProgressDialog mProgressDialog;  

private class ProgressTask extends AsyncTask<String, Void, Boolean> {
        @Override
        protected void onPreExecute() {
            super.onPreExecute();

            // Create a progressdialog
            mProgressDialog = new ProgressDialog(getActivity());

            // Set progressdialog title
            mProgressDialog.setTitle("Please wait");

            // Set progressdialog message
            mProgressDialog.setMessage("Fetching data...");
            mProgressDialog.setIndeterminate(false);

        }

        @Override
        protected Boolean doInBackground(String... params) {
            //To do in the background
            //Define variable of JSON parser type
            JSONParser jParser = new JSONParser();

            //Pass url to json parser class to fetch and save it into array variable
            JSONArray json = jParser.getJSONFromUrl(url);

            //loop from 0 to length of an array by increasing by 1
            for (int i = 0; i < json.length(); i++) {

                //Try and catch routine to prevent any crashes
                try {
                    //Get an object defined in { ... } in original json file
                    JSONObject c = json.getJSONObject(i);

                    //Separate object by obtaining values for each of the sections
                    String vtitle = c.getString(title);
                    String vcontent = c.getString(content);
                    String vuser = c.getString(user);

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

                    //Fill up an array with data extracted
                    map.put(title, vtitle);
                    map.put(content, vcontent);
                    map.put(user, vuser);

                    //Add values into jsonlist
                    jsonlist.add(map);

                } catch (JSONException e)
                {
                    //In case of any error Stack trace will be returned
                    e.printStackTrace();
                }
            }
            //Once everything has been done return null value
            return null;
        }
        @Override
        protected void onPostExecute(Boolean aBoolean) {
            //Insert all data downloaded through list adapter
            ListAdapter adapter = new SimpleAdapter(getActivity(), jsonlist, R.layout.list_activity, new String[] { title, content, user }, new int[] { R.id.title, R.id.content, R.id.user });

            // Locate the listview 
            //listview = (ListView) findViewById(R.id.list);

            // Set the adapter to the ListView
            //listview.setAdapter(adapter);

            //Get rid off dialog when operation of fetching data has been done
            if (mProgressDialog.isShowing()) {
                mProgressDialog.dismiss();
            }
        }
    }

如您所见,我已经尝试了注释代码,但 listview = (ListView) findViewById(R.id.list); 返回以下错误:

Cannot resolve method findViewById(int)

这阻止我执行程序。这是非常令人沮丧的,因为我确实在数组中拥有了我需要的所有数据,但只有一行代码阻止我显示它。

我也尝试过:

    ListAdapter adapter = new SimpleAdapter(context, jsonlist, R.layout.list_activity, new String[] { title, content, user }, new int[] { R.id.title, R.id.content, R.id.user });
    setListAdapter(adapter);
    lv = getListView();

但与前面的情况一样,返回未解析方法的错误。这是因为 fragment 是由 fragment 扩展的,向其中添加任何内容都会使其崩溃

public class Fragment2 extends Fragment, ListActivity {...}

最佳答案

将其添加到 Fragment2 类中的代码中。

private ListView listview;

@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
                         Bundle savedInstanceState) {
    View v = inflater.inflate(R.layout.YOUR_FRAGMENT_LAYOUT, container, false);

    listview = (ListView) v.findViewById(R.id.R.id.list);
    return v;
}

关于java - 如何使用适配器填充ListView,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31235087/

相关文章:

java - 找不到 Activity 异常

java - 全屏 DialogFragment 与 StatusBar 重叠

android - 如何将 fragment 添加到自定义抽屉导航模板?

java - Servlet getParameter() 返回 null 但值被传输

android - 从url下载APK并执行

android - 如何在捕获交易之前使用 Paypal 轻松更新订单?

android - 单击 View 寻呼机第二个 fragment 中的按钮时返回 View 寻呼机的第一个 fragment

java - 速度 : four ints or one int with many operations

java - JAVA 中的对象引用和类型转换

java - 如何从外部 APK 文件将签名读入 ByteArray