CookieManager not sending cookie after first and second request - android

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

Related

How to get data from key of a JSON [duplicate]

This question already has answers here:
How to iterate over a JSONObject?
(15 answers)
Closed 5 years ago.
I am creating an app in which i need to parse a list of contacts which is in JSONObject format, with key before each object, i don't know how to parse this format.
{
"1": {
"mobileContact": "98562325",
"systemContact": "9198562325"
},
"3": {
"mobileContact": "987563656",
"systemContact": "91987563656"
},
"4": {
"mobileContact": "965632525",
"systemContact": "91965632525"
},
"6": {
"mobileContact": "965436222",
"systemContact": "91965436222"
}
}
Use the keys() iterator to iterate over all the properties, and call get() for each.
Iterator<String> iter = json.keys();
while (iter.hasNext()) {
String key = iter.next();
try {
Object value = json.get(key);
} catch (JSONException e) {
// Something went wrong!
}
}
try{
JSONObject json = new JSONObject(jsonRespondeString);
Iterator<String> iterator = json.keys();
while (iterator.hasNext()){
String key = iterator.next();
JSONObject object = json.getJSONObject(key);
String value1 = object.getString("key1");
String value2 = object.getString("key2");
}
}
catch (JSONException e){
e.printStackTrace();
}
please try this it helps
You can use GSON library to parse it.
String data = "{\n" +
" \"1\": {\n" +
" \"mobileContact\": \"98562325\",\n" +
" \"systemContact\": \"9198562325\"\n" +
" },\n" +
" \"3\": {\n" +
" \"mobileContact\": \"987563656\",\n" +
" \"systemContact\": \"91987563656\"\n" +
" },\n" +
" \"4\": {\n" +
" \"mobileContact\": \"965632525\",\n" +
" \"systemContact\": \"91965632525\"\n" +
" },\n" +
" \"6\": {\n" +
" \"mobileContact\": \"965436222\",\n" +
" \"systemContact\": \"91965436222\"\n" +
" }\n" +
"}";
Map<String, Item> itemMap = new HashMap<>();
itemMap = new Gson().fromJson(data, itemMap.getClass());
Log.i("data", itemMap);
Item Class
private class Item {
String mobileContact;
String systemContact;
// getters and setters
public String getMobileContact() {
return mobileContact;
}
public void setMobileContact(String mobileContact) {
this.mobileContact = mobileContact;
}
public String getSystemContact() {
return systemContact;
}
public void setSystemContact(String systemContact) {
this.systemContact = systemContact;
}
}
You need to add the following to the build.gradle file,
compile 'com.google.code.gson:gson:2.8.0'

OrmSqlite automap Results

I am using OrmSqlite database, want to auto map the results in GenericRawResults rawResults
String querString = "select * from ZADDRISKDETAILS where ZRISK_DEFINED_STATUS='" + status + "' AND ZPROJECTID ='" + projectID + "' AND ZRESPECTIVE_USERID ='" + userID + "' AND ZRISKDATETIME like '" + selectedYear + "%' ";
GenericRawResults<String[]> rawResults = mDBHelper.getRecommendationPinDetailsDao().queryRaw(querString);
List<String[]> results = rawResults.getResults();
for (int i = 0; i < results.size(); i++) {
ListModel model = new ListModel();
model.setDueDate(results.get(i)[2]);
model.setRiskCategory(results.get(i)[8]);
model.setRiskObservation(results.get(i)[14]);
model.setStatus(results.get(i)[11]);
model.setPriority(results.get(i)[19]);
model.setRiskRecommendation(results.get(i)[21]);
model.setIssuedDate(results.get(i)[10]);
}
I want to map those results directly to map model class obj. (Eg. ListModel.class) without giving the index. I think RawRowMapper does this, but no idea.
Use Dio to map model class,
private Dao<News, Integer> newsDao = null;
public Dao<News, Integer> getNewsDao() {
if (null == this.newsDao) {
try {
this.newsDao = getDao(News.class);
} catch (java.sql.SQLException e) {
e.printStackTrace();
}
}
return this.newsDao;
}
public List<News> getAllNews() {
List<News> news = null;
try {
news = getHelper().getNewsDao().queryForAll();
} catch (SQLException e) {
e.printStackTrace();
}
return news;
}
It may help you..

how should i make JSONObject and JSONArray from json url or json

My JSON:
{
"response_code": 200,
"error": false,
"train_name": "KCG YPR EXP",
"train_num": "17603",
"pnr": "1234567890",
"failure_rate": 19.346153846153847,
"doj": "20-8-2015",
"chart_prepared": "Y",
"class": "SL",
"total_passengers": 2,
"train_start_date": {
"month": 8,
"year": 2015,
"day": 20
},
"from_station": {
"code": "KCG",
"name": "KACHEGUDA"
},
"boarding_point": {
"code": "KCG",
"name": "KACHEGUDA"
},
"to_station": {
"code": "YPR",
"name": "YESVANTPUR JN"
},
"reservation_upto": {
"code": "YPR",
"name": "YESVANTPUR JN"
},
"passengers": [
{
"no": 1,
"booking_status": "S7,58,GN",
"current_status": "S7,58",
"coach_position": 9
},
{
"no": 2,
"booking_status": "S7,59,GN",
"current_status": "S7,59",
"coach_position": 9
}
]
}
What I did so far:
if(jsonStr!=null)
{
try
{
JSONObject object=new JSONObject(jsonStr);
JSONArray jsonArray=object.getJSONArray("passengers");
for (int i=0;i<=jsonArray.length();i++)
{
JSONObject o=jsonArray.getJSONObject(i);
int no= Integer.parseInt(o.optString("no").toString());
String booking_status=o.getString("Booking Status");
String current_status=o.getString("Current Status");
String coach_position=o.getString("Coach Position");
JSONObject data=o.getJSONObject("details");
String train_name = data.getString("Train Name");
int train_num = Integer.parseInt(data.optString("train number").toString());
int pnr = Integer.parseInt(data.optString("pnr").toString());
String chart_prepared = data.getString("Chart Prepared");
int total_passengers=Integer.parseInt(data.optString("total passengers").toString());
JSONObject date=data.getJSONObject("tarin_start_date");
int month=Integer.parseInt(data.optString("month").toString());
int year=Integer.parseInt(data.optString("year").toString());
int day=Integer.parseInt(data.optString("day").toString());
JSONObject co=date.getJSONObject("from_station");
String code=co.getString("code");
String name=co.getString("name");
JSONObject co1=co.getJSONObject("boarding_point");
String code1=co1.getString("code");
String name1=co1.getString("name");
JSONObject co2=co1.getJSONObject("to_station");
String code2=co2.getString("code");
String name2=co2.getString("name");
JSONObject co3=co2.getJSONObject("from_station");
String code3=co3.getString("code");
String name3=co3.getString("name");
HashMap<String,String> dtail=new HashMap<>();
dtail.put("no", String.valueOf(no));
dtail.put("Booking Staus",booking_status);
dtail.put("Current Staus",current_status);
dtail.put("Coach Positon",coach_position);
dtail.put("Train Name",train_name);
dtail.put("Train Number", String.valueOf(train_num));
dtail.put("pnr", String.valueOf(pnr));
dtail.put("chart prepared",chart_prepared);
dtail.put("total passengers", String.valueOf(total_passengers));
dtail.put("month", String.valueOf(month));
dtail.put("year", String.valueOf(year));
dtail.put("day", String.valueOf(day));
dtail.put("code",code);
dtail.put("name",name);
dtail.put("code",code1);
dtail.put("name",name1);
dtail.put("code",code2);
dtail.put("name",name2);
dtail.put("code",code3);
dtail.put("name",name3);
dataList.add(dtail);
}
}
catch (final JSONException e) {
Log.e(TAG, "Json parsing error: " + e.getMessage());
runOnUiThread(new Runnable() {
#Override
public void run() {
Toast.makeText(getApplicationContext(),
"Json parsing error: " + e.getMessage(),
Toast.LENGTH_LONG).show();
}
});
}
}
else
{
Log.e(TAG, "Couldn't get json from server.");
runOnUiThread(new Runnable() {
#Override
public void run() {
Toast.makeText(getApplicationContext(),
"Couldn't get json from server. Check LogCat for possible errors!",
Toast.LENGTH_LONG).show();
}
});
}
return null;
}
Here is your solution.
Hope this will help you. Whenever you work with JSON check all key name. It should always same as response key name
if (jsonStr != null) {
try {
JSONObject object = new JSONObject(jsonStr);
HashMap<String, String> dtail = new HashMap<>();
JSONArray jsonArray = object.getJSONArray("passengers");
for (int i = 0; i < jsonArray.length(); i++) {
JSONObject o = jsonArray.getJSONObject(i);
int no = Integer.parseInt(o.optString("no").toString());
String booking_status = o.getString("booking_status");
String current_status = o.getString("current_status");
String coach_position = o.getString("coach_position");
dtail.put("no", String.valueOf(no));
dtail.put("Booking Staus", booking_status);
dtail.put("Current Staus", current_status);
dtail.put("Coach Positon", coach_position);
}
String train_name = object.getString("train_name");
int train_num = Integer.parseInt(object.optString("train_num").toString());
int pnr = Integer.parseInt(object.optString("pnr").toString());
String chart_prepared = object.getString("chart_prepared");
int total_passengers = Integer.parseInt(object.optString("total_passengers").toString());
JSONObject date = object.getJSONObject("train_start_date");
int month = Integer.parseInt(date.optString("month").toString());
int year = Integer.parseInt(date.optString("year").toString());
int day = Integer.parseInt(date.optString("day").toString());
JSONObject co = object.getJSONObject("from_station");
String code = co.getString("code");
String name = co.getString("name");
JSONObject co1 = object.getJSONObject("boarding_point");
String code1 = co1.getString("code");
String name1 = co1.getString("name");
JSONObject co2 = object.getJSONObject("to_station");
String code2 = co2.getString("code");
String name2 = co2.getString("name");
JSONObject co3 = object.getJSONObject("reservation_upto");
String code3 = co3.getString("code");
String name3 = co3.getString("name");
dtail.put("Train Name", train_name);
dtail.put("Train Number", String.valueOf(train_num));
dtail.put("pnr", String.valueOf(pnr));
dtail.put("chart prepared", chart_prepared);
dtail.put("total passengers", String.valueOf(total_passengers));
dtail.put("month", String.valueOf(month));
dtail.put("year", String.valueOf(year));
dtail.put("day", String.valueOf(day));
dtail.put("code", code);
dtail.put("name", name);
dtail.put("code", code1);
dtail.put("name", name1);
dtail.put("code", code2);
dtail.put("name", name2);
dtail.put("code", code3);
dtail.put("name", name3);
dataList.add(dtail);
} catch (final JSONException e) {
Log.e("Json", "Json parsing error: " + e.getMessage());
runOnUiThread(new Runnable() {
#Override
public void run() {
Toast.makeText(getApplicationContext(),
"Json parsing error: " + e.getMessage(),
Toast.LENGTH_LONG).show();
}
});
}
Hope this will help :-
#Override
protected void onCreate(#Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.dummy);
String str = "{\n" +
" \"response_code\": 200,\n" +
" \"error\": false,\n" +
" \"train_name\": \"KCG YPR EXP\",\n" +
" \"train_num\": \"17603\",\n" +
" \"pnr\": \"1234567890\",\n" +
" \"failure_rate\": 19.346153846153847,\n" +
" \"doj\": \"20-8-2015\",\n" +
" \"chart_prepared\": \"Y\",\n" +
" \"class\": \"SL\",\n" +
" \"total_passengers\": 2,\n" +
" \"train_start_date\": {\n" +
" \"month\": 8,\n" +
" \"year\": 2015,\n" +
" \"day\": 20\n" +
" },\n" +
" \"from_station\": {\n" +
" \"code\": \"KCG\",\n" +
" \"name\": \"KACHEGUDA\"\n" +
" },\n" +
" \"boarding_point\": {\n" +
" \"code\": \"KCG\",\n" +
" \"name\": \"KACHEGUDA\"\n" +
" },\n" +
" \"to_station\": {\n" +
" \"code\": \"YPR\",\n" +
" \"name\": \"YESVANTPUR JN\"\n" +
" },\n" +
" \"reservation_upto\": {\n" +
" \"code\": \"YPR\",\n" +
" \"name\": \"YESVANTPUR JN\"\n" +
" },\n" +
" \"passengers\": [\n" +
" {\n" +
" \"no\": 1,\n" +
" \"booking_status\": \"S7,58,GN\",\n" +
" \"current_status\": \"S7,58\",\n" +
" \"coach_position\": 9\n" +
" },\n" +
" {\n" +
" \"no\": 2,\n" +
" \"booking_status\": \"S7,59,GN\",\n" +
" \"current_status\": \"S7,59\",\n" +
" \"coach_position\": 9\n" +
" }\n" +
" ]\n" +
"}";
parseJson(str);
}
private void parseJson(String jsonStr) {
HashMap<String, String> dtail = new HashMap<>();
if (jsonStr != null) {
try {
JSONObject object = new JSONObject(jsonStr);
int responseCode = object.getInt("response_code");
boolean error = object.getBoolean("error");
String train_name = object.getString("train_name");
int train_num = object.getInt("train_num");
int pnr = object.getInt("pnr");
double failurerate = object.getDouble("failure_rate");
String dateofJoin = object.getString("doj");
String chart = object.getString("chart_prepared");
String Class = object.getString("class");
int total_passengers = object.getInt("total_passengers");
JSONObject date = object.getJSONObject("train_start_date");
int month = date.getInt("month");
int year = date.getInt("year");
int day = date.getInt("day");
JSONObject co = object.getJSONObject("from_station");
String code = co.getString("code");
String name = co.getString("name");
JSONObject co1 = object.getJSONObject("boarding_point");
String code1 = co1.getString("code");
String name1 = co1.getString("name");
JSONObject co2 = object.getJSONObject("to_station");
String code2 = co2.getString("code");
String name2 = co2.getString("name");
JSONObject co3 = object.getJSONObject("from_station");
String code3 = co3.getString("code");
String name3 = co3.getString("name");
JSONArray jsonArray = object.getJSONArray("passengers");
for (int i = 0; i < jsonArray.length(); i++) {
JSONObject jsonObject = jsonArray.getJSONObject(i);
int no = jsonObject.getInt("no");
String booking_status = jsonObject.getString("booking_status");
String current_status = jsonObject.getString("current_status");
int coach_position = jsonObject.getInt("coach_position");
dtail.put("no", String.valueOf(no));
dtail.put("booking_status", booking_status);
dtail.put("current_status", current_status);
dtail.put("coach_position", String.valueOf(coach_position));
}
dtail.put("responseCode", String.valueOf(responseCode));
dtail.put("error", "" + error);
dtail.put("Train Name", train_name);
dtail.put("dateofJoin", dateofJoin);
dtail.put("chart", chart);
dtail.put("Class", Class);
dtail.put("Train Number", String.valueOf(train_num));
dtail.put("pnr", String.valueOf(pnr));
dtail.put("FAILURE_RATE", String.valueOf(failurerate));
dtail.put("total passengers", String.valueOf(total_passengers));
dtail.put("month", String.valueOf(month));
dtail.put("year", String.valueOf(year));
dtail.put("day", String.valueOf(day));
dtail.put("code", code);
dtail.put("name", name);
dtail.put("code", code1);
dtail.put("name", name1);
dtail.put("code", code2);
dtail.put("name", name2);
dtail.put("code", code3);
dtail.put("name", name3);
Log.e("Result------", "" + dtail);
} catch (final JSONException e) {
Log.e("tag", "Json parsing error: " + e.getMessage());
runOnUiThread(new Runnable() {
#Override
public void run() {
Toast.makeText(getApplicationContext(),
"Json parsing error: " + e.getMessage(),
Toast.LENGTH_LONG).show();
}
});
}
}
}

stopSerivce gives null object reference

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).

Add validation so that EditText fields cannot be null

So I'm trying to add validation onto my btnSubmit which will check that all editText fields have some sort of data in before storing into the array. Would anyone be able to help?
if (btnSubmit == null) throw new AssertionError();
btnSubmit.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
if(editMod.getText().length()==0){
editMod.setError("Please fill in all fields");
}
else if(editRoom.getText().length()==0){
editRoom.setError("Please fill in all fields");
}
if (editMod.getText() != null) {
strModule = editMod.getText().toString();
}
if (editRoom.getText() != null) {
strRoomInfo = editMod.getText().toString();
}
inputData = strDay + " " + strTime + " " + strDuration + " " + strType + " " + strModule + " " + strRoomInfo;
parent.addItem(inputData);
try {
writeFile();
} catch (Exception e) {
Log.e("Writing to file Failed.", " ");
}
}
});
}
What's editMod here? EditText or TextInputLayout?
For this current code, here is the updated version:
if (btnSubmit == null) throw new AssertionError();
btnSubmit.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
if(editMod.getText().toString().isEmpty()){
editMod.setError("Please fill in all fields");
}
else if(editRoom.getText().toString().isEmpty()){
editRoom.setError("Please fill in all fields");
}
if (editMod.getText().toString() != null) {
strModule = editMod.getText().toString();
}
if (editRoom.getText().toString() != null) {
strRoomInfo = editMod.getText().toString();
}
inputData = strDay + " " + strTime + " " + strDuration + " " + strType + " " + strModule + " " + strRoomInfo;
parent.addItem(inputData);
try {
writeFile();
} catch (Exception e) {
Log.e("Writing to file Failed.", " ");
}
}
});
}
Update your question and add xml code plus the rest of Java Code.
Try this code:
if (TextUtils.isEmtpy(<Your EditText here>.getText().toString())) {
//Empty
}

Categories

Resources