AsyncTask: onPostExecute is not being invoked - android

I am trying to get the onPostExecute() method invoked after finishing the doInBackground() method and then passed the custom arrayList<ItemDTO> to the Map activity but onPostExecute method is not being invoked. I am not getting any Output in the Logcat as asign that it was invoked. How can I fix it?
I have debugged it and I can see the data in the ArrayList data object.
I appreciate any help.
GetLLRD class
public class GetLLRD {
Context mContext;
public void post_selected(String json, Context context) {
new MyAsyncTask().execute(json);
context = this.mContext;
}
class MyAsyncTask extends AsyncTask<String, Integer, List<ItemDTO>> {
#Override
protected List<ItemDTO> doInBackground(String... params) {
.
.
.
.
Gson gson = new Gson();
Type listType = new TypeToken<List<ItemDTO>>() {
}.getType();
ArrayList<ItemDTO> data = gson.fromJson(sb.toString(), listType);
.
.
.
.
return data;
}
protected void onPostExecute(ArrayList<ItemDTO> result) {
new Handler().postDelayed(new Runnable() {
#Override
public void run() {
new MyAsyncTask().execute();
System.out.println("The method onPostExcute() in GETLLRD class was invoked again");
}
}, 1*30 * 1000);
if (result != null) {
Intent intent = new Intent(mContext, Map.class);
intent.putExtra("list",result);
mContext.startActivity(intent);
}else{
Log.e("123", "Avoiding null pointer, the dat is null in the GETLLRD class!!!");
}
}
}
}
MapDataJSON class with the inner class ItemDTo which I need to get the data from the JSON string that I am getting from the Server.
public class MapDataJSON {
ArrayList<ItemDTO> items;
public MapDataJSON(ArrayList<ItemDTO> items) {
super();
this.items = items;
}
public ArrayList<ItemDTO> getItems() {
return items;
}
public void setItems(ArrayList<ItemDTO> items) {
this.items = items;
}
public static class ItemDTO implements Serializable {
private static final long serialVersionUID = 1L;
double latitude;
double longitude;
int route;
String direction;
public ItemDTO(double latitude, double longitude, int route,
String direction) {
super();
this.latitude = latitude;
this.longitude = longitude;
this.route = route;
this.direction = direction;
}
public double getLatitude() {
return latitude;
}
public double getLongitude() {
return longitude;
}
public int getRoute() {
return route;
}
public String getDirection() {
return direction;
}
public void setLatitude(double latitude) {
this.latitude = latitude;
}
public void setLongitude(double longitude) {
this.longitude = longitude;
}
public void setRoute(int route) {
this.route = route;
}
public void setDirection(String direction) {
this.direction = direction;
}
}
}

Your not actually overriding the correct method signature of AsyncTask
it should be
protected void onPostExecute(List<ItemDTO> result)
by specifying ArrayList you're changing the method signature. This is why it's useful to use the Override annotation as your ide or compiler will tell you the method signature doesn't match.

Related

how can I save ArrayList <LatLng>savedPath in RealmObject

I tried to save this object using Realm But I got this error
Error:(24, 9) error: Type
java.util.ArrayList of field
savedPath is not supported
Here is my code :
public class TrackingInfo extends RealmObject {
private int order_id;
private double savedDistance;
private double savedDuration;
private ArrayList <LatLng>savedPath;
public int getOrder_id() {
return order_id;
}
public void setOrder_id(int order_id) {
this.order_id = order_id;
}
public double getSavedDistance() {
return savedDistance;
}
public void setSavedDistance(double savedDistance) {
this.savedDistance = savedDistance;
}
public double getSavedDuration() {
return savedDuration;
}
public void setSavedDuration(double savedDuration) {
this.savedDuration = savedDuration;
}
public ArrayList<LatLng> getSavedPath() {
return savedPath;
}
public void setSavedPath(ArrayList<LatLng> savedPath) {
this.savedPath = savedPath;
}
public TrackingInfo(){}}
Thanx in advance
Both List and LatLng cannot be stored in Realm directly. You will need to create a model object for LatLng and then use a RealmList object containing your model objects.
public class Location extends RealmObject {
public Location() { }
double latitude;
double longitude;
}
RealmList<Location> savedPath = new RealmList<Location>();
//Add location objects to savedPath and store it in your TrackingInfo object
You will need to manually convert objects of the LatLng class to the Location class when you are inserting/retrieving from the database.

Pass LinkedList to another activity

I have a Linked List in one activity (A) that I want to share with another Activity (B).
The list contains a username of type string and contains coordinates of type LatLng. I am also using Intent and bundle to share data between activities. I tried using Parcelable but unable to figure out how to use it. Here is the code I have:
data.java
public class data implements Parcelable{
private LatLng coordinates;
private String name;
public data() {
name = null;
coordinates = null;
}
public data(String name, LatLng coordinates)
{
this.name = name;
this.coordinates = coordinates;
}
public data(Parcel in) {
coordinates = in.readParcelable(LatLng.class.getClassLoader());
name = in.readString();
}
public static final Creator<data> CREATOR = new Creator<data>() {
#Override
public data createFromParcel(Parcel in) {
return new data(in);
}
#Override
public data[] newArray(int size) {
return new data[size];
}
};
public LatLng getLatLng () {
return coordinates;
}
#Override
public int describeContents() {
return hashCode();
}
#Override
public void writeToParcel(Parcel dest, int flags) {
dest.writeString(name);
dest.writeParcelable(coordinates, flags);
}
}
Activity A
public class A extends FragmentActivity implements
OnMapReadyCallback,
GoogleApiClient.ConnectionCallbacks,
GoogleApiClient.OnConnectionFailedListener,
GoogleMap.OnMyLocationButtonClickListener,
ActivityCompat.OnRequestPermissionsResultCallback {
Button switchToSeek;
double mLatitude;
double mLongitude;
LinkedList<data> storedData = new LinkedList<>();
protected void onCreate(Bundle savedInstanceState) {
...
switchToSeek.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
getCurrentLocation();
Intent intent = new Intent(A.this, B.class);
Bundle xy = new Bundle();
xy.putDouble("x", mLatitude);
xy.putDouble("y", mLongitude);
xy.putParcelable("list", storedData); <---------- error: wrong second arugment
intent.putExtra("xy", xy);
A.this.startActivity(intent);
}
});
Activity B
public class B extends FragmentActivity implements OnMapReadyCallback {
double mLatitude;
double mLongitude;
LatLng current;
GoogleMap gMap;
LinkedList <data> copyData = new LinkedList<>();
#Override
public void onMapReady(GoogleMap googleMap) {
gMap = googleMap;
...
Intent intent = getIntent();
Bundle xy = intent.getBundleExtra("xy");
if (xy != null) {
mLatitude = xy.getDouble("x");
mLongitude = xy.getDouble("y");
}
/***** Call linked list here and set equal to copyData *****/
current = new LatLng(mLatitude, mLongitude);
gMap.moveCamera(CameraUpdateFactory.newLatLngZoom(current, 18.0f));
}
There is no easy way to do that, since LinkedList does not implement serializable or parcelable.
You CAN implement your own linked list class and make it a serializable/parcelable object which can then be passed.
Or you can convert its content into another data type such as an array and then recreate the linkedlist.* THIS IS HIGHLY INEFFICIENT
I believe there are other ways but this is a standard problem in android dev. Maybe try using fragments if possible and passing the linkedlist through a setter()
If the list is not huge, you can do it using the following helper class:
public class ParcelableLinkedList<E extends Parcelable> implements Parcelable {
private final LinkedList<E> linkedList;
public final Creator<ParcelableLinkedList> CREATOR = new Creator<ParcelableLinkedList>() {
#Override
public ParcelableLinkedList createFromParcel(Parcel in) {
return new ParcelableLinkedList(in);
}
#Override
public ParcelableLinkedList[] newArray(int size) {
return new ParcelableLinkedList[size];
}
};
public ParcelableLinkedList(Parcel in) {
// Read size of list
int size = in.readInt();
// Read the list
linkedList = new LinkedList<E>();
for (int i = 0; i < size; i++) {
linkedList.add((E)in.readParcelable(ParcelableLinkedList.class.getClassLoader()));
}
}
public ParcelableLinkedList(LinkedList<E> linkedList) {
this.linkedList = linkedList;
}
LinkedList<E> getLinkedList() {
return linkedList;
}
#Override
public int describeContents() {
return 0;
}
#Override
public void writeToParcel(Parcel parcel, int flags) {
// Write size of the list
parcel.writeInt(linkedList.size());
// Write the list
for (E entry : linkedList) {
parcel.writeParcelable(entry, flags);
}
}
}
In your onClick() method, add the data to the Bundle like this:
xy.putParcelable("list", new ParcelableLinkedList<data>(storedData));
To extract the data from the Bundle, do this:
copyData = ((ParcelableLinkedList<data>)xy.getParcelable("list")).getLinkedList();
I haven't actually compiled and tested this code, but it should work.
If the list is really huge, you are better off storing it in a static member variable in one class and then just referencing it from the other. This isn't normally the way you want to do things in Android, but it is sometimes more expedient to do this than to serialize and deserialize a huge amount of data just to pass it between 2 activities that have access to the same memory space.

android- putParcelableArrayList in CountDownTimer put same value on List returned

I try to get val from AudioRecord in a countDown but when I get the list extra in the Activity, contains same value (I have already checked that AudioRecord returns me differents values). Please help me!. Thanks in advance.
Note: I call the countDown passing it 45 * 1000 and 100
// Class of CountDownTimer
dataValues = new ArrayList<Data>();
(MenuActivity)context).runOnUiThread(new Runnable() {
#Override
public void run() {
new CountDownTimer(millis, intervalInMillis){
#Override
public void onTick(long millisUntilFinished) {
firstValues.add(val); // val from AudioRecord
if (firstValues.size() >=10){
firstValues.remove(0);
data.setValue(avgFromIntList(firstValues));
data.setTime(new Date().getTime());
dataValues.add(data);
}
}
#Override
public void onFinish() {
Bundle extras = new Bundle();
extras.putLong("idSession", session.getId());
extras.putParcelableArrayList("values",dataValues);
Intent toPast = new Intent(context, SessionPastActivity.class);
toPast.putExtras(extras);
context.startActivity(toPast);
}
}.start();
}
});
// Model class that implement Parcelable
public class Data implements Parcelable {
private Integer value;
private Long time;
public Data(Integer value, Long time) {
this.value = value;
this.time = time;
}
public Data() {
}
public Integer getValue() {
return value;
}
public void setValue(Integer value) {
this.value = value;
}
public Long getTime() {
return time;
}
public void setTime(Long time) {
this.time = time;
}
#Override
public String toString() {
return "Data{" +
", value=" + value +
", time=" + time +
'}';
}
#Override
public int describeContents() {
return 0;
}
#Override
public void writeToParcel(Parcel dest, int flags) {
dest.writeInt(value);
dest.writeLong(time);
Log.e("inWrite", toString());
}
// this is used to regenerate your object. All Parcelables must have a CREATOR that implements these two methods
public static final Parcelable.Creator<Data> CREATOR = new Parcelable.Creator<Data>() {
public Data createFromParcel(Parcel in) {
return new Data(in);
}
public Data[] newArray(int size) {
return new Data[size];
}
};
// example constructor that takes a Parcel and gives you an object populated with it's values
private Data(Parcel in) {
value = in.readInt();
time = in.readLong();
Log.e("inREAD", toString());
}
// Activity class
ArrayList values_amplitude = getIntent().getExtras().getParcelableArrayList("values");
try this
Bundle bundle=getIntent.getExtra();
if(bundle != null){
ArrayList<Data> values_amplitude = (ArrayList<Data>).getParcelable("values");
} else {}
Hope it will work for you

Android - Saving custom object - Shared Preferences or Database?

I'm creating a location based reminder application.
I've got a custom object called Reminder, which stores latitude, longitude, the location name and the subject of the reminder - Aswell as what profile it belongs to.
I'm then inputting the location name and sujbect into a ListView (Using cardlibs here too).
However now I need to save the data for when I close the application, and was wondering the best way to go about this - Do I store the entire 'Reminder' object or do I just store multiple pieces of data in Shared Preferences / A database.
This is my code - It's very inefficient/Ugly:
Reminder:
public class Reminder implements Parcelable {
public double latitude;
public double longitude;
public String subject;
public String locationName;
public String profile;
public Reminder() {
}
public Reminder(Parcel in) {
String[] data = new String[5];
in.readStringArray(data);
this.subject = data[0];
this.locationName = data[1];
this.latitude = Double.parseDouble(data[2]);
this.longitude = Double.parseDouble(data[3]);
this.profile = data[4];
}
public String getProfile() {
return profile;
}
public double getLatitude() {
return latitude;
}
public String getLocationName() {
return locationName;
}
public double getLongitude() {
return longitude;
}
public String getSubject() {
return subject;
}
public void setProfile(String profile) {
this.profile = profile;
}
public void setLatitude(double latitude) {
this.latitude = latitude;
}
public void setLocationName(String locationName) {
this.locationName = locationName;
}
public void setLongitude(double longitude) {
this.longitude = longitude;
}
public void setSubject(String subject) {
this.subject = subject;
}
#Override
public int describeContents() {
return 0;
}
#Override
public void writeToParcel(Parcel dest, int flags) {
dest.writeStringArray(new String[] { this.subject, this.locationName,
String.valueOf(this.latitude), String.valueOf(this.longitude), this.profile });
}
public static final Parcelable.Creator<Reminder> CREATOR = new Parcelable.Creator<Reminder>() {
public Reminder createFromParcel(Parcel source) {
// TODO Auto-generated method stub
return new Reminder(source); // using parcelable constructor
}
public Reminder[] newArray(int size) {
// TODO Auto-generated method stub
return new Reminder[size];
}
};
}
List using a fragment:
public class HomeFragment extends Fragment {
public static ArrayList<Card> cards = new ArrayList<Card>();
Reminder reminder;
public HomeFragment() {
}
#Override
public void onActivityCreated(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onActivityCreated(savedInstanceState);
reminder = getActivity().getIntent().getParcelableExtra("reminder");
Card card = new Card(getActivity());
CardHeader cardHeader = new CardHeader(getActivity());
if (reminder != null) {
cardHeader.setTitle(reminder.getSubject());
card.addCardHeader(cardHeader);
card.setTitle(reminder.getLocationName());
cards.add(card);
}
CardArrayAdapter mCardArrayAdapter = new CardArrayAdapter(
getActivity(), cards);
CardListView listView = (CardListView) getActivity().findViewById(
R.id.card_list);
mCardArrayAdapter.notifyDataSetChanged();
if (listView != null)
listView.setAdapter(mCardArrayAdapter);
}
Any criticism on how my code could of been wrote better would also be really beneficial, as I feel I'm being a huge rookie and missing something obvious which would make it more efficient.
Thanks!
Basically the choice to use shared preferences vs a database hinges on a number of things:
1) How many objects are we talking about? How complex are they?
2) Do you intend on searching/manipulating these objects or are you just saving/loading them.
3) Do you intend to export/move/send objects?
4) Do you want the objects to be recoverable across application contexts - that is beyond only the single app in question.
In your specific case I would use a database.
http://developer.android.com/guide/topics/data/data-storage.html#pref
As you can see in the docs here prefs isn't really intended for Object storage - it's for key value pairs. While you could store an object as a number of key value pairs in the shared prefs and reconstruct from there, you would have to go through some weird model conversions to do this for multiple objects. In short it doesn't really make sense.

How to extend LatLng

I wrote a code to draw a path from gpx file. If the user turns the smartphone, the path is cleared, then I created a ArrayList<MyLatLng> where every MyLatLng object is:
public class MyLatLng implements Parcelable {
private double latitude;
private double longitude;
public MyLatLng(double lat, double lon) {
latitude = lat;
longitude = lon;
}
#Override
public int describeContents() {
return 0;
}
#Override
public void writeToParcel(Parcel parcel, int arg) {
parcel.writeDouble(latitude);
parcel.writeDouble(longitude);
}
public static final Parcelable.Creator<MyLatLng> CREATOR = new Creator<MyLatLng>() {
#Override
public MyLatLng createFromParcel(Parcel parcel) {
double latitude = parcel.readDouble();
double longitude = parcel.readInt();
return new MyLatLng(latitude, longitude);
}
#Override
public MyLatLng[] newArray(int size) {
return new MyLatLng[size];
}
};
//Metodi get/set
public double getLatitude() {
return latitude;
}
public double getLongitude() {
return longitude;
}
}
And using onSaveInstanceState I avoid the cancellation of the path. But this method introduces a non-elegance in my code because every time I need to create a LatLng object from MyLatLng object. Do you have any advice about this? Thanks a lot :)

Categories

Resources