Android片段静态方法不显示listview项

时间:2016-06-01 07:15:36

标签: android listview android-fragments

我之前已经发布了这个问题..但是没有得到任何建议那就是为什么我再次发布它..我有片段在listview中显示它..所以,我有(我的部分代码):

public class TwoFragment extends Fragment  {

    Button btn1;
    static ListView listview;
    ProgressDialog mProgressDialog;
    static Activity activity;

    public TwoFragment() {

    }

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {

        View view = inflater.inflate(R.layout.fragment_two2, container, false);
         activity = getActivity();
        listview = (ListView) view.findViewById(R.id.listview);
        return view;
    }

    public static void display(final String serverResponse) {

        @SuppressWarnings("unused")
        final class DownloadJSON extends AsyncTask<String, String, Void> {
            private  JSONObject jsonobject;
            private  JSONArray jsonarray;
                private  ListViewAdapter adapter;
            private  ArrayList<HashMap<String, String>> arraylist;
            @Override
            protected Void doInBackground(String... params) {
                try {

                    jsonarray = new JSONArray(serverResponse);
                    Gson gson = new Gson();

                    User[] user = gson.fromJson(jsonarray.toString(), User[].class);
                    for (int i = 0; i < user.length; i++) {
                        HashMap<String, String> map = new HashMap<String, String>();
                        map.put("name", user[i].getFullname());
                        arraylist.add(map);

                    }

                } catch (JSONException e) {
                    Log.e("Error", e.getMessage());
                    e.printStackTrace();
                } catch (Exception e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                }
                return null;
            }

            @Override
            protected void onPostExecute(Void args) {

                adapter = new ListViewAdapter(activity, arraylist);
                listview.setAdapter(adapter);
                adapter.notifyDataSetChanged();
            }
        }
    }
}

在这段代码中,我没有在listview中显示任何内容..

1 个答案:

答案 0 :(得分:1)

你持有对Activity和ListView的静态引用?这是an memory leak的主要例子。

从display方法中删除static关键字,也从activity和listview变量中删除。实际上你不需要对Activity的引用,因为你可以在'onPostExecute'中获得带有'getActivity'的实例。但只有当片段仍然附加到活动时。

你也在定义AsyncTask,但没有用[instance] .execute();

来调用它。

现在我看一下代码,它甚至可以编译吗?据我所知,不允许在方法中定义类。