0

When i run my app, and i press on a button it force closes. I fixed my Android manifest and i cannot find the problem. Here is the Logcat:

   03-09 17:46:17.301: D/dalvikvm(2133): Debugger has detached; object registry had 1 entries
03-09 17:46:17.438: D/dalvikvm(2133): GC_EXTERNAL_ALLOC freed 43K, 49% free 2794K/5379K, external 1596K/2108K, paused 95ms
03-09 17:46:17.587: D/dalvikvm(2133): GC_EXTERNAL_ALLOC freed 1K, 49% free 2793K/5379K, external 3471K/4335K, paused 42ms
03-09 17:46:17.825: D/dalvikvm(2133): GC_EXTERNAL_ALLOC freed <1K, 49% free 2795K/5379K, external 5048K/5580K, paused 76ms
03-09 17:46:18.001: D/dalvikvm(2133): GC_EXTERNAL_ALLOC freed <1K, 49% free 2796K/5379K, external 8143K/8403K, paused 44ms
03-09 17:46:49.407: D/dalvikvm(2133): GC_EXTERNAL_ALLOC freed 15K, 48% free 2825K/5379K, external 11785K/11958K, paused 19ms
03-09 17:46:49.544: D/dalvikvm(2133): GC_EXTERNAL_ALLOC freed 1K, 48% free 2826K/5379K, external 13363K/14068K, paused 19ms
03-09 17:46:49.622: D/dalvikvm(2133): GC_EXTERNAL_ALLOC freed <1K, 48% free 2827K/5379K, external 16457K/17091K, paused 19ms
03-09 17:46:49.704: D/AndroidRuntime(2133): Shutting down VM
03-09 17:46:49.704: W/dalvikvm(2133): threadid=1: thread exiting with uncaught exception (group=0x40015578)
03-09 17:46:49.708: E/AndroidRuntime(2133): FATAL EXCEPTION: main
03-09 17:46:49.708: E/AndroidRuntime(2133): java.lang.RuntimeException: Unable to start activity ComponentInfo{izzy.n/izzy.n.main1}: java.lang.NullPointerException
03-09 17:46:49.708: E/AndroidRuntime(2133):     at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:1651)
03-09 17:46:49.708: E/AndroidRuntime(2133):     at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:1667)
03-09 17:46:49.708: E/AndroidRuntime(2133):     at android.app.ActivityThread.access$1500(ActivityThread.java:117)
03-09 17:46:49.708: E/AndroidRuntime(2133):     at android.app.ActivityThread$H.handleMessage(ActivityThread.java:935)
03-09 17:46:49.708: E/AndroidRuntime(2133):     at android.os.Handler.dispatchMessage(Handler.java:99)
03-09 17:46:49.708: E/AndroidRuntime(2133):     at android.os.Looper.loop(Looper.java:130)
03-09 17:46:49.708: E/AndroidRuntime(2133):     at android.app.ActivityThread.main(ActivityThread.java:3687)
03-09 17:46:49.708: E/AndroidRuntime(2133):     at java.lang.reflect.Method.invokeNative(Native Method)
03-09 17:46:49.708: E/AndroidRuntime(2133):     at java.lang.reflect.Method.invoke(Method.java:507)
03-09 17:46:49.708: E/AndroidRuntime(2133):     at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:842)
03-09 17:46:49.708: E/AndroidRuntime(2133):     at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:600)
03-09 17:46:49.708: E/AndroidRuntime(2133):     at dalvik.system.NativeStart.main(Native Method)
03-09 17:46:49.708: E/AndroidRuntime(2133): Caused by: java.lang.NullPointerException
03-09 17:46:49.708: E/AndroidRuntime(2133):     at izzy.n.main1.populateCalendarSpinner(main1.java:69)
03-09 17:46:49.708: E/AndroidRuntime(2133):     at izzy.n.main1.onCreate(main1.java:52)
03-09 17:46:49.708: E/AndroidRuntime(2133):     at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1047)
03-09 17:46:49.708: E/AndroidRuntime(2133):     at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:1615)
03-09 17:46:49.708: E/AndroidRuntime(2133):     ... 11 more

Here is the code for Android Manifest:

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="izzy.n"
    android:versionCode="1"
    android:versionName="1.0" >

     <uses-sdk android:minSdkVersion="10" />


     <uses-permission android:name="android.permission.READ_CALENDAR"></uses-permission>
    <uses-permission android:name="android.permission.WRITE_CALENDAR"></uses-permission>

    <application



        android:icon="@drawable/ic_launcher"
        android:label="@string/app_name" >
        <activity
            android:name="izzy.n.IzzynActivity"
            android:label="@string/app_name" >
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />

                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
        <activity
            android:name="izzy.n.notes"
            android:label="@string/notes"></activity>


        <activity 
            android:name="izzy.n.calculator"
            android:label="@string/calculator"></activity>


        <activity android:name="izzy.n.main1"
                  android:label="@string/app_name"></activity>

    </application>








</manifest>

and finally here is the main1.java:

class MyCalendar {
    public String name;
    public String id;
    public MyCalendar(String _name, String _id) {
        name = _name;
        id = _id;
    }
    @Override
    public String toString() {
        return name;
    }
}

public class main1 extends Activity {
    /*********************************************************************
     * UI part*/
    private Spinner m_spinner_calender;
    private Button m_button_add;
    private Button m_button_add2;
    private Button m_button_getEvents;
    private TextView m_text_event;
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
        /*get calendar list and populate the view*/
        getCalendars();
        populateCalendarSpinner();
        populateAddBtn();
        populateAddBtn2();
        populateTextEvent();
        populateGetEventsBtn();
    }
    private void populateCalendarSpinner() {
        m_spinner_calender = (Spinner)this.findViewById(R.id.spinner_calendar);
        ArrayAdapter l_arrayAdapter = new ArrayAdapter(this.getApplicationContext(), android.R.layout.simple_spinner_item, m_calendars);
        l_arrayAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
        m_spinner_calender.setAdapter(l_arrayAdapter);
        m_spinner_calender.setSelection(0);
        m_spinner_calender.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
            @Override
            public void onItemSelected(AdapterView<?> p_parent, View p_view,
                    int p_pos, long p_id) {
                m_selectedCalendarId = m_calendars[(int)p_id].id;
            }
            @Override
            public void onNothingSelected(AdapterView<?> arg0) {}
        });
    }
    private void populateAddBtn() {
        m_button_add = (Button) this.findViewById(R.id.button_add);
        m_button_add.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                addEvent();
            }
        });
    }
    private void populateAddBtn2() {
        m_button_add2 = (Button) this.findViewById(R.id.button_add2);
        m_button_add2.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                addEvent2();
            }
        });
    }
    private void populateGetEventsBtn() {
        m_button_getEvents = (Button) findViewById(R.id.button_get_events);
        m_button_getEvents.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                getLastThreeEvents();
            }
        });
    }
    private void populateTextEvent() {
        m_text_event = (TextView) findViewById(R.id.text_event);
        String l_str = "title: roman10 calendar tutorial test\n" +
            "description: This is a simple test for calendar api\n" + 
            "eventLocation: @home\n" + 
            "start time:" + getDateTimeStr(0) + "\n" + 
            "end time: " + getDateTimeStr(30) + "\n" + 
            "event status: confirmed\n" + 
            "all day: no\n" + 
            "has alarm: yes\n";
        m_text_event.setText(l_str);
    }
    /****************************************************************
     * Data part
     */
    /*retrieve a list of available calendars*/
    private MyCalendar m_calendars[];
    private String m_selectedCalendarId = "0";
    private void getCalendars() {
        String[] l_projection = new String[]{"_id", "displayName"};
        Uri l_calendars;
        if (Build.VERSION.SDK_INT >= 8) {
            l_calendars = Uri.parse("content://com.android.calendar/calendars");
        } else {
            l_calendars = Uri.parse("content://calendar/calendars");
        }
        Cursor l_managedCursor = this.managedQuery(l_calendars, l_projection, null, null, null);    //all calendars
        //Cursor l_managedCursor = this.managedQuery(l_calendars, l_projection, "selected=1", null, null);   //active calendars
        if (l_managedCursor.moveToFirst()) {
            m_calendars = new MyCalendar[l_managedCursor.getCount()];
            String l_calName;
            String l_calId;
            int l_cnt = 0;
            int l_nameCol = l_managedCursor.getColumnIndex(l_projection[1]);
            int l_idCol = l_managedCursor.getColumnIndex(l_projection[0]);
            do {
                l_calName = l_managedCursor.getString(l_nameCol);
                l_calId = l_managedCursor.getString(l_idCol);
                m_calendars[l_cnt] = new MyCalendar(l_calName, l_calId);
                ++l_cnt;
            } while (l_managedCursor.moveToNext());
        }
    }
    /*add an event to calendar*/
    private void addEvent() {
        ContentValues l_event = new ContentValues();
        l_event.put("calendar_id", m_selectedCalendarId);
        l_event.put("title", "roman10 calendar tutorial test");
        l_event.put("description", "This is a simple test for calendar api");
        l_event.put("eventLocation", "@home");
        l_event.put("dtstart", System.currentTimeMillis());
        l_event.put("dtend", System.currentTimeMillis() + 1800*1000);
        l_event.put("allDay", 0);
        //status: 0~ tentative; 1~ confirmed; 2~ canceled
        l_event.put("eventStatus", 1);
        //0~ default; 1~ confidential; 2~ private; 3~ public
        l_event.put("visibility", 0);
        //0~ opaque, no timing conflict is allowed; 1~ transparency, allow overlap of scheduling
        l_event.put("transparency", 0);
        //0~ false; 1~ true
        l_event.put("hasAlarm", 1);
        Uri l_eventUri;
        if (Build.VERSION.SDK_INT >= 8) {
            l_eventUri = Uri.parse("content://com.android.calendar/events");
        } else {
            l_eventUri = Uri.parse("content://calendar/events");
        }
        Uri l_uri = this.getContentResolver().insert(l_eventUri, l_event);
        Log.v("++++++test", l_uri.toString());
    }
    /*add an event through intent, this doesn't require any permission
     * just send intent to android calendar
     * http://www.openintents.org/en/uris*/
    private void addEvent2() {
        Intent l_intent = new Intent(Intent.ACTION_EDIT);
        l_intent.setType("vnd.android.cursor.item/event");
        //l_intent.putExtra("calendar_id", m_selectedCalendarId);  //this doesn't work
        l_intent.putExtra("title", "roman10 calendar tutorial test");
        l_intent.putExtra("description", "This is a simple test for calendar api");
        l_intent.putExtra("eventLocation", "@home");
        l_intent.putExtra("beginTime", System.currentTimeMillis());
        l_intent.putExtra("endTime", System.currentTimeMillis() + 1800*1000);
        l_intent.putExtra("allDay", 0);
        //status: 0~ tentative; 1~ confirmed; 2~ canceled
        l_intent.putExtra("eventStatus", 1);
        //0~ default; 1~ confidential; 2~ private; 3~ public
        l_intent.putExtra("visibility", 0);
        //0~ opaque, no timing conflict is allowed; 1~ transparency, allow overlap of scheduling
        l_intent.putExtra("transparency", 0);
        //0~ false; 1~ true
        l_intent.putExtra("hasAlarm", 1);
        try {
            startActivity(l_intent);
        } catch (Exception e) {
            Toast.makeText(this.getApplicationContext(), "Sorry, no compatible calendar is found!", Toast.LENGTH_LONG).show();
        }
    }
    /*get a list of events
     * http://jimblackler.net/blog/?p=151*/
    private void getLastThreeEvents() {
        Uri l_eventUri;
        if (Build.VERSION.SDK_INT >= 8) {
            l_eventUri = Uri.parse("content://com.android.calendar/events");
        } else {
            l_eventUri = Uri.parse("content://calendar/events");
        }
        String[] l_projection = new String[]{"title", "dtstart", "dtend"};
        Cursor l_managedCursor = this.managedQuery(l_eventUri, l_projection, "calendar_id=" + m_selectedCalendarId, null, "dtstart DESC, dtend DESC");
        //Cursor l_managedCursor = this.managedQuery(l_eventUri, l_projection, null, null, null);
        if (l_managedCursor.moveToFirst()) {
            int l_cnt = 0;
            String l_title;
            String l_begin;
            String l_end;
            StringBuilder l_displayText = new StringBuilder();
            int l_colTitle = l_managedCursor.getColumnIndex(l_projection[0]);
            int l_colBegin = l_managedCursor.getColumnIndex(l_projection[1]);
            int l_colEnd = l_managedCursor.getColumnIndex(l_projection[1]);
            do {
                l_title = l_managedCursor.getString(l_colTitle);
                l_begin = getDateTimeStr(l_managedCursor.getString(l_colBegin));
                l_end = getDateTimeStr(l_managedCursor.getString(l_colEnd));
                l_displayText.append(l_title + "\n" + l_begin + "\n" + l_end + "\n----------------\n");
                ++l_cnt;
            } while (l_managedCursor.moveToNext() && l_cnt < 3);
            m_text_event.setText(l_displayText.toString());
        }
    }
    /************************************************
     * utility part
     */
    private static final String DATE_TIME_FORMAT = "yyyy MMM dd, HH:mm:ss";
    public static String getDateTimeStr(int p_delay_min) {
        Calendar cal = Calendar.getInstance();
        SimpleDateFormat sdf = new SimpleDateFormat(DATE_TIME_FORMAT);
        if (p_delay_min == 0) {
            return sdf.format(cal.getTime());
        } else {
            Date l_time = cal.getTime();
            l_time.setMinutes(l_time.getMinutes() + p_delay_min);
            return sdf.format(l_time);
        }
    }
    public static String getDateTimeStr(String p_time_in_millis) {
        SimpleDateFormat sdf = new SimpleDateFormat(DATE_TIME_FORMAT);
        Date l_time = new Date(Long.parseLong(p_time_in_millis));
        return sdf.format(l_time);
    }
}
user1248404
  • 59
  • 1
  • 8

2 Answers2

1

If you look at your stack trace, you'll see that the problem is a NullPointerException from here:

at izzy.n.main1.populateCalendarSpinner(main1.java:69)

Something at line 69 in main1 is null, but you are trying to use it. I can't tell which line that is from what you've provided above, so its tough to provide a more specific answer.

Here is my guess. If the cause is from this line:

  m_selectedCalendarId = m_calendars[(int)p_id].id;

Then there might not be an element at m_calendars[(int)p_id]. What you might really need is:

  m_selectedCalendarId = m_calendars[p_pos].id;

For future reference, the Eclipse Debugger is a great help in situations like this. Here is a tutorial to help you get started with it: http://www.ibm.com/developerworks/library/os-ecbug/

Eric Levine
  • 13,536
  • 5
  • 49
  • 49
  • If i dont set it to zero, what would the argument be? – user1248404 Mar 09 '12 at 23:07
  • Are you talking about this line: m_spinner_calender.setSelection(0); ? If so, are you sure that is line 69? – Eric Levine Mar 09 '12 at 23:10
  • `m_button_getEvents = (Button) findViewById(R.id.button_get_events);` is line 69. Does this button id exist? – Matt K Mar 09 '12 at 23:11
  • m_spinner_calender.setSelection(0); = line 69 – user1248404 Mar 09 '12 at 23:13
  • @MattK are you sure that is it? The stack trace says it is within the populateCalendarSpinner method. – Eric Levine Mar 09 '12 at 23:14
  • @user1248404 I don't think that is right, because the stack trace indicates that line 52 (from onCreate) is calling populateCalendarSpinner. Unless there are more things that are different besides a lack of imports, that doesn't line up. Could it be this line: m_selectedCalendarId = m_calendars[(int)p_id].id; – Eric Levine Mar 09 '12 at 23:20
  • o! im really sorry your right i just edited some comments silly me. – user1248404 Mar 09 '12 at 23:23
  • I took a guess at which line it might be and added a possible solution to my answer above. – Eric Levine Mar 09 '12 at 23:24
  • is there anything for `setSelection(0)` to select? is it being populated properly by `populateCalendarSpinner()`? – Matt K Mar 09 '12 at 23:25
  • I believe it is being populated. elevine i did debug. – user1248404 Mar 09 '12 at 23:30
  • @user1248404 If you used the debugger, then you should be breaking on the line that causes the exception and be able to inspect the variables to see what is null and causing the problem.... – Eric Levine Mar 10 '12 at 00:21
0

Have you checked if m_calendars is being initialized correctly. Ensure that the l_arrayAdapter is not null.