0

我正在尝试过滤代码,目前遇到了一些 NullException 错误。有人可以帮帮我吗?

我想从 URL 源(XML 数据)中获取代码并使用 Spinner 将其过滤掉

示例:微调器:“今天”,“明天” 选择“今天”后,它将显示今天的事件。选择“明天”后,它将显示明天的事件。

但是,我遇到了一些空异常。谁能指导我?

public class AndroidXMLParsingActivity extends ListActivity implements OnItemSelectedListener {

    String[] browseby;
    Date d = new Date();

    String[] dates = { "Today", "Tomorrow", "Next Week",

    };

    ArrayList<String> browse = new ArrayList<String>();
    ArrayList<String> mPostingData = new ArrayList<String>();
    Spinner s1;
    ListView listview;
    CustomAdapter cus;

    // All static variables
    static final String URL = "http://api.eventful.com/rest/events/search?app_key=42t54cX7RbrDFczc&location=singapore";
    // XML node keys
    static final String KEY_EVENT = "event"; // parent node
    static final String KEY_TITLE = "title";
    static final String KEY_START_TIME = "start_time";


    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        ArrayList<HashMap<String, String>> menuItems = new ArrayList<HashMap<String, String>>();

        XMLParser parser = new XMLParser();
        String xml = parser.getXmlFromUrl(URL); // getting XML
        Document doc = parser.getDomElement(xml); // getting DOM element

        NodeList nl = doc.getElementsByTagName(KEY_EVENT);
        // looping through all item nodes <item>
        for (int i = 0; i < nl.getLength(); i++) {
            // creating new HashMap
            HashMap<String, String> map = new HashMap<String, String>();
            Element e = (Element) nl.item(i);
            // adding each child node to HashMap key => value
            map.put(KEY_TITLE, parser.getValue(e, KEY_TITLE));


            map.put(KEY_START_TIME, parser.getValue(e, KEY_START_TIME));

            // adding HashList to ArrayList
            menuItems.add(map);
        }

        // Adding menuItems to ListView
        ListAdapter adapter = new SimpleAdapter(this, menuItems,
                R.layout.list_item, new String[] { KEY_TITLE,KEY_START_TIME }, new int[] {
                        R.id.title,
                        R.id.startTime });

        setListAdapter(adapter);

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

        lv.setOnItemClickListener(new OnItemClickListener() {

            @Override
            public void onItemClick(AdapterView<?> parent, View view,
                    int position, long id) {
                // getting values from selected ListItem
                String title = ((TextView) view.findViewById(R.id.title))
                        .getText().toString();


                // Starting new intent
                Intent in = new Intent(getApplicationContext(),
                        SingleMenuItemActivity.class);
                in.putExtra(KEY_TITLE, title);


                startActivity(in);

            }
        });
        listview = (ListView) findViewById(R.id.listView1);
        s1 = (Spinner) findViewById(R.id.spinner1);
        for (int i = 0; i < browseby.length; i++) {
            browse.add(browseby[i]);
        }

        // aa = new
        // ArrayAdapter<String>(this,android.R.layout.simple_list_item_1,Category);
        s1.setOnItemSelectedListener(this);
        mPostingData = browse;
        for (int i = 0; i < mPostingData.size(); i++) {
            if (mPostingData.size() > 0)
                Log.i("Datas", mPostingData.get(i));
        }
        cus = new CustomAdapter(this, 0);
        setListAdapter(cus);

        ArrayAdapter<String> aa = new ArrayAdapter<String>(this,
                android.R.layout.simple_spinner_item, dates);

        aa.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
        s1.setAdapter(aa);
        }

    public void onItemSelected(AdapterView<?> parent, View v, int position,
            long id) {
        // listview.setFilterText(Category[position]);
        String Text = s1.getSelectedItem().toString();
        cus.getFilter().filter(Text);
        cus.notifyDataSetChanged();
        }

        public void onNothingSelected(AdapterView<?> parent) {
        // listview.setFilterText("");
        }

        public void onListItemClick(ListView parent, View v, int position, long id) {
        Toast.makeText(this, "You have selected " + mPostingData.get(position),
                Toast.LENGTH_SHORT).show();
        }

        class CustomAdapter extends ArrayAdapter<String> {

        public void setData(ArrayList<String> mPpst) {
            mPostingData = mPpst;// contains class items data.
        }

        @Override
        public Filter getFilter() {
            return new Filter() {
                @Override
                protected void publishResults(CharSequence constraint,
                        FilterResults start_time) {
                    if (start_time != null && start_time.count >= 0) {
                        setData((ArrayList<String>) start_time.values);
                    } else {
                        setData(browse);// set original values
                    }

                    notifyDataSetInvalidated();
                }

                @Override
                protected FilterResults performFiltering(CharSequence constraint) {
                    FilterResults result = new FilterResults();
                    if(constraint=="Today")  {

                        constraint = constraint.toString();
                        CharSequence s  = DateFormat.format("yyyy-MM-dd ", d.getTime());
                        ArrayList<String> foundItems = new ArrayList<String>();
                        if (browse != null) {
                            for (int i = 0; i < browse.size(); i++) {

                                if (browse.get(i).contains(s)){
                                    System.out.println("My datas" + browse.get(i));
                                    foundItems.add(browse.get(i));

                                } else {



                                }
                            }
                        }
                        result.count = foundItems.size();// search results found
                                                            // return count
                        result.values = foundItems;// return values
                    } else {
                        result.count = -1;// no search results found
                    }

                    return result;
                }
            };
        }

        LayoutInflater mInflater;

        public CustomAdapter(Context context, int textViewResourceId) {
            super(context, textViewResourceId);
            // TODO Auto-generated constructor stub
            mInflater = (LayoutInflater) context
                    .getSystemService(Context.LAYOUT_INFLATER_SERVICE);
        }

        @Override
        public int getCount() {
            // TODO Auto-generated method stub
            return mPostingData.size();
        }

        @Override
        public long getItemId(int position) {
            // TODO Auto-generated method stub
            return position;
        }

        @Override
        public View getView(int position, View convertView, ViewGroup parent) {
            // TODO Auto-generated method stub
            ViewHolder vh;
            if (convertView == null) {
                vh = new ViewHolder();
                convertView = mInflater.inflate(R.layout.row, null);
                vh.t1 = (TextView) convertView.findViewById(R.id.textView1);

                convertView.setTag(vh);
            } else {
                // Get the ViewHolder back to get fast access to the TextView
                // and the ImageView.
                vh = (ViewHolder) convertView.getTag();
            }
            if (mPostingData.size() > 0)
                vh.t1.setText(mPostingData.get(position));
            return convertView;
        }

        }

        static class ViewHolder {
        TextView t1;
        }
        }

空异常错误在这里:

for (int i = 0; i < browseby.length; i++) {
4

3 回答 3

1
String[] browseby;

您的数组未初始化(长度分配为零)。你需要初始化它:

browseby = new String[<size>];

但尤其是在您的情况下,请尝试考虑使用动态数组而不是静态数组(您的情况)。您不知道要插入多少项目。

在您的情况下,动态数组的使用效率更高。

更新:

如何用作动态数组?

动态数组是具有动态大小的数组(当您添加越来越多的项目时,大小会自动增加)。因此,您只需用 next 替换您的静态 browseby 数组,List例如:

List<String> browseby = new ArrayList<String>();
于 2013-08-02T06:36:55.780 回答
0

只需在开始循环之前放置一个条件:

if(browseby!=null){
  [ your loop ]
}
or
if(browseby==null){

            browse.add("Data  Note Found");

}else{
for (int i = 0; i < browseby.length; i++) {
            browse.add(browseby[i]);
        }
}
于 2013-08-02T06:41:04.737 回答
0

请检查您的代码 browseby 是否为 null,因为您没有在 in 类中初始化 browseby。使用前初始化browseby。

于 2013-08-02T06:41:25.283 回答