I want to remind the user when he selected some date. I found an example for a remainder here but I got a NullPointerException
.
package com.example.eventremainder;
import java.util.Calendar;
import com.example.eventremainder.R;
import com.example.eventremainder.Service.ScheduleClient;
import android.app.Activity;
import android.app.AlertDialog;
import android.content.ContentValues;
import android.content.DialogInterface;
import android.content.Intent;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.os.Bundle;
import android.provider.Contacts;
import android.provider.ContactsContract;
import android.text.Editable;
import android.text.TextWatcher;
import android.view.KeyEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemSelectedListener;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.DatePicker;
import android.widget.EditText;
import android.widget.Spinner;
import android.widget.TextView;
import android.widget.Toast;
public class AddEventActivity extends Activity{
private EditText nameEditText,phoneet;
TextView dobm;
private DatePicker datePicker;
private Button ok,browse;
private String checkedevent;
private Spinner spinner;
private ScheduleClient scheduleClient;
private static final String[] arrayString={"BirthDay","MarriageDay"};
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.selectevent);
nameEditText=(EditText)findViewById(R.id.editText1);
phoneet=(EditText)findViewById(R.id.phneno);
dobm=(TextView)findViewById(R.id.dobm);
datePicker=(DatePicker)findViewById(R.id.scheduleTimePicker);
spinner=(Spinner)findViewById(R.id.spinner1);
ok=(Button)findViewById(R.id.ok);
browse=(Button)findViewById(R.id.browse);
ok.setEnabled(false);
scheduleClient=new ScheduleClient(AddEventActivity.this);
scheduleClient.doBindService();
}
public void onResume()
{
super.onResume();
nameEditText.addTextChangedListener(tw);
dialogBox();
}
TextWatcher tw=new TextWatcher() {
public void onTextChanged(CharSequence arg0, int arg1, int arg2, int arg3) {
if(String.valueOf(arg0).equals(""))
{
ok.setEnabled(false);
}
else{
ok.setEnabled(true);
}
}
public void beforeTextChanged(CharSequence arg0, int arg1, int arg2,
int arg3) {
}
public void afterTextChanged(Editable arg0) {
if(!nameEditText.getText().toString().equals("")){
ok.setEnabled(true);
}
}
};
public void dialogBox()
{
ArrayAdapter<String > arrayAdapter=new ArrayAdapter<String>(AddEventActivity.this, android.R.layout.simple_dropdown_item_1line, arrayString);
spinner.setAdapter(arrayAdapter);
spinner.setOnItemSelectedListener(new OnItemSelectedListener() {
public void onItemSelected(AdapterView<?> arg0, View arg1,
int arg2, long arg3) {
checkedevent=arrayString[arg2];
}
public void onNothingSelected(AdapterView<?> arg0) {
}
});
browse.setClickable(true);
ok.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
SQLiteDatabase sqLiteDatabase=null;
sqLiteDatabase=openOrCreateDatabase("eventremainder", 0 ,null);
String checkedname="---";
String phone="--";
int day=0,month=0,year;
checkedname=nameEditText.getText().toString().trim();
day=datePicker.getDayOfMonth();
year=datePicker.getYear();
month=datePicker.getMonth();
String month2=month(month);
String date=""+day+"-"+(month2);
Calendar c=Calendar.getInstance();
c.set(year, month, day);
c.set(Calendar.HOUR_OF_DAY, 0);
c.set(Calendar.MINUTE, 0);
c.set(Calendar.SECOND, 0);
// Ask our service to set an alarm for that date, this activity talks to the client that talks to the service
scheduleClient.setAlarmForNotification(c);
try{
String selection="name=? and event=? and day=? and month=?";
String[] whereArgs1={checkedname,checkedevent,""+day,month2};
Cursor cursor=sqLiteDatabase.query("eventstable", null, selection, whereArgs1, null, null, null);
if(cursor.moveToNext())
{
throw new IndexOutOfBoundsException();
}
else
{
ContentValues cv=new ContentValues();
cv.put("name", checkedname);
cv.put("event", checkedevent);
cv.put("day",day);
cv.put("month", month2);
cv.put("monthint", month);
cv.put("year", year);
cv.put("phone_no",phone);
nameEditText.setText("");
phoneet.setText("");
long l=sqLiteDatabase.insert("eventstable", null, cv);
if(l!=-1l)
{
Toast.makeText(getApplicationContext(), checkedname + checkedevent + " Added " , Toast.LENGTH_LONG).show();
switchToTab(checkedevent);
}
}
}
catch (IndexOutOfBoundsException e) {
nameEditText.setError("These Details are already exists");
}
finally{
sqLiteDatabase.close();
}
}
});
}
public String month(int month)
{
String month1=null;
switch (month) {
case 0:month1="Jan";
break;
case 1:month1="Feb";
break;
case 2:month1="Mar";
break;
case 3:month1="Apr";
break;
case 4:month1="May";
break;
case 5:month1="Jun";
break;
case 6:month1="Jul";
break;
case 7:month1="Aug";
break;
case 8:month1="Sep";
break;
case 9:month1="Oct";
break;
case 10:month1="Nov";
break;
case 11:month1="Dec";
break;
}
return month1;
}
public void browsemethod(View arg0) {
Intent intent =new Intent(getApplicationContext(), ContactsListActivity.class);
startActivityForResult(intent, 1);
}
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if(resultCode==RESULT_OK && requestCode==1){
String name = data.getStringExtra("name");
String phone=data.getStringExtra("phonenumber");
tw.onTextChanged(name, 5, 5, 5);
nameEditText.setText(name);
phoneet.setText(phone);
}
}
public boolean onKeyDown(int keyCode,KeyEvent event)
{
super.onKeyDown(keyCode, event);
switch (keyCode) {
case KeyEvent.KEYCODE_BACK:
AlertDialog.Builder alertdialogbuilder=new AlertDialog.Builder(AddEventActivity.this);
alertdialogbuilder.setTitle("Do you want to exist from application");
alertdialogbuilder.setPositiveButton("yes", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
finish();
}
});
alertdialogbuilder.setNegativeButton("No", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
}
});
alertdialogbuilder.create();
alertdialogbuilder.show();
return true;
default:
break;
}
return false;
}
public void switchToTab(String tab)
{
TabMainActivity tabMainActivity=(TabMainActivity) this.getParent();
if(tab.equalsIgnoreCase("BirthDay"))
{
tabMainActivity.switchTab(0);
}
else {
if(tab.equalsIgnoreCase("MarriageDay"))
{
tabMainActivity.switchTab(1);
}
}
}
}
</b>
another class i ussed is scheduleclient
<b>
package com.example.eventremainder.Service;
import java.util.Calendar;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.ServiceConnection;
import android.os.IBinder;
/**
* This is our service client, it is the 'middle-man' between the
* service and any activity that wants to connect to the service
*
* @author paul.blundell
*/
public class ScheduleClient {
// The hook into our service
private ScheduleService mBoundService;
// The context to start the service in
private Context mContext;
// A flag if we are connected to the service or not
private boolean mIsBound;
public ScheduleClient(Context context) {
mContext = context;
}
/**
* Call this to connect your activity to your service
*/
public void doBindService() {
// Establish a connection with our service
mContext.bindService(new Intent(mContext, ScheduleService.class), mConnection, Context.BIND_AUTO_CREATE);
mIsBound = true;
}
/**
* When you attempt to connect to the service, this connection will be called with the result.
* If we have successfully connected we instantiate our service object so that we can call methods on it.
*/
private ServiceConnection mConnection = new ServiceConnection() {
public void onServiceConnected(ComponentName className, IBinder service) {
// This is called when the connection with our service has been established,
// giving us the service object we can use to interact with our service.
mBoundService = ((ScheduleService.ServiceBinder) service).getService();
}
public void onServiceDisconnected(ComponentName className) {
mBoundService = null;
}
};
/**
* Tell our service to set an alarm for the given date
* @param c a date to set the notification for
*/
public void setAlarmForNotification(Calendar c){
mBoundService.setAlarm(c);
}
/**
* When you have finished with the service call this method to stop it
* releasing your connection and resources
*/
public void doUnbindService() {
if (mIsBound) {
// Detach our existing connection.
mContext.unbindService(mConnection);
mIsBound = false;
}
}
}
It was showing null pointer exception at mBoundService.setAlarm(c)
.
Looks like the service was not bound successfully. The connection doesn't return immediately, but since you call this in an event handler this is most likely not the issue. Did you register the service correctly? Try to put some debug statements/breakpoints in the onServiceConnected() method to verify it is actually called/when it is called.
I was also facing same problem.. I had called it in onCreate method for some reason..but when I called it from other events then its works fine.. I know, I am late but this can be a solution that can help others
来源:https://stackoverflow.com/questions/13379580/java-lang-nullpointerexception-showing-at-mboundservice-setalarmc