android


How can I pass data doInBackground inside a snippet in other class?


I have a class to do an AsyncTask that is working fine and I can pass the data to my mainActivity. Now I have the problem that I don't know how to can handle this data in other places in my MainActivity. I want to use this data in a snippet (marker) to put some information in the marker:
AsyncTask class.
public class DistanceBetweenLocations extends AsyncTask<String, Void, String> {
URL url;
#Override
protected String doInBackground(String... params) {
HttpURLConnection urlConnection = null;
StringBuilder result = null;
String duration = "";
String distance = "";
try {
url = new URL(params[0]);
}catch (MalformedURLException m){
}
try {
urlConnection = (HttpURLConnection) url.openConnection();
}catch (IOException e){
}
try {
InputStream in = new BufferedInputStream(urlConnection.getInputStream());
BufferedReader reader = new BufferedReader(new InputStreamReader(in));
result = new StringBuilder();
String line;
while((line = reader.readLine()) != null) {
result.append(line);
}
}catch (IOException e){
} finally {
urlConnection.disconnect();
}
try {
JSONObject jsonObject = new JSONObject(result.toString());
JSONArray jsonArray = jsonObject.getJSONArray("rows");
JSONObject object_rows = jsonArray.getJSONObject(0);
JSONArray jsonArrayElements = object_rows.getJSONArray("elements");
JSONObject object_elements = jsonArrayElements.getJSONObject(0);
JSONObject object_duration = object_elements.getJSONObject("duration");
JSONObject object_distance = object_elements.getJSONObject("distance");
duration = object_duration.getString("text");
distance = object_distance.getString("text");
return distance + ", " + duration + " Driving";
} catch (JSONException e) {
e.printStackTrace();
}
return null;
}
#Override
protected void onPreExecute() {
super.onPreExecute();
}
#Override
protected void onPostExecute(String s) {
super.onPostExecute(s);
MainActivity mp = new MainActivity();
mp.getDataFromAsyncTask(s);
}
}
This is the method that I get the data in my MainActivity that is a Fragment:
public void getDataFromAsyncTask(String result) {
getDistanceAndTime = result + km;
}
And I want to use this data here:
mMap.addMarker(new MarkerOptions().position(new LatLng(geoPoint.getLatitude(), geoPoint.getLongitude()))
.title(name.getName())
.snippet(getDistanceAndTime)//here is where I want to put the data that I get in getDataFromAsyncTask
.icon(BitmapDescriptorFactory.defaultMarker(BitmapDescriptorFactory.HUE_RED)));
This is that I'm trying, but I get a no data:
I have a global variable that I'm using in my getDataFromAsyncTask and put in my snippet, but he take first the data of the inicialization:
String getDistanceAndTime
public void getDataFromAsyncTask(String result) {
getDistanceAndTime = result + km;
}
mMap.addMarker(new MarkerOptions().position(new LatLng(geoPoint.getLatitude(), geoPoint.getLongitude()))
.title(name.getName())
.snippet(getDistanceAndTime)//here is where I want to put the data that I get in getDataFromAsyncTask
.icon(BitmapDescriptorFactory.defaultMarker(BitmapDescriptorFactory.HUE_RED)));
This is what I would do when handling such scenarios - communication between classes; make your code as decoupled as possible. With that in mind, Events come to play!
Create an Event class (Plain Old Java Object POJO) with a variable (boolean isCompleted and a value you need to update your marker - obtained from AsyncTask). Your constructor should take values to set these variables inside onPostExecute. This is where you notify your activity of the event. EventBus.getDefault().post(new EventClassName(true, value));
Using of the event libraries - my favorite is EventBus, inside your onPostExecute() method of the AsyncTask, you can pass back the new value to the activity.
The activity must register (subscribe) to the event you created in step 1 by doing EventBus.getDefault().register(this)
You also must unregister inside onDestroy of your activity or Fragment.
Now, finally, you need to add a method with the following signature to your activity - this method will catch the event posted from onPostExecute() and must look like this : public void onEvent(EventClassName event)
Inside this method, you should call a method that updates your Marker or update it directly if you prefer!
To use EventBus library, simply add this to your build.gradle dependecies
compile 'org.greenrobot:eventbus:3.0.0'
You should be good to go! Good luck and happy coding.
In onPostExecute method you are instantiating the activity yourself, it just serves no purpose, activity is instantiated by the system. If you are calling the AsyncTask from MainActivity, then pass the reference to it and then call your method using that reference.
There's a misunderstanding about your code here:
MainActivity mp = new MainActivity();
mp.getDataFromAsyncTask(s);
In Android, you don't create activity object instances. Android creates them for you when you start the activity.
To pass a string or other data to an activity, you can put that data in the intent that starts the activity, then you pull that data out of the intent during the activity's onCreate() to work with it. This is one of the most fundamental practices in Android, and the documentation for that is here.

Related Links

Borderless button in linearlayout with layout_weight in Android
App force closes on a null pointer exception. Culprit is known but no solution
Coin Recognition on Android
Is there a difference in performance between drawing a scaled image versus a regular image?
Android-Layout: RelativeLayout automatic re-sizing edittext fields possible?
“No such file or directory” trying to execute linux binary on Android device
Alert dialog period is to short
IntentFilter Camera and Picture Taken
Activity reloads the whole data from server again when coming back from an other activity in Android
Using ContentProviders for non persistent data
Can I custom tab layout and theme in android?
Event handler for OptionsMenuItem in fullscreenwrapper2 and sl4a
How to modify already sent broadcast in android
Delete view from ListView
Android different screen size issues (Testing on Galaxy S1, S2, S3 and Note2 etc)
Debugging my Android app [closed]

Categories

HOME
cygwin
beautifulsoup
c++11
time-complexity
jax-rs
character-encoding
sh
sitecore
database-normalization
emscripten
maxscript
python-multithreading
crystal-reports-2013
siddhi
startup
jsonpath
automatic-ref-counting
gruntfile
aws-sdk
template-engine
asp.net-mvc-viewmodel
digital-signature
enterprise-miner
kendo-mobile
guzzle
ios10.2
visual-studio-extensions
event-store
ckfinder
shared
handler
magento-1.8
volatile
livelink
r-grid
nested-lists
apns-php
ogc
movilizer
subclipse
android-exoplayer
flask-login
dbcontext
insight
openblas
payara-micro
magic-draw
amq
git-flow
mapxtreme
hadoop-2.7.2
beamer
drawstring
dup
refinerycms
mediametadataretriever
php-socket
redis-cluster
createprocess
nupic
toast
mobiledoc-kit
user-management
file-move
oracle-spatial
dulwich
nutiteq
fits
shopizer
nodelist
iiop
crowd
device-tree
encryption-asymmetric
codeplex
cancellation
live555
android-framework
multiautocompletetextview
gwt-openlayers
scrypt
facebook-timeline
web-farm
wcf-configuration
paginator
inkcanvas
httponly
google-maps-mobile
node-redis
saxparseexception
w3c-geolocation
codebase
addchild

Resources

Encrypt Message