Put a List<String> in a Bundle - android

I have an IntentService that goes connects to a website and creates a list with parsed HTML via JSoup. I now need to pass that list back in a Bundle and I'm not sure how to do it. Here is my code for the IntentService:
public class NewerService extends IntentService {
public NewerService() {
super("NewerService");
// TODO Auto-generated constructor stub
}
#Override
protected void onHandleIntent(Intent intent) {
ResultReceiver rec = intent.getParcelableExtra("receiverTag");
String playersName = intent.getStringExtra("Player");
List<String> list = new ArrayList<String>();
Document doc = null;
try {
doc = Jsoup.connect("http://espn.go.com/nhl/team/stats/_/name/phi/philadelphia-flyers").get();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
for (Element table : doc.select("table.tablehead")) {
for (Element row : table.select("tr")) {
Elements tds = row.select("td");
if (tds.size() > 6) {
String a = tds.get(0).text() + ":" + " Games Played: "+
tds.get(1).text()+"," + " GOALS: " + tds.get(2).text()+"," +
" ASSISTS: " + tds.get(3).text() + " POINTS: " +
tds.get(4).text() + " PLUS/MINUS: " + tds.get(5).text() + "
PIM: " + tds.get(6).text();
list.add(a); // Add the string to the list
}
}
}
}
I appreciate any help in advance. Thank you

Have you tried using Bundle.putStringArrayList or Intent.putStringArrayListExtra?
If you mean you don't know how to start an activity from a service, try this question.

Related

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

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

Definning a reference to method attribute for custom view

I want my custom view to have an attribute that can be set via XML that defines a callback for some custom behaviour that this view would support.
I know that i can tweak a simple string to be such using reflections, but it exists in the android API as Button has android:onClick so i wonder if this is something i can get out of the box instead of reinventing the wheel.
Anyone familiar with how it is done or do i must go ahead and implement it on my own using refelections?
seeing the android source code, looks as they did the same as i was going to :
case R.styleable.View_onClick:
if (context.isRestricted()) {
throw new IllegalStateException("The android:onClick attribute cannot "
+ "be used within a restricted context");
}
final String handlerName = a.getString(attr);
if (handlerName != null) {
setOnClickListener(new OnClickListener() {
private Method mHandler;
public void More ...onClick(View v) {
if (mHandler == null) {
try {
mHandler = getContext().getClass().getMethod(handlerName,
View.class);
} catch (NoSuchMethodException e) {
int id = getId();
String idText = id == NO_ID ? "" : " with id '"
+ getContext().getResources().getResourceEntryName(
id) + "'";
throw new IllegalStateException("Could not find a method " +
handlerName + "(View) in the activity "
+ getContext().getClass() + " for onClick handler"
+ " on view " + View.this.getClass() + idText, e);
}
}
try {
mHandler.invoke(getContext(), View.this);
} catch (IllegalAccessException e) {
throw new IllegalStateException("Could not execute non "
+ "public method of the activity", e);
} catch (InvocationTargetException e) {
throw new IllegalStateException("Could not execute "
+ "method of the activity", e);
}
}
});
}
So this i guess is the only way...

CookieManager not sending cookie after first and second request

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

Retrieve records from sqllite using Array list

I am retrieving all records from database and saving all records in array list.when i show array list records ,repeated data displayed,i don't know what's the prolblem??
Calling this function in view_record class:
public ArrayList<tuple> getdata() { // TODO Auto-generated method stub
tuple obj=new tuple();
Cursor c = ourDatabase.query(DATABASE_TABLE, PROJECTION_ALL, null, null, null, null, null);
if(c == null) {
return null;
}
ArrayList <tuple> data = new ArrayList<tuple>();
// String result = " ";
int i=0;
for(c.moveToFirst();!c.isAfterLast();c.moveToNext()){
obj.ROWID= c.getString(c.getColumnIndexOrThrow(KEY_ROWID));
obj.CNAME= c.getString(c.getColumnIndexOrThrow(KEY_CNAME));
obj.SNAME= c.getString(c.getColumnIndexOrThrow(KEY_SNAME));
obj.FAMILY= c.getString(c.getColumnIndexOrThrow(KEY_FAMILY));
obj.LOCATION= c.getString(c.getColumnIndexOrThrow(KEY_LOCATION));
obj.IMAGE1= c.getBlob(c.getColumnIndexOrThrow(KEY_IMAGE1));
obj.IMAGE2= c.getBlob(c.getColumnIndexOrThrow(KEY_IMAGE2));
obj.IMAGE3= c.getBlob(c.getColumnIndexOrThrow(KEY_IMAGE3));
data.add(i, obj);
i++;
}
c.close();
return data; }
My view_record class
public class view_record extends Activity {
#Override protected void onCreate(Bundle savedInstanceState) { // TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.db_view);
TextView tv=(TextView) findViewById(R.id.tvSqlinfo);
ImageView img=(ImageView) findViewById(R.id.img_view);
db_handler info=new db_handler(this);
info.open();
// Log.d("abc", "adb");
ArrayList <tuple> data=info.getdata();
Log.d("abc", "adb");
String result="";
for(int i=0;i<data.size();i++){
result +=" " + data.get(i).ROWID + " " + data.get(i).CNAME + " " + data.get(i).SNAME + " " + data.get(i).FAMILY + " " + data.get(i).LOCATION + "\n";
tv.setText(result);
img.setImageBitmap(Utilities.getImage(data.get(0).IMAGE2));
}
info.close(); } }
I want to view as follows :
" 1 cname sname family location "
" 2 cname sname family location "
But i am getting
" 2 cname sname family location "
" 2 cname sname family location "
Means last record displayed two times.
and one more thing ,i want to get all records where cname=something,getting error while doing it so
you are not making a new project in your for loop. That is whay you are getting same results. just do...
on start of for loop add this line obj=new tuple();
Answer to your Second Question
for(int i=0;i<data.size();i++){
result +=" " + data.get(i).ROWID + " " + data.get(i).CNAME + " " + data.get(i).SNAME + " " + data.get(i).FAMILY + " " + data.get(i).LOCATION + "\n";
img.setImageBitmap(Utilities.getImage(data.get(0).IMAGE2));
}
tv.setText(Html.fromHtml(result));

Categories

Resources