userNoIdea
userNoIdea

Reputation: 143

How to solve the Null Exception Error

i'm trying to filter the code and currently met with some NullException error.. can anyone help me out?

I would like to get the code from a URL sources(XML Data) and filter it out using Spinner

Example: spinner : "Today","Tomorrow" Upon select "Today" it will show out the events for today. Upon select "Tomorrow" it will show out the events for tomorrow.

However, I meet with some Null Exception. Can anyone guide me?

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;
        }
        }

The Null Exception Error is at here :

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

Upvotes: 0

Views: 201

Answers (3)

Simon Dorociak
Simon Dorociak

Reputation: 33505

String[] browseby;

Your array is not initialised (has length assigned to zero). You need to initialise it:

browseby = new String[<size>];

But especially in your case try to think about an usage of dynamic array instead static array (your case). You don't know how many items you will have to insert.

Dynamic array is in your case more efficient to use.

Update:

how do I use as dynamic array?

Dynamic array is array with dynamic size (size is automatic increased when you're adding more and more items). So you need just replace yours static browseby array with next List for example:

List<String> browseby = new ArrayList<String>();

Upvotes: 1

Mukhtiar Ahmed
Mukhtiar Ahmed

Reputation: 631

Please check your code browseby is null because you are not initializing browseby the in clas. Initialize the browseby before use.

Upvotes: 0

Mukesh Dabhi
Mukesh Dabhi

Reputation: 85

just put a condition before start a loop :

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]);
        }
}

Upvotes: 0

Related Questions