i am following this tutorial to implement google direction API. In the tutorial the onclick and all codes related to inputing data are in a fragmentActivity. But i would like to use a fragment. i would like to know how to change the asyncTask class in the tutorial so that it is using the right Context to find my fragment.
Here is my attempt.
public class GetDirectionsAsyncTask extends AsyncTask<Map<String, Object>, Object, ArrayList<LatLng>>
{
public static final String USER_CURRENT_LATLNG = "user_current_latlng";
public static final String DESTINATION_LATLNG = "destination_latlng";
public static final String DIRECTIONS_MODE = "directions_mode";
private MainActivity activity;
private Closest fragment;
private Exception exception;
private ProgressDialog progressDialog;
public GetDirectionsAsyncTask(Closest fragment, MainActivity activity)
{
super();
this.activity = activity;
}
public void onPreExecute()
{
progressDialog = new ProgressDialog(this.fragment.getActivity());
progressDialog.setMessage("Calculating directions");
progressDialog.show();
}
#Override
public void onPostExecute(ArrayList<LatLng> result)
{
progressDialog.dismiss();
if (exception == null)
{
fragment.handleGetDirectionsResult(result);
}
else
{
processException();
}
}
#Override
protected ArrayList<LatLng> doInBackground(Map<String, Object>... params)
{
Map<String, Object> paramMap = params[0];
try
{
LatLng fromPosition = (LatLng) paramMap.get(USER_CURRENT_LATLNG);
LatLng toPosition = (LatLng) paramMap.get(DESTINATION_LATLNG);
GMapV2Direction md = new GMapV2Direction();
Document doc = md.getDocument(fromPosition, toPosition, (String)paramMap.get(DIRECTIONS_MODE));
ArrayList<LatLng> directionPoints = md.getDirection(doc);
return directionPoints;
}
catch (Exception e)
{
exception = e;
return null;
}
}
private void processException()
{
Toast.makeText(activity, "Error retriving data", Toast.LENGTH_LONG).show();
}
}
The minute it needs to know the Context, it crashes in logcat with a nullpointer exception. if u realise, the first time it needs the context is on progressDialog = new ProgressDialog(this.fragment.getActivity());
Simply replace this.fragment.getActivity() with this.activity since you already have reference to the activity.
Technically, to make it a more reusable and decoupled class I would replace the reference to MainActivity and simply call it Context since that's really all you need it for and don't really care if it's the MainActivity or some other Activity that this later lives on.
Instead
progressDialog = new ProgressDialog(this.fragment.getActivity());
use
progressDialog = new ProgressDialog(activity);
Related
So I am new to programming, what I'm trying to do is to make an android app that will give to the client the nearest and fastest way to go the cinema/gas station/market. The problem with that is that first I need to find the nearest places via google api get the lats and lngs and then use them to direction api.
So what I have done is this:
GetNearbyPlaces.java
public class GetNearbyPlaces extends AsyncTask<Object, String, String>
{
private String googleplaceData, url;
private GoogleMap mMap;
#Override
protected String doInBackground(Object... objects)
{
mMap = (GoogleMap) objects[0];
url = (String) objects[1];
DownloadUrl downloadUrl = new DownloadUrl();
try
{
googleplaceData = downloadUrl.ReadTheURL(url);
}
catch (IOException e)
{
e.printStackTrace();
}
return googleplaceData;
}
#Override
protected void onPostExecute(String s)
{
List<HashMap<String, String>> nearbyPlacesList = null;
DataParser dataParser = new DataParser();
nearbyPlacesList = dataParser.parse(s);
DisplayNearbyPlaces(nearbyPlacesList);
super.onPostExecute(s);
Log.d("Message","telos execute ");
}
private void DisplayNearbyPlaces(List<HashMap<String, String>> nearbyPlacesList)
{
for (int i=0; i<nearbyPlacesList.size();
{
Log.d("Message","mesa stin for ");
MarkerOptions markerOptions = new MarkerOptions();
HashMap<String, String> googleNearbyPlace = nearbyPlacesList.get(i);
String nameOfPlace = googleNearbyPlace.get("place_name");
String vicinity = googleNearbyPlace.get("vicinity");
double lat = Double.parseDouble(googleNearbyPlace.get("lat"));
double lng = Double.parseDouble(googleNearbyPlace.get("lng"));
LatLng latLng = new LatLng(lat, lng);
markerOptions.position(latLng);
markerOptions.title(nameOfPlace + " : " + vicinity);
markerOptions.icon(BitmapDescriptorFactory.defaultMarker(BitmapDescriptorFactory.HUE_YELLOW));
mMap.addMarker(markerOptions);
mMap.moveCamera(CameraUpdateFactory.newLatLng(latLng));
mMap.animateCamera(CameraUpdateFactory.zoomTo(10));
}
}
}
GoogleUserMaps.java
case R.id.gasstation_nearby:
mMap.clear();
mMap.addMarker(userLocMarkerOptions);
mMap.setTrafficEnabled(true);
url = getUrl(latitude,longitude,gasStation);
transferData[0] = mMap;
transferData[1] = url;
Log.d("Message","Prin kanei execute ");
getNearbyPlaces.execute(transferData);
Log.d("Message","afou kanei execute ");
Toast.makeText(this, "Searching for Nearby Gas Stations.", Toast.LENGTH_SHORT).show();
Toast.makeText(this, "Showing for Nearby Gas Stations.", Toast.LENGTH_SHORT).show();
break;
I want to add something inside DisplayNearbyPlaces a public variable in order to get the lats and lngs but when I use it after the getNearbyPlaces.execute(transferData).get(); of GoogleUserMaps.java it gives me 0 result. I can't understand AsyncTask. Is there any way that I can wait until
getNearbyPlaces.execute(transferData).get(); finishes the execute in order to get the lats and lngs ?
Thank you in advance !
my logcat
I want to get the result after the execute finishes as I show you in the image bellow
Async task runs in a seperate thread than UI thread. It would be better if you try to use a Callback interface and when onPost of Async task is called perform the action in that callback
#Strack I am posting code example of interface
`
public interface PlaceListener{
void searchStarted();
void searchEnded();
}
public class GetNearbyPlaces extends AsyncTask<Object, String, String>
{
private String googleplaceData, url;
private GoogleMap mMap;
private PlaceListener placeListener;
public GetNearbyPlaces(PlaceListener placeListener){
this.placeListner = placeListener;
}
//onPreExecute(){ placeListner.searchStarted();}
#Override
protected String doInBackground(Object... objects)
{
mMap = (GoogleMap) objects[0];
url = (String) objects[1];
DownloadUrl downloadUrl = new DownloadUrl();
try
{
googleplaceData = downloadUrl.ReadTheURL(url);
}
catch (IOException e)
{
e.printStackTrace();
}
return googleplaceData;
}
#Override
protected void onPostExecute(String s)
{
placeListner.serachEnded();
List<HashMap<String, String>> nearbyPlacesList = null;
DataParser dataParser = new DataParser();
nearbyPlacesList = dataParser.parse(s);
DisplayNearbyPlaces(nearbyPlacesList);
super.onPostExecute(s);
Log.d("Message","telos execute ");
}
}
`
Implement the PlaceListener in Caller Activity and perform your desired task in searchEnded. You can make the parameters of your interface methods according to your desired data you want to pass
ok. create a new call back:
public interface MyCallBack {
void myTaskDone(List<HashMap<String, String>> nearbyPlacesList);
}
create one in your activity:
MyCallBack myCallBack = new MyCallBack() {
#Override
public void myTaskDone(List<HashMap<String, String>> nearbyPlacesList) {
DisplayNearbyPlaces(nearbyPlacesList);
}
};
send a reference to the Aynctask:
getNearbyPlaces.execute(transferData, map, new MyCallBack() {
#Override
public void myTaskDone(List<HashMap<String, String>> nearbyPlacesList) {
DisplayNearbyPlaces(nearbyPlacesList);
}
});
complete code:
public interface MyCallBack {
void myTaskDone(List<HashMap<String, String>> nearbyPlacesList);
}
public class GetNearbyPlaces extends AsyncTask<Object, String, String> {
private String googleplaceData;
private String url;
private GoogleMap mMap;
private MyCallBack myCallBack;
public GetNearbyPlaces(String url, GoogleMap mMap, MyCallBack myCallBack) {
this.url = url;
this.mMap = mMap;
this.myCallBack = myCallBack;
}
#Override
protected String doInBackground(Object... objects) {
DownloadUrl downloadUrl = new DownloadUrl();
try {
googleplaceData = downloadUrl.ReadTheURL(url);
} catch (IOException e) {
e.printStackTrace();
}
return googleplaceData;
}
#Override
protected void onPostExecute(String s) {
List<HashMap<String, String>> nearbyPlacesList = null;
DataParser dataParser = new DataParser();
nearbyPlacesList = dataParser.parse(s);
myCallBack.myTaskDone(nearbyPlacesList);
}
}
private void DisplayNearbyPlaces(List<HashMap<String, String>> nearbyPlacesList) {
/// your code
}
MyCallBack myCallBack = new MyCallBack() {
#Override
public void myTaskDone(List<HashMap<String, String>> nearbyPlacesList) {
DisplayNearbyPlaces(nearbyPlacesList);
}
};
How to call it:
//.....
transferData[0] = mMap;
transferData[1] = url;
Log.d("Message","Prin kanei execute ");
GetNearbyPlaces getNearbyPlaces = new GetNearbyPlaces(transferData, map, myCallBack);
getNearbyPlaces.execute();
//or:
GetNearbyPlaces getNearbyPlaces = new GetNearbyPlaces(transferData, map, new MyCallBack() {
#Override
public void myTaskDone(List<HashMap<String, String>> nearbyPlacesList) {
DisplayNearbyPlaces(nearbyPlacesList);
}
});
getNearbyPlaces.execute();
I am busy with an application where i am getting data from my azure database with sql and storing it in an array. I created a separate class where i get my data and my main activity connects to this class and then displays it.
Here is my getData class:
public class GetData {
Connection connect;
String ConnectionResult = "";
Boolean isSuccess = false;
public List<Map<String,String>> doInBackground() {
List<Map<String, String>> data = null;
data = new ArrayList<Map<String, String>>();
try {
ConnectionHelper conStr=new ConnectionHelper();
connect =conStr.connectionclass(); // Connect to database
if (connect == null) {
ConnectionResult = "Check Your Internet Access!";
} else {
// Change below query according to your own database.
String query = "select * from cc_rail";
Statement stmt = connect.createStatement();
ResultSet rs = stmt.executeQuery(query);
while (rs.next()) {
Map<String,String> datanum=new HashMap<String,String>();
datanum.put("NAME",rs.getString("RAIL_NAME"));
datanum.put("PRICE",rs.getString("RAIL_UNIT_PRICE"));
datanum.put("RANGE",rs.getString("RAIL_RANGE"));
datanum.put("SUPPLIER",rs.getString("RAIL_SUPPLIER"));
datanum.put("SIZE",rs.getString("RAIL_SIZE"));
data.add(datanum);
}
ConnectionResult = " successful";
isSuccess=true;
connect.close();
}
} catch (Exception ex) {
isSuccess = false;
ConnectionResult = ex.getMessage();
}
return data;
}
}
And in my Fragmentactivity.java I simply just call the class as shown here:
List<Map<String,String>> MyData = null;
GetValence mydata =new GetValence();
MyData= mydata.doInBackground();
String[] fromwhere = { "NAME","PRICE","RANGE","SUPPLIER","SIZE" };
int[] viewswhere = {R.id.Name_txtView , R.id.price_txtView,R.id.Range_txtView,R.id.size_txtView,R.id.supplier_txtView};
ADAhere = new SimpleAdapter(getActivity(), MyData,R.layout.list_valence, fromwhere, viewswhere);
list.setAdapter(ADAhere);
list.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
HashMap<String,Object> obj=(HashMap<String,Object>)ADAhere.getItem(position);
String ID=(String)obj.get("A");
Toast.makeText(getActivity(), ID, Toast.LENGTH_SHORT).show();
}
});
My problem comes when I want to include the onPreExecute and onPostExecute because I am relatively new to android studio and I do not know where to put the following lines of code:
#Override
protected void onPreExecute() {
ProgressDialog progress;
progress = ProgressDialog.show(MainActivity.this, "Synchronising", "Listview Loading! Please Wait...", true);
}
#Override
protected void onPostExecute(String msg) {
progress.dismiss();
}
You need to get the data from your azure database using a background service or AsyncTask. However, you are defining a class GetData which does not extend AsyncTask and hence the whole operation is not asynchronous. And I saw you have implemented doInBackground method which is not applicable here as you are not extending AsyncTask. I would suggest an implementation like the following.
You want to get some data from your azure database and want to show them in your application. In these kind of situations, you need to do this using an AsyncTask to call the server api to get the data and pass the data to the calling activity using an interface. Let us have an interface like the following.
public interface HttpResponseListener {
void httpResponseReceiver(String result);
}
Now from your Activity while you want to get the data through an web service call, i.e. AsyncTask, just the pass the interface from the activity class to the AsyncTask. Remember that your AsyncTask should have an instance variable of that listener as well. So the overall implementation should look like the following.
public abstract class HttpRequestAsyncTask extends AsyncTask<Void, Void, String> {
public HttpResponseListener mHttpResponseListener;
private final Context mContext;
HttpRequestAsyncTask(Context mContext, HttpResponseListener listener) {
this.mContext = mContext;
this.mHttpResponseListener = listener;
}
#Override
protected String doInBackground(Void... params) {
String result = null;
try {
// Your implementation of getting data from your server
} catch (Exception e) {
e.printStackTrace();
}
return result;
}
#Override
protected void onPostExecute(final String result) {
mHttpResponseListener.httpResponseReceiver(result);
}
#Override
protected void onCancelled() {
mHttpResponseListener.httpResponseReceiver(null);
}
}
Now you need to have the httpResponseReceiver function implemented in the calling Activity. So the sample activity should look like.
public class YourActivity extends AppCompatActivity implements HttpResponseListener {
// ... Other code and overriden functions
public void callAsyncTaskForGettingData() {
// Pass the listener here
HttpRequestAsyncTask getDataTask = new HttpRequestGetAsyncTask(
YourActivity.this, this);
getDataTask.executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR);
}
#Override
public void httpResponseReceiver(String result) {
// Get the response callback here
// Do your changes in UI elements here.
}
}
To read more about how to use AsyncTask, you might consider having a look at here.
i'm creating an app that grabs list of playlists on YouTube. It used to be a list of videos, but i've changed the code and now it did not let me override that method.
My understanding is that i should change the "extends AsyncTask" with the new Playlist value instead of Video as it was before, but it still did not work.
it was:
public abstract class GetPlaylistAsyncTask extends AsyncTask<String, Void, Pair<String, List<Video>>> {
and now is:
public abstract class GetPlaylistAsyncTask extends AsyncTask<String, Void, Pair<String, List<Playlist>>> {
This is where is the error:
mPlaylist = new Playlist(mPlaylistId);
initAdapter(mPlaylist);
new GetPlaylistAsyncTask(mYouTubeDataApi, mTitle, mSearchQuery) {
#Override
public void onPostExecute(Pair<String, List<Playlist>> result) {
handleGetPlaylistResult(mPlaylist, result);
}
}.execute(mPlaylist.playlistId, mPlaylist.getNextPageToken());
And this is the AsyncTask:
public abstract class GetPlaylistAsyncTask extends AsyncTask<String, Void, Pair<String, List<Playlist>>> {
private static final String TAG = "GetPlaylistAsyncTask";
private static final Long YOUTUBE_PLAYLIST_MAX_RESULTS = 50L;
private static final String YOUTUBE_VIDEOS_PART = "snippet,contentDetails,statistics"; // video resource properties that the response will include.
private static final String YOUTUBE_VIDEOS_FIELDS = "items(id,snippet(title,description,thumbnails/high),contentDetails/duration,statistics)"; // selector specifying which fields to include in a partial response.
private YouTube mYouTubeDataApi;
private String mTitle;
private String mSearchQuery;
public GetPlaylistAsyncTask(YouTube api, String title, String searchQuery) {
mYouTubeDataApi = api;
mTitle = title;
mSearchQuery = searchQuery;
}
#Override
protected Pair<String, List<Playlist>> doInBackground(String... params) {
SearchListResponse searchResponse;
try {
YouTube.Search.List search = mYouTubeDataApi.search().list("id,snippet");
search.setKey(ApiKey.YOUTUBE_API_KEY);
search.setQ(mTitle + " " + mSearchQuery);
search.setType("video");
search.setFields("items(id/kind,id/videoId,snippet/title,snippet/thumbnails/default/url)");
search.setMaxResults(YOUTUBE_PLAYLIST_MAX_RESULTS);
searchResponse = search.execute();
} catch (IOException e) {
e.printStackTrace();
return null;
}
if (searchResponse == null) {
Log.e(TAG, "Failed to get playlist");
return null;
}
ArrayList videoIds = new ArrayList();
for (SearchResult item : searchResponse.getItems()) {
videoIds.add(item.getId().getVideoId());
}
VideoListResponse videoListResponse = null;
try {
videoListResponse = mYouTubeDataApi.videos()
.list(YOUTUBE_VIDEOS_PART)
.setFields(YOUTUBE_VIDEOS_FIELDS)
.setKey(ApiKey.YOUTUBE_API_KEY)
.setId(TextUtils.join(",", videoIds)).execute();
} catch (IOException e) {
e.printStackTrace();
}
return new Pair(searchResponse.getNextPageToken(), videoListResponse.getItems());
}
}
i don't get what is wrong on my code, i'll appreciate if you can point me on the right direction. Thanks in advance!
I've figured it out. The "onPostExecute" takes the object that doInBackground returns, as this post says:
stackoverflow post
Thanks to all for your answers, especially to #Enzokie
Just change public to protected since onPostExecute is not public by design.
#Override
protected void onPostExecute(Pair<String, List<Playlist>> result) {
handleGetPlaylistResult(mPlaylist, result);
}
Is there any way to break AsyncTaskResult>>
into to list ?
or get like 30,40,.. value of it only?
i have a Async class and it return the result of webservice fetch to adapter.
now because of huge data i want to split the result into seperate segment with passing
number of result to async class.
here is myasync class :
protected AsyncTaskResult<ArrayList<HashMap<String, String>>> doInBackground(
String... arg0) {
String xml = "Get String from my web service class"
myXmlParsingClass myparser = new myXmlParsingClass (xml, "getitem");
myparser .runParser();
AsyncTaskResult<ArrayList<HashMap<String, String>>> myresult = new AsyncTaskResult<ArrayList<HashMap<String, String>>>(myXmlParsingClass .getParsedData());
return myresult ;
}
and my asynctaskresult :
public class AsyncTaskResult<T> {
private T result = null;
private Exception error = null;
public T getResult() {
return result;
}
public Exception getError() {
return error;
}
public AsyncTaskResult(T result) {
super();
this.result = result;
}
public AsyncTaskResult() {
super();
}
public AsyncTaskResult(Exception error) {
super();
this.error = error;
}
this is what i have done so far :
in the getview method inside my adapter i made second method to pass a number to async class:
MyAsyncClass ma = new MyAsyncClass(myview,userid,5);
in MyAsyncClass :
public MyAsyncClass ( View context,String _id) {
this.targetCtx = context ;
id = _id;
}
public MyAsyncClass ( View context,String _id,int _ID_To_Show) {
this.targetCtx = context ;
id = _id;
ID_To_Show= _ID_To_Show;
}
and on PostExecute method :
if(ID_To_Show >0 ){
MySecondAdapter Madapter = new MySecondAdapter(targetCtx, myresult.getResult(),ID_To_Show);
mylist.setAdapter(Madapter);
}else{
MySecondAdapter Madapter = new MySecondAdapter(targetCtx, myresult.getResult());
mylist.setAdapter(Madapter);
and finally in MySecondAdapter i added this :
public MySecondAdapter(View a, ArrayList<HashMap<String, String>> id,int _ID_To_Show) {
idfromhayoolafetch = id;
myinflater = (LayoutInflater) AppContext.getAppContext().getSystemService(Context.LAYOUT_INFLATER_SERVICE);
ID_To_Show= _ID_To_Show;
}
public MySecondAdapter(View a, ArrayList<HashMap<String, String>> id) {
idfromhayoolafetch = id;
myinflater = (LayoutInflater) AppContext.getAppContext().getSystemService(Context.LAYOUT_INFLATER_SERVICE);
}
public int getCount() {
if(ID_To_Show>0){
return ID_To_Show;
}else{
return idfromhayoolafetch.size();
}
}
this approch show the amount of item i want to show in each call and i can pass value to it
but is other way i can do this ?
problem is i cant ask hayoola to limit the value in respond.
Such a request should be handled by server it self.
As in server should accept number of items to return and only send that many items.
But still if you want async task to handle it you can do following:
protected AsyncTaskResult<ArrayList<HashMap<String, String>>> doInBackground(
String... arg0) {
String xml = "Get String from my web service class"
myXmlParsingClass myparser = new myXmlParsingClass (xml, "getitem");
myparser .runParser();
AsyncTaskResult<ArrayList<HashMap<String, String>>> myresult = new AsyncTaskResult<ArrayList<HashMap<String, String>>>(myXmlParsingClass .getParsedData());
ArrayList<HashMap<String, String>> result=myresult.getResult();
myresult.setResult(result.subList(0,maxItems));//maxItems=30 set it while creating async task object
return myresult ;
}
I have an application that does some long calculations, and I would like to show a progress dialog while this is done. So far I have found that I could do this with threads/handlers, but didn't work, and then I found out about the AsyncTask.
In my application I use maps with markers on it, and I have implemented the onTap function to call a method that I have defined. The method creates a dialog with Yes/No buttons, and I would like to call an AsyncTask if Yes is clicked. My question is how to pass an ArrayList<String> to the AsyncTask (and work with it there), and how to get back a new ArrayList<String> like a result from the AsyncTask?
The code of the method looks like this:
String curloc = current.toString();
String itemdesc = item.mDescription;
ArrayList<String> passing = new ArrayList<String>();
passing.add(itemdesc);
passing.add(curloc);
ArrayList<String> result = new ArrayList<String>();
new calc_stanica().execute(passing,result);
String minim = result.get(0);
int min = Integer.parseInt(minim);
String glons = result.get(1);
String glats = result.get(2);
double glon = Double.parseDouble(glons);
double glat = Double.parseDouble(glats);
GeoPoint g = new GeoPoint(glon, glat);
String korisni_linii = result.get(3);
So, as you see, I would like to send the string array list "passing" to the AsyncTask, and to get the "result" string array list back from it. And the calc_stanica AssycTask class looks like this:
public class calc_stanica extends AsyncTask<ArrayList<String>, Void, ArrayList<String>> {
ProgressDialog dialog;
#Override
protected void onPreExecute() {
dialog = new ProgressDialog(baraj_mapa.this);
dialog.setTitle("Calculating...");
dialog.setMessage("Please wait...");
dialog.setIndeterminate(true);
dialog.show();
}
protected ArrayList<String> doInBackground(ArrayList<String>... passing) {
//Some calculations...
return something; //???
}
protected void onPostExecute(Void unused) {
dialog.dismiss();
}
So my question is how to get the elements of the "passing" array list in the AsyncTask doInBackground method (and use them there), and how to return an array list to use in the main method (the "result" array list)?
Change your method to look like this:
String curloc = current.toString();
String itemdesc = item.mDescription;
ArrayList<String> passing = new ArrayList<String>();
passing.add(itemdesc);
passing.add(curloc);
new calc_stanica().execute(passing); //no need to pass in result list
And change your async task implementation
public class calc_stanica extends AsyncTask<ArrayList<String>, Void, ArrayList<String>> {
ProgressDialog dialog;
#Override
protected void onPreExecute() {
dialog = new ProgressDialog(baraj_mapa.this);
dialog.setTitle("Calculating...");
dialog.setMessage("Please wait...");
dialog.setIndeterminate(true);
dialog.show();
}
protected ArrayList<String> doInBackground(ArrayList<String>... passing) {
ArrayList<String> result = new ArrayList<String>();
ArrayList<String> passed = passing[0]; //get passed arraylist
//Some calculations...
return result; //return result
}
protected void onPostExecute(ArrayList<String> result) {
dialog.dismiss();
String minim = result.get(0);
int min = Integer.parseInt(minim);
String glons = result.get(1);
String glats = result.get(2);
double glon = Double.parseDouble(glons);
double glat = Double.parseDouble(glats);
GeoPoint g = new GeoPoint(glon, glat);
String korisni_linii = result.get(3);
}
UPD:
If you want to have access to the task starting context, the easiest way would be to override onPostExecute in place:
new calc_stanica() {
protected void onPostExecute(ArrayList<String> result) {
// here you have access to the context in which execute was called in first place.
// You'll have to mark all the local variables final though..
}
}.execute(passing);
Why would you pass an ArrayList??
It should be possible to just call execute with the params directly:
String curloc = current.toString();
String itemdesc = item.mDescription;
new calc_stanica().execute(itemdesc, curloc)
That how varrargs work, right?
Making an ArrayList to pass the variable is double work.
I sort of agree with leander on this one.
call:
new calc_stanica().execute(stringList.toArray(new String[stringList.size()]));
task:
public class calc_stanica extends AsyncTask<String, Void, ArrayList<String>> {
#Override
protected ArrayList<String> doInBackground(String... args) {
...
}
#Override
protected void onPostExecute(ArrayList<String> result) {
... //do something with the result list here
}
}
Or you could just make the result list a class parameter and replace the ArrayList with a boolean (success/failure);
public class calc_stanica extends AsyncTask<String, Void, Boolean> {
private List<String> resultList;
#Override
protected boolean doInBackground(String... args) {
...
}
#Override
protected void onPostExecute(boolean success) {
... //if successfull, do something with the result list here
}
}
I dont do it like this. I find it easier to overload the constructor of the asychtask class ..
public class calc_stanica extends AsyncTask>
String String mWhateveryouwantToPass;
public calc_stanica( String whateveryouwantToPass)
{
this.String mWhateveryouwantToPass = String whateveryouwantToPass;
}
/*Now you can use whateveryouwantToPass in the entire asynchTask ... you could pass in a context to your activity and try that too.*/ ... ...
You can receive returning results like that:
AsyncTask class
#Override
protected Boolean doInBackground(Void... params) {
if (host.isEmpty() || dbName.isEmpty() || user.isEmpty() || pass.isEmpty() || port.isEmpty()) {
try {
throw new SQLException("Database credentials missing");
} catch (SQLException e) {
e.printStackTrace();
}
}
try {
Class.forName("org.postgresql.Driver");
} catch (ClassNotFoundException e) {
e.printStackTrace();
}
try {
this.conn = DriverManager.getConnection(this.host + ':' + this.port + '/' + this.dbName, this.user, this.pass);
} catch (SQLException e) {
e.printStackTrace();
}
return true;
}
receiving class:
_store.execute();
boolean result =_store.get();
Hoping it will help.