具有获取 json 值的片段中的自定义适配器

Posted

技术标签:

【中文标题】具有获取 json 值的片段中的自定义适配器【英文标题】:Custom Adapter in fragment with get json value 【发布时间】:2017-08-04 10:48:49 【问题描述】:

当在活动中显示片段时,我正在尝试从片段中的 JSON 获取列表。 当我展示适配器时我遇到了问题。

SiswaFragment

public class SiswaFragment extends Fragment 
    // TODO: Rename parameter arguments, choose names that match
    // the fragment initialization parameters, e.g. ARG_ITEM_NUMBER
    private static final String ARG_PARAM1 = "param1";
    private static final String ARG_PARAM2 = "param2";
    private List<MenuItem> menuItem;
    private ListView listView;
    private MenuListAdapter listAdapter;
    private String URL_FEED = AppConfig.URL;


    // TODO: Rename and change types of parameters
    private String mParam1;
    private String mParam2;

    private OnFragmentInteractionListener mListener;

    public SiswaFragment() 
        // Required empty public constructor
    

    // TODO: Rename and change types and number of parameters
    public static SiswaFragment newInstance(String param1, String param2) 
        SiswaFragment fragment = new SiswaFragment();
        Bundle args = new Bundle();
        args.putString(ARG_PARAM1, param1);
        args.putString(ARG_PARAM2, param2);
        fragment.setArguments(args);
        return fragment;
    

    @Override
    public void onCreate(Bundle savedInstanceState) 
        super.onCreate(savedInstanceState);
        if (getArguments() != null) 
            mParam1 = getArguments().getString(ARG_PARAM1);
            mParam2 = getArguments().getString(ARG_PARAM2);
        
    

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

        View view = inflater.inflate(R.layout.fragment_siswa, container, false);
        //session = new SessionManager(getActivity().getApplicationContext());

        listView = (ListView) view.findViewById(R.id.listSiswa);
        menuItem = new ArrayList<MenuItem>();

        RequestQueue rq = Volley.newRequestQueue(getActivity().getApplicationContext());

        String no_hp = "085733777717";
        String URL = URL_FEED + "/?nomor_hp=" + no_hp;

        StringRequest stringRequest = new StringRequest(Request.Method.GET, URL,
                new Response.Listener<String>() 
                    @Override
                    public void onResponse(String response) 
                        // Do something with the response

                        try

                            JSONObject o = new JSONObject(response);
                            JSONArray feedArray = o.getJSONArray("data");

                            for (int i = 0; i < feedArray.length(); i++) 
                                JSONObject feedObj = (JSONObject) feedArray.get(i);

                                //Toast.makeText(getApplicationContext(), feedObj.toString(), Toast.LENGTH_LONG).show();
                                MenuItem item = new MenuItem();
                                item.setId(feedObj.getString("kode"));
                                item.setImage(AppConfig.URL_ASSETS + "user.png");
                                item.setName(feedObj.getString("nama"));
                                item.setDescription(feedObj.getString("kelas"));
                                item.setRemarks(feedObj.getString("sekolah"));

                                menuItem.add(item);
                            

                            //txt.setText(sb.toString());


                          catch (JSONException ex)

                    
                ,
                new Response.ErrorListener() 
                    @Override
                    public void onErrorResponse(VolleyError error) 
                        // Handle error
                    
                );

        listAdapter = new MenuListAdapter(getActivity(), menuItem);
        listView.setAdapter(listAdapter);
        // Inflate the layout for this fragment
        rq.add(stringRequest );
        return view;
    

    // TODO: Rename method, update argument and hook method into UI event
    public void onButtonPressed(Uri uri) 
        if (mListener != null) 
            mListener.onFragmentInteraction(uri);
        
    

    @Override
    public void onAttach(Context context) 
        super.onAttach(context);
    

    @Override
    public void onDetach() 
        super.onDetach();
        mListener = null;
    

    public interface OnFragmentInteractionListener 
        // TODO: Update argument type and name
        void onFragmentInteraction(Uri uri);
    


MenuListAdapter

public class MenuListAdapter extends BaseAdapter 
    private Activity activity;
    private LayoutInflater inflater;
    private List<MenuItem> menuItem;
    private SessionManager session;
    private Database db;
    private Context context;
    ImageLoader imageLoader = AppController.getInstance().getImageLoader();

    public MenuListAdapter(Activity activity, List<MenuItem> menuItem) 
        this.activity = activity;
        this.menuItem = menuItem;
        this.context = activity.getApplicationContext();
    

    @Override
    public int getCount() 
        return menuItem.size();
    

    @Override
    public Object getItem(int location) 
        return menuItem.get(location);
    

    @Override
    public long getItemId(int position) 
        return position;
    

    @Override
    public View getView(final int position, View convertView, ViewGroup parent) 

        db = new Database(activity.getApplicationContext());

        // Session manager
        session = new SessionManager(activity.getApplicationContext());

        if (inflater == null)
            inflater = (LayoutInflater) activity.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
        if (convertView == null) 
            convertView = inflater.inflate(R.layout.menu_item, null);
        

        if (imageLoader == null) 
            imageLoader = AppController.getInstance().getImageLoader();
        

        TextView name = (TextView) convertView.findViewById(R.id.name);
        TextView description = (TextView) convertView.findViewById(R.id.description);
        NetworkImageView image = (NetworkImageView) convertView.findViewById(R.id.profilePic);
        //FeedImageView feedImageView = (FeedImageView) convertView.findViewById(R.id.feedImage1);

        final MenuItem item = menuItem.get(position);

        name.setText(item.getName());
        description.setText(item.getDescription());
        image.setImageUrl(item.getImage(), imageLoader);

        return convertView;
    

我在运行时发现问题,只是显示闪烁(强制关闭)。我认为listAdapter = new MenuListAdapter(getActivity(), menuItem);listView.setAdapter(listAdapter); 的问题。 希望我说清楚了,谢谢。

【问题讨论】:

首先在catch块here //txt.setText上方添加listAdapter = new MenuListAdapter..并显示错误代码 它会崩溃吗? 还是一样。 【参考方案1】:

一切都很好,除了一件事......!

您已在请求之前设置了适配器,此时您的菜单列表为空,因为您尚未收到来自 bac-kend 的任何数据。

//just here
listAdapter = new MenuListAdapter(getActivity(), menuItem);
    listView.setAdapter(listAdapter);
    // Inflate the layout for this fragment
    rq.add(stringRequest );

所以,当调用onResponse 回调时,您将获得数据... 您可以在其中添加一个逻辑来在此之前初始化您的适配器并刷新您的菜单列表并调用notifyDataSetChanged 方法来刷新您的列表视图。

只需像这样修改你的方法:

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

    View view = inflater.inflate(R.layout.fragment_siswa, container, false);
    //session = new SessionManager(getActivity().getApplicationContext());

    listView = (ListView) view.findViewById(R.id.listSiswa);
    menuItem = new ArrayList<MenuItem>();

    RequestQueue rq = Volley.newRequestQueue(getActivity().getApplicationContext());

    String no_hp = "085733777717";
    String URL = URL_FEED + "/?nomor_hp=" + no_hp;
    listAdapter = new MenuListAdapter(getActivity(), menuItem);
    listView.setAdapter(listAdapter);

    StringRequest stringRequest = new StringRequest(Request.Method.GET, URL,
            new Response.Listener<String>() 
                @Override
                public void onResponse(String response) 
                    // Do something with the response

                    try

                        JSONObject o = new JSONObject(response);
                        JSONArray feedArray = o.getJSONArray("data");

                        for (int i = 0; i < feedArray.length(); i++) 
                            JSONObject feedObj = (JSONObject) feedArray.get(i);

                            //Toast.makeText(getApplicationContext(), feedObj.toString(), Toast.LENGTH_LONG).show();
                            MenuItem item = new MenuItem();
                            item.setId(feedObj.getString("kode"));
                            item.setImage(AppConfig.URL_ASSETS + "user.png");
                            item.setName(feedObj.getString("nama"));
                            item.setDescription(feedObj.getString("kelas"));
                            item.setRemarks(feedObj.getString("sekolah"));

                            menuItem.add(item);
                        

                        //txt.setText(sb.toString());
                        listAdapter.notifyDataSetChanged();

                      catch (JSONException ex)

                
            ,
            new Response.ErrorListener() 
                @Override
                public void onErrorResponse(VolleyError error) 
                    // Handle error
                
            );
    // Inflate the layout for this fragment
    rq.add(stringRequest );
    return view;

【讨论】:

@Yohanes Budi Hartoyo 如果我的回答对你有帮助,请接受我的回答。 感谢您的帮助。但是,我的问题还没有解决。还是和上一个一样。 03-14 17:14:00.313 1342-3949/? W/ActivityManager:强制完成活动 1 com.absensi.studenttoparent/.activity.MainActivity 我从 [androidhive.info/2013/11/… 获得了滑动菜单和片段的示例,并与 [***.com/questions/35673159/… 组合用于函数 onCreateView。 logcat --> W/ActivityManager﹕ Force finishing activity 1 com.absensi.studenttoparent/.activity.MainActivity 您可以查看此link,希望对您有所帮助。

以上是关于具有获取 json 值的片段中的自定义适配器的主要内容,如果未能解决你的问题,请参考以下文章

片段中的自定义列表适配器

片段中 ListView 的自定义适配器不起作用

片段中ListView的android自定义适配器

如何将最新数据附加到android中的自定义基本适配器列表视图?

具有包含 CheckBoxes 的自定义适配器的 Listview

Java 数据类型的自定义 JSON 序列化