如何绑定的ListView对象中的片段? [英] How to bind ListView Objects in Fragments?

查看:75
本文介绍了如何绑定的ListView对象中的片段?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个问题,我的JSON数据对象绑定到ListView片段。我发现了一个NPE在第100行,我绑定到我的简单的适配器。我试图了解这样做的各种方法,但都没有成功。据<一href="http://developer.android.com/reference/android/app/ListFragment.html#setListAdapter%28android.widget.ListAdapter%29"相对=nofollow>的文档:

  

您必须使用<一个href="http://developer.android.com/reference/android/app/ListFragment.html#setListAdapter%28android.widget.ListAdapter%29"相对=nofollow> ListFragment.setListAdapter()到列表中与关联   的适配器。不要直接调用ListView.setAdapter(),否则   重要的初始化将被跳过。

我敢肯定,这是我的问题,但我不知道如何去纠正我的code。下面是NPE和我的活动。请任何帮助将AP preciated,尤其是因为我学习,我去....一些code例如

  

主题ID = 1:螺纹未捕获异常退出(组= 0x40a781f8)   致命异常:在主显示java.lang.NullPointerException   android.widget.SimpleAdapter(SimpleAdapter.java:85)在   com.andaero.app.NavigationListFragment $ 1.callback(NavigationListFragment.java:100)   在   com.andaero.app.NavigationListFragment $ 1.callback(NavigationListFragment.java:1)   在   com.androidquery.callback.AbstractAjaxCallback.callback(AbstractAjaxCallback.java:440)   在   com.androidquery.callback.AbstractAjaxCallback.afterWork(AbstractAjaxCallback.java:1010)   在   com.androidquery.callback.AbstractAjaxCallback.run(AbstractAjaxCallback.java:804​​)   在android.os.Handler.handleCallback(Handler.java:605)在   android.os.Handler.dispatchMessage(Handler.java:92)在   android.os.Looper.loop(Looper.java:137)在   android.app.ActivityThread.main(ActivityThread.java:4424)在   java.lang.reflect.Method.invokeNative(本机方法)在   java.lang.reflect.Method.invoke(Method.java:511)在   com.android.internal.os.ZygoteInit $ MethodAndArgsCaller.run(ZygoteInit.java:787)   在com.android.internal.os.ZygoteInit.main(ZygoteInit.java:554)在   dalvik.system.NativeStart.main(本机方法)

 公共类NavigationListFragment扩展ListFragment {
    上下文语境;
    私人活动℃;
    最后AQuery AQ =新AQuery(C);
    私有静态字符串URL =htt​​p://192.168.1.17/Andaero/php/regulatory_list.php;

    @覆盖
    公共查看onCreateView(LayoutInflater充气,容器的ViewGroup,捆绑savedInstanceState){
        最终的视图中查看= inflater.inflate(R.layout.listview,集装箱,假);
        Log.i(NavigationListFragment,ListView的充气!!);
        返回查看;
    }

    @覆盖
    公共无效onActivityCreated(包savedInstanceState){
        super.onActivityCreated(savedInstanceState);
        // AsyncTasks.getJSONArrays(上下文);用于获取//异步任务
        // JSONarray
        aq.ajax(URL,JSONArray.class,新AjaxCallback&LT; JSONArray&GT;(){
            // JSON节点名称
            私有静态最后弦乐TAG_ID =_id;
            私有静态最后弦乐TAG_LABEL =标签;
            私有静态最后弦乐TAG_TITLE =称号;
            私有静态最后弦乐TAG_DISCR =说明;
            私有静态最后弦乐TAG_GO2URL =gotoURL;

            公共无效回调(字符串URL,JSONArray JSON,AjaxStatus状态){
                如果(JSON!= NULL){
                    // NavigationListFragment.jsonListCallback(JSON);
                    Log.i(NavigationListFragment,陷入JSON:+ json.toString());
                    //哈希映射为的ListView
                    ArrayList的&LT; HashMap的&LT;字符串,字符串&GT;&GT; mList =新的ArrayList&LT; HashMap的&LT;字符串,字符串&GT;&GT;();
                    尝试 {
                        //解析字符串到JSON对象
                        的for(int i = 0; I&LT; json.length();我++){
                            的JSONObject json_data = json.getJSONObject(ⅰ);

                            //保存在变量中的每个JSON项目
                            字符串ID = json_data.getString(TAG_ID);
                            字符串标签= json_data.getString(TAG_LABEL);
                            字符串标题= json_data.getString(TAG_TITLE);
                            字符串描述= json_data.getString(TAG_DISCR);
                            字符串gotoURL = json_data.getString(TAG_GO2URL);

                            //创建新的HashMap
                            HashMap的&LT;字符串,字符串&GT;图=新的HashMap&LT;字符串,字符串&GT;();

                            //添加每个子节点HashMap中的key =&GT;值
                            map.put(tag_id,分别编号);
                            map.put(TAG_LABEL,标签);
                            map.put(TAG_TITLE,职称);
                            map.put(TAG_DISCR,说明);
                            map.put(TAG_GO2URL,gotoURL);

                            //添加HashList到ArrayList中
                            mList.add(图)
                            Log.i(NavigationListFragment,散列:+地图);
                        }
                    }赶上(JSONException E){
                        Log.e(log_tag,错误分析数据+ e.toString());
                    }

                    //创建列表项映射
                    字符串从=新的String [] {TAG_LABEL,TAG_TITLE,TAG_DISCR,TAG_GO2URL} [];
                    INT []到=新INT [] {R.id.listLabel,R.id.listTitle,R.id.listDiscription,R.id.dummy};

                    //更新已解析JSON数据到ListView控件
                    SimpleAdapter适配器=新SimpleAdapter(C,mList,R.layout.list_item,从,到); //&LT;  -  NPE IS HERE
                    setListAdapter(适配器);

                    //选择单一的ListView项
                    ListView的LV = getListView();

                    //启动新的页面中选择单列表项
                    lv.setOnItemClickListener(新OnItemClickListener(){

                        公共无效onItemClick(适配器视图&LT;&GT;母公司视图中查看,
                                INT位置,长的id){
                            //去做
                        }
                    });

                }
                //登录任何网络/ JSON错误
                开关(status.get code()){
                    案例AjaxStatus.TRANSFORM_ERROR:
                        Log.i(GetJSONArray,TRANSFORM_ERROR);
                        打破;
                    案例AjaxStatus.NETWORK_ERROR:
                        Log.i(GetJSONArray,NETWORK_ERROR);
                        // TODO创建警报对话框
                    案例AjaxStatus.AUTH_ERROR:
                        Log.i(GetJSONArray,AUTH_ERROR);
                        打破;
                }
            }
        });

    }
}
 

解决方案

除非你是忽略code你永远不分配的 C值上下文

在调用

  SimpleAdapter适配器=新SimpleAdapter(C,mList,R.layout.list_item,从,到);
 

正在传递C,这将永远是空的。

开关C到 getActivity(),问题应该消失

Additionaly,

 最后AQuery AQ =新AQuery(C);
 

您应该初始化这个一旦你知道你有机会到getActivity()。当创建一个片段也不会立即访问的活动,直到连接(..)被调用。

I am having an issue binding my JSON data Object to a listView fragment. I'm getting an NPE at line 100 where I bind to my Simple Adapter. I have tried various ways about doing this but have been unsuccessful. According to the docs:

You must use ListFragment.setListAdapter() to associate the list with an adapter. Do not directly call ListView.setAdapter() or else important initialization will be skipped.

I'm sure that is my issue but I don't know how to go about correcting my code. Below is the NPE and my activity. Please any help will be appreciated, esp some code example because I'm learning as I go....

threadid=1: thread exiting with uncaught exception (group=0x40a781f8) FATAL EXCEPTION: main java.lang.NullPointerException at android.widget.SimpleAdapter.(SimpleAdapter.java:85) at com.andaero.app.NavigationListFragment$1.callback(NavigationListFragment.java:100) at com.andaero.app.NavigationListFragment$1.callback(NavigationListFragment.java:1) at com.androidquery.callback.AbstractAjaxCallback.callback(AbstractAjaxCallback.java:440) at com.androidquery.callback.AbstractAjaxCallback.afterWork(AbstractAjaxCallback.java:1010) at com.androidquery.callback.AbstractAjaxCallback.run(AbstractAjaxCallback.java:804) at android.os.Handler.handleCallback(Handler.java:605) at android.os.Handler.dispatchMessage(Handler.java:92) at android.os.Looper.loop(Looper.java:137) at android.app.ActivityThread.main(ActivityThread.java:4424) at java.lang.reflect.Method.invokeNative(Native Method) at java.lang.reflect.Method.invoke(Method.java:511) at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:787) at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:554) at dalvik.system.NativeStart.main(Native Method)

public class NavigationListFragment extends ListFragment {
    Context context;
    private Activity c;
    final AQuery aq = new AQuery(c);
    private static String url = "http://192.168.1.17/Andaero/php/regulatory_list.php";

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        final View view = inflater.inflate(R.layout.listview, container, false);
        Log.i("NavigationListFragment", "ListView Inflated!!");
        return view;
    }

    @Override
    public void onActivityCreated(Bundle savedInstanceState) {
        super.onActivityCreated(savedInstanceState);
        // AsyncTasks.getJSONArrays(context);// asynchronous task for getting
        // JSONarray
        aq.ajax(url, JSONArray.class, new AjaxCallback<JSONArray>() {
            // JSON Node names
            private static final String TAG_ID = "_id";
            private static final String TAG_LABEL = "label";
            private static final String TAG_TITLE = "title";
            private static final String TAG_DISCR = "description";
            private static final String TAG_GO2URL = "gotoURL";

            public void callback(String url, JSONArray json, AjaxStatus status) {
                if (json != null) {
                    // NavigationListFragment.jsonListCallback(json);
                    Log.i("NavigationListFragment", "Caught JSON: " + json.toString());
                    // Hashmap for ListView
                    ArrayList<HashMap<String, String>> mList = new ArrayList<HashMap<String, String>>();
                    try {
                        // Parse the string to a JSON object
                        for (int i = 0; i < json.length(); i++) {
                            JSONObject json_data = json.getJSONObject(i);

                            // Storing each json item in variable
                            String id = json_data.getString(TAG_ID);
                            String label = json_data.getString(TAG_LABEL);
                            String title = json_data.getString(TAG_TITLE);
                            String description = json_data.getString(TAG_DISCR);
                            String gotoURL = json_data.getString(TAG_GO2URL);

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

                            // adding each child node to HashMap key => value
                            map.put(TAG_ID, id);
                            map.put(TAG_LABEL, label);
                            map.put(TAG_TITLE, title);
                            map.put(TAG_DISCR, description);
                            map.put(TAG_GO2URL, gotoURL);

                            // adding HashList to ArrayList
                            mList.add(map);
                            Log.i("NavigationListFragment", "Hash: " + map);
                        }
                    } catch (JSONException e) {
                        Log.e("log_tag", "Error parsing data " + e.toString());
                    }

                    // create the list item mapping
                    String[] from = new String[] {TAG_LABEL, TAG_TITLE, TAG_DISCR, TAG_GO2URL};
                    int[] to = new int[] { R.id.listLabel, R.id.listTitle, R.id.listDiscription, R.id.dummy };

                    // Updating parsed JSON data into ListView
                    SimpleAdapter adapter = new SimpleAdapter(c, mList, R.layout.list_item, from, to);//<--NPE IS HERE
                    setListAdapter(adapter);

                    // selecting single ListView item
                    ListView lv = getListView();

                    // Launching new screen on Selecting Single ListItem
                    lv.setOnItemClickListener(new OnItemClickListener() {

                        public void onItemClick(AdapterView<?> parent, View view,
                                int position, long id) {
                            //TODO
                        }
                    });

                }
                // Log any network/JSON Errors
                switch (status.getCode()) {
                    case AjaxStatus.TRANSFORM_ERROR :
                        Log.i("GetJSONArray", "TRANSFORM_ERROR");
                        break;
                    case AjaxStatus.NETWORK_ERROR :
                        Log.i("GetJSONArray", "NETWORK_ERROR");
                        // TODO Create Alert Dialog
                    case AjaxStatus.AUTH_ERROR :
                        Log.i("GetJSONArray", "AUTH_ERROR");
                        break;
                }
            }
        });

    }
}

解决方案

Unless you are omitting code you never assign the value of c or context.

When calling

SimpleAdapter adapter = new SimpleAdapter(c, mList, R.layout.list_item, from, to);

You are passing in "c" which will always be null.

switch "c" to getActivity() and the problem should go away

Additionaly,

final AQuery aq = new AQuery(c);

You should initialize this once you know you have access to getActivity(). When a fragment is created it will not immediately have access to the activity until attach(..) is called.

这篇关于如何绑定的ListView对象中的片段?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆