Warning: file_get_contents(/data/phpspider/zhask/data//catemap/6/EmptyTag/127.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Android 带有Asynctask和自定义适配器的ListFragment_Android_Android Fragments_Android Asynctask_Android Listfragment - Fatal编程技术网

Android 带有Asynctask和自定义适配器的ListFragment

Android 带有Asynctask和自定义适配器的ListFragment,android,android-fragments,android-asynctask,android-listfragment,Android,Android Fragments,Android Asynctask,Android Listfragment,我的问题很基本,但我看不出解决办法。这是我在Android上的第三个项目。 到目前为止,我使用的片段中声明了一个ListView,onCreateView,其中我正在膨胀我的ListView和onActivityCreated来初始化布局。现在我想用ListFragment做同样的事情 我使用此exmaple作为参考: 下面是我用于带有ListView的片段的修改代码。我将此更改为使用ListFragment,但没有成功。有人能帮我吗?先谢谢你 public class PlayersL

我的问题很基本,但我看不出解决办法。这是我在Android上的第三个项目。 到目前为止,我使用的片段中声明了一个ListView,
onCreateView
,其中我正在膨胀我的ListView和
onActivityCreated
来初始化布局。现在我想用ListFragment做同样的事情

我使用此exmaple作为参考:

下面是我用于带有ListView的片段的修改代码。我将此更改为使用ListFragment,但没有成功。有人能帮我吗?先谢谢你

    public class PlayersListFragment extends ListFragment {
    OnPlayerSelectedListener mCallback;

    // URL to make request
    private static String URL = Utils.URL;
    private static int userID;
    ArrayList<HashMap<String, Object>> playersList;
    ListView playerView;
    private Dialog pDialog;

    // The container Activity must implement this interface so the frag can
    // deliver messages
    public interface OnPlayerSelectedListener {
        /** Called by HeadlinesFragment when a list item is selected */
        public void onPlayerSelected(int position);
    }

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

        // We need to use a different list item layout for devices older than
        // Honeycomb
        int layout = Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB ? android.R.layout.simple_list_item_activated_1
                : android.R.layout.simple_list_item_1;

        // Create an array adapter for the list view, using the Ipsum headlines
        // array
        setRetainInstance(true);
        new PlayersLoadTask().execute();
    }


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

    public boolean onOptionsItemSelected(MenuItem item) {
        return false;
    }


    private void initLayout() {         
        if(getActivity().getIntent()!=null) {
            userID = getActivity().getIntent().getIntExtra("id", 0);
        } else {
            return;
        }
        playerView = (ListView) getActivity().findViewById(R.id.list);
        playersList = new ArrayList<HashMap<String, Object>>();
        int[] colors = {0, 0xFFFF0000, 0}; // red for the example

    }
    @Override
    public void onStart() {
        super.onStart();

        // When in two-pane layout, set the listview to highlight the selected
        // list item
        // (We do this during onStart because at the point the listview is
        // available.)
        if (getFragmentManager().findFragmentById(R.id.playerDetailFragment) != null) {
            getListView().setChoiceMode(ListView.CHOICE_MODE_SINGLE);
        }
    }


    @Override
    public void onAttach(Activity activity) {
        super.onAttach(activity);

        // This makes sure that the container activity has implemented
        // the callback interface. If not, it throws an exception.
        try {
            mCallback = (OnPlayerSelectedListener) activity;
        } catch (ClassCastException e) {
            throw new ClassCastException(activity.toString()
                    + " must implement OnPlayerSelectedListener");
        }
    }

    @Override
    public void onListItemClick(ListView l, View v, int position, long id) {
        // Notify the parent activity of selected item
        mCallback.onPlayerSelected(position);

        // Set the item as checked to be highlighted when in two-pane layout
        getListView().setItemChecked(position, true);
    }

    class PlayersLoadTask extends AsyncTask<String, String, String> {

        @Override
        protected void onPreExecute() {
            pDialog = ProgressDialog.show(getActivity(), "",
                    "Loading. Please wait...", true);
        }

        @Override
        protected String doInBackground(String... params) {
            try {

                ArrayList<BasicNameValuePair> parameters = new ArrayList<BasicNameValuePair>();
                parameters.add(new BasicNameValuePair("request", "getPlayers"));
                parameters.add(new BasicNameValuePair("clubid", Integer
                        .toString(userID)));

                DefaultHttpClient httpClient = new DefaultHttpClient();
                HttpPost httpPost = new HttpPost(URL);
                httpPost.setEntity(new UrlEncodedFormEntity(parameters,
                        ("ISO-8859-1")));
                HttpResponse httpResponse = httpClient.execute(httpPost);
                HttpEntity httpEntity = httpResponse.getEntity();

                // if this is null the web service returned an empty page
                if (httpEntity == null) // response is empty so exit out
                    return null;

                String jsonString = EntityUtils.toString(httpEntity);

                if (jsonString != null && jsonString.length() != 0) 
                {
                    JSONArray jsonArray = new JSONArray(jsonString);
                    for (int i = 0; i < jsonArray.length(); i++) {
                        HashMap<String, Object> map = new HashMap<String, Object>();
                        JSONObject jsonObject = (JSONObject) jsonArray.get(i);
                        int id = jsonObject.getInt("id");
                        String name = jsonObject.getString("name");

                        map.put("id", id);
                        map.put("name", name);
                        playersList.add(map);

                    }
                }
            } catch (UnsupportedEncodingException e) {
                e.printStackTrace();
            } catch (ClientProtocolException e) {
                e.printStackTrace();
            } catch (IOException e) {
                e.printStackTrace();
            } catch (JSONException e) {
                e.printStackTrace();
            } catch (Exception e) {
                Log.e("ERROR SOMEWHERE!!!! ", e.toString());
            }
            return null;

        }

        @Override
        protected void onPostExecute(String file_url) {
            if (pDialog.isShowing())
                pDialog.dismiss();
            if (playersList.size() == 0) {
                Toast.makeText(getActivity(), "No players in a list",
                        Toast.LENGTH_SHORT).show();
            } else {
                playerView.setAdapter(new PlayerListAdapter( // <<== EXCEPTION HERE
                        getActivity(), R.id.player_list_id,
                        playersList));
            }

        }
    }
}

onactivitycreated
中调用
initLayout()
,其中包含以下内容

playerView = (ListView) getActivity().findViewById(R.id.list);
以上是导致
NullPointerException

所以换成

 playerView = getListView();   // since you extend ListFragment

这就是我解决问题的方法。似乎您必须在onCreate()或onActivityCreated()中包含setListAdapter()。供日后参考的代码:

public class PlayersListFragment extends ListFragment {
OnPlayerSelectedListener mCallback;

// URL to make request
private static String URL = Utils.URL;
private static int userID;
ArrayList<HashMap<String, Object>> playersList;
ListView playerView;
private ProgressDialog pDialog;

// The container Activity must implement this interface so the frag can
// deliver messages
public interface OnPlayerSelectedListener {
    /** Called by HeadlinesFragment when a list item is selected */
    public void onPlayerSelected(int position);
}




@Override
public void onActivityCreated(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState); 
    setRetainInstance(true);
    initLayout();

    new PlayersLoadTask().execute();
    int layout = Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB ?
            android.R.layout.simple_list_item_activated_1 : android.R.layout.simple_list_item_1;
    setListAdapter(new PlayerListAdapter(getActivity(), layout, playersList));

}

public boolean onOptionsItemSelected(MenuItem item) {
    return false;
}


private void initLayout() {         
    if(getActivity().getIntent()!=null) {
        userID = getActivity().getIntent().getIntExtra("id", 0);
    } else {
        return;
    }
    playerView = getListView();
    playersList = new ArrayList<HashMap<String, Object>>();

}
@Override
public void onStart() {
    super.onStart();

    // When in two-pane layout, set the listview to highlight the selected
    // list item
    // (We do this during onStart because at the point the listview is
    // available.)
    if (getFragmentManager().findFragmentById(R.id.playerDetailFragment) != null) {
        playerView.setChoiceMode(ListView.CHOICE_MODE_SINGLE);
    }
}


@Override
public void onAttach(Activity activity) {
    super.onAttach(activity);

    // This makes sure that the container activity has implemented
    // the callback interface. If not, it throws an exception.
    try {
        mCallback = (OnPlayerSelectedListener) activity;
    } catch (ClassCastException e) {
        throw new ClassCastException(activity.toString()
                + " must implement OnPlayerSelectedListener");
    }
}

@Override
public void onListItemClick(ListView l, View v, int position, long id) {
    // Notify the parent activity of selected item
    mCallback.onPlayerSelected(position);

    // Set the item as checked to be highlighted when in two-pane layout
    playerView.setItemChecked(position, true);
}

class PlayersLoadTask extends AsyncTask<String, String, String> {

    @Override
    protected void onPreExecute() {
        pDialog = ProgressDialog.show(getActivity(), "",
                "Loading. Please wait...", true);
    }

    @Override
    protected String doInBackground(String... params) {
        try {

            ArrayList<BasicNameValuePair> parameters = new ArrayList<BasicNameValuePair>();
            parameters.add(new BasicNameValuePair("request", "getPlayers"));
            parameters.add(new BasicNameValuePair("clubid", Integer
                    .toString(userID)));

            DefaultHttpClient httpClient = new DefaultHttpClient();
            HttpPost httpPost = new HttpPost(URL);
            httpPost.setEntity(new UrlEncodedFormEntity(parameters,
                    ("ISO-8859-1")));
            HttpResponse httpResponse = httpClient.execute(httpPost);
            HttpEntity httpEntity = httpResponse.getEntity();

            // if this is null the web service returned an empty page
            if (httpEntity == null) // response is empty so exit out
                return null;

            String jsonString = EntityUtils.toString(httpEntity);

            if (jsonString != null && jsonString.length() != 0) 
            {
                JSONArray jsonArray = new JSONArray(jsonString);
                for (int i = 0; i < jsonArray.length(); i++) {
                    HashMap<String, Object> map = new HashMap<String, Object>();
                    JSONObject jsonObject = (JSONObject) jsonArray.get(i);
                    int id = jsonObject.getInt("id");
                    String name = jsonObject.getString("name");

                    map.put("id", id);
                    map.put("name", name);
                    playersList.add(map);

                }
            }
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        } catch (ClientProtocolException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        } catch (JSONException e) {
            e.printStackTrace();
        } catch (Exception e) {
            Log.e("ERROR SOMEWHERE!!!! ", e.toString());
        }
        return null;

    }

    @Override
    protected void onPostExecute(String file_url) {
        if (pDialog.isShowing())
            pDialog.dismiss();
        if (playersList.size() == 0) {
            Toast.makeText(getActivity(), "No players in a list",
                    Toast.LENGTH_SHORT).show();

        } else if(playerView != null) {
            setListAdapter(new PlayerListAdapter(getActivity(),  R.id.player_list_id, playersList));
            /*playerView.setAdapter(new PlayerListAdapter(
                    getActivity(), R.id.player_list_id,
                    playersList));*/
        }
    }
}
公共类PlayersListFragment扩展ListFragment{
OnPlayerSelectedListener McCallback;
//发出请求的URL
私有静态字符串URL=Utils.URL;
私有静态int用户id;
ArrayList玩家列表;
ListView播放视图;
私人对话;
//容器活动必须实现此接口,以便frag能够
//传递信息
PlayerSelectedListener上的公共接口{
/**选择列表项时由HeadlinesFragment调用*/
公共球员当选(国际位置);
}
@凌驾
已创建ActivityState上的公共无效(Bundle savedInstanceState){
super.onCreate(savedInstanceState);
setRetainInstance(真);
initLayout();
新建PlayerLoadTask().execute();
int layout=Build.VERSION.SDK\u int>=Build.VERSION\u code.h?
android.R.layout.simple_list_item_activated_1:android.R.layout.simple_list_item_1;
setListAdapter(新的PlayerListAdapter(getActivity(),布局,playerList));
}
公共布尔值onOptionsItemSelected(菜单项项){
返回false;
}
私有void initLayout(){
if(getActivity().getIntent()!=null){
userID=getActivity().getIntent().getIntExtra(“id”,0);
}否则{
返回;
}
playerView=getListView();
PlayerList=新的ArrayList();
}
@凌驾
public void onStart(){
super.onStart();
//在双窗格布局中,将listview设置为高亮显示选定的
//列表项
//(我们在onStart期间执行此操作,因为此时listview
//可用。)
if(getFragmentManager().findFragmentById(R.id.playerDetailFragment)!=null){
playerView.setChoiceMode(ListView.CHOICE\u MODE\u SINGLE);
}
}
@凌驾
公共事务主任(活动){
超级转速计(活动);
//这确保容器活动已实现
//回调接口。如果不是,则抛出异常。
试一试{
mCallback=(OnPlayerSelectedListener)活动;
}catch(ClassCastException e){
抛出新的ClassCastException(activity.toString()
+“必须实现OnPlayerSelectedListener”);
}
}
@凌驾
public void onListItemClick(列表视图l、视图v、整数位置、长id){
//通知所选项目的父活动
mCallback.onPlayerSelected(位置);
//将项目设置为选中状态,以便在双窗格布局中高亮显示
playerView.setItemChecked(位置,真);
}
类PlayerLoadTask扩展了AsyncTask{
@凌驾
受保护的void onPreExecute(){
pDialog=ProgressDialog.show(getActivity(),“”,
“正在加载。请稍候…”,正确);
}
@凌驾
受保护的字符串doInBackground(字符串…参数){
试一试{
ArrayList参数=新的ArrayList();
添加(新的BasicNameValuePair(“请求”、“获取玩家”);
添加(新的BasicNameValuePair(“clubid”),整数
.toString(userID));
DefaultHttpClient httpClient=新的DefaultHttpClient();
HttpPost HttpPost=新的HttpPost(URL);
httpPost.setEntity(新的UrlEncodedFormEntity)(参数,
(“ISO-8859-1”);
HttpResponse HttpResponse=httpClient.execute(httpPost);
HttpEntity HttpEntity=httpResponse.getEntity();
//如果为null,则web服务返回一个空页面
如果(httpEntity==null)//响应为空,则退出
返回null;
字符串jsonString=EntityUtils.toString(httpEntity);
if(jsonString!=null&&jsonString.length()!=0)
{
JSONArray JSONArray=新的JSONArray(jsonString);
for(int i=0;ipublic class PlayersListFragment extends ListFragment {
OnPlayerSelectedListener mCallback;

// URL to make request
private static String URL = Utils.URL;
private static int userID;
ArrayList<HashMap<String, Object>> playersList;
ListView playerView;
private ProgressDialog pDialog;

// The container Activity must implement this interface so the frag can
// deliver messages
public interface OnPlayerSelectedListener {
    /** Called by HeadlinesFragment when a list item is selected */
    public void onPlayerSelected(int position);
}




@Override
public void onActivityCreated(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState); 
    setRetainInstance(true);
    initLayout();

    new PlayersLoadTask().execute();
    int layout = Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB ?
            android.R.layout.simple_list_item_activated_1 : android.R.layout.simple_list_item_1;
    setListAdapter(new PlayerListAdapter(getActivity(), layout, playersList));

}

public boolean onOptionsItemSelected(MenuItem item) {
    return false;
}


private void initLayout() {         
    if(getActivity().getIntent()!=null) {
        userID = getActivity().getIntent().getIntExtra("id", 0);
    } else {
        return;
    }
    playerView = getListView();
    playersList = new ArrayList<HashMap<String, Object>>();

}
@Override
public void onStart() {
    super.onStart();

    // When in two-pane layout, set the listview to highlight the selected
    // list item
    // (We do this during onStart because at the point the listview is
    // available.)
    if (getFragmentManager().findFragmentById(R.id.playerDetailFragment) != null) {
        playerView.setChoiceMode(ListView.CHOICE_MODE_SINGLE);
    }
}


@Override
public void onAttach(Activity activity) {
    super.onAttach(activity);

    // This makes sure that the container activity has implemented
    // the callback interface. If not, it throws an exception.
    try {
        mCallback = (OnPlayerSelectedListener) activity;
    } catch (ClassCastException e) {
        throw new ClassCastException(activity.toString()
                + " must implement OnPlayerSelectedListener");
    }
}

@Override
public void onListItemClick(ListView l, View v, int position, long id) {
    // Notify the parent activity of selected item
    mCallback.onPlayerSelected(position);

    // Set the item as checked to be highlighted when in two-pane layout
    playerView.setItemChecked(position, true);
}

class PlayersLoadTask extends AsyncTask<String, String, String> {

    @Override
    protected void onPreExecute() {
        pDialog = ProgressDialog.show(getActivity(), "",
                "Loading. Please wait...", true);
    }

    @Override
    protected String doInBackground(String... params) {
        try {

            ArrayList<BasicNameValuePair> parameters = new ArrayList<BasicNameValuePair>();
            parameters.add(new BasicNameValuePair("request", "getPlayers"));
            parameters.add(new BasicNameValuePair("clubid", Integer
                    .toString(userID)));

            DefaultHttpClient httpClient = new DefaultHttpClient();
            HttpPost httpPost = new HttpPost(URL);
            httpPost.setEntity(new UrlEncodedFormEntity(parameters,
                    ("ISO-8859-1")));
            HttpResponse httpResponse = httpClient.execute(httpPost);
            HttpEntity httpEntity = httpResponse.getEntity();

            // if this is null the web service returned an empty page
            if (httpEntity == null) // response is empty so exit out
                return null;

            String jsonString = EntityUtils.toString(httpEntity);

            if (jsonString != null && jsonString.length() != 0) 
            {
                JSONArray jsonArray = new JSONArray(jsonString);
                for (int i = 0; i < jsonArray.length(); i++) {
                    HashMap<String, Object> map = new HashMap<String, Object>();
                    JSONObject jsonObject = (JSONObject) jsonArray.get(i);
                    int id = jsonObject.getInt("id");
                    String name = jsonObject.getString("name");

                    map.put("id", id);
                    map.put("name", name);
                    playersList.add(map);

                }
            }
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        } catch (ClientProtocolException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        } catch (JSONException e) {
            e.printStackTrace();
        } catch (Exception e) {
            Log.e("ERROR SOMEWHERE!!!! ", e.toString());
        }
        return null;

    }

    @Override
    protected void onPostExecute(String file_url) {
        if (pDialog.isShowing())
            pDialog.dismiss();
        if (playersList.size() == 0) {
            Toast.makeText(getActivity(), "No players in a list",
                    Toast.LENGTH_SHORT).show();

        } else if(playerView != null) {
            setListAdapter(new PlayerListAdapter(getActivity(),  R.id.player_list_id, playersList));
            /*playerView.setAdapter(new PlayerListAdapter(
                    getActivity(), R.id.player_list_id,
                    playersList));*/
        }
    }
}