Asynctask accessed for two activities - java

I have a AsyncTask for downloading a route from API Google Directions. The task starts at first Activity, where I show the time and the distance of the user to a point, but my map is in the second activity where I need draw the line of the route. My question is how to maintain a unique download task between two tasks (If the download has not completed in first activity), and access the data of the task on two activities.
public class DownloadDirections {
String urlDownload;
PolylineOptions lineOptions = null;
Context context;
String mTime;
String mDistance;
public DownloadDirections (Context context, String urlDownload){
this.urlDownload = urlDownload;
this.context = context;
new DownloadDirectionsTask().execute(urlDownload);
}
// Fetches data from url passed
private class DownloadDirectionsTask extends AsyncTask<String, Void, String> {
// Downloading data in non-ui thread
#Override
protected String doInBackground(String... url) {
// For storing data from web service
String data = "";
try {
// Fetching the data from web service
data = downloadUrl(url[0]);
} catch (Exception e) {
Log.d("Background Task", e.toString());
}
return data;
}
// Executes in UI thread, after the execution of
// doInBackground()
#Override
protected void onPostExecute(String result) {
super.onPostExecute(result);
ParserTask parserTask = new ParserTask();
// Invokes the thread for parsing the JSON data
parserTask.execute(result);
}
}
/**
* A method to download json data from url
*/
private String downloadUrl(String strUrl) throws IOException {
String data = "";
InputStream iStream = null;
HttpURLConnection urlConnection = null;
try {
URL url = new URL(strUrl);
// Creating an http connection to communicate with url
urlConnection = (HttpURLConnection) url.openConnection();
// Connecting to url
urlConnection.connect();
// Reading data from url
iStream = urlConnection.getInputStream();
BufferedReader br = new BufferedReader(new InputStreamReader(iStream));
StringBuffer sb = new StringBuffer();
String line = "";
while ((line = br.readLine()) != null) {
sb.append(line);
}
data = sb.toString();
br.close();
} catch (Exception e) {
e.printStackTrace();
} finally {
iStream.close();
urlConnection.disconnect();
}
return data;
}
/**
* A class to parse the Google Places in JSON format
*/
private class ParserTask extends AsyncTask<String, Integer, List<List<HashMap<String, String>>>> {
// Parsing the data in non-ui thread
#Override
protected List<List<HashMap<String, String>>> doInBackground(String... jsonData) {
JSONObject jObject;
List<List<HashMap<String, String>>> routes = null;
try {
jObject = new JSONObject(jsonData[0]);
DirectionsJSONParser parser = new DirectionsJSONParser();
// Starts parsing data
routes = parser.parse(jObject);
} catch (Exception e) {
e.printStackTrace();
}
return routes;
}
// Executes in UI thread, after the parsing process
#Override
protected void onPostExecute(List<List<HashMap<String, String>>> result) {
ArrayList<LatLng> points = null;
MarkerOptions markerOptions = new MarkerOptions();
String distance = "";
String duration = "";
if(result != null) {
if (result.size() < 1) {
Toast.makeText(context, "No Points", Toast.LENGTH_SHORT).show();
return;
}
}
if(result != null) {
// Traversing through all the routes
for (int i = 0; i < result.size(); i++) {
points = new ArrayList<LatLng>();
lineOptions = new PolylineOptions();
// Fetching i-th route
List<HashMap<String, String>> path = result.get(i);
// Fetching all the points in i-th route
for (int j = 0; j < path.size(); j++) {
HashMap<String, String> point = path.get(j);
if (j == 0) { // Get distance from the list
distance = (String) point.get("distance");
continue;
} else if (j == 1) { // Get duration from the list
duration = (String) point.get("duration");
continue;
}
double lat = Double.parseDouble(point.get("lat"));
double lng = Double.parseDouble(point.get("lng"));
LatLng position = new LatLng(lat, lng);
points.add(position);
}
// Adding all the points in the route to LineOptions
lineOptions.addAll(points);
lineOptions.width(2);
lineOptions.color(Color.RED);
mTime = duration;
mDistance = distance;
}
}
}
}
}

There are lots of options.
Download the entire item in the first activity, pass it to the second as intent data and access in the second activity. You may store the data in the internal storage (Preference, DB or Files depending on the size) if you want, and access accordingly.
You want to execute the task multiple times (one after another):
Keep a reference to the task object, and from the second activity call, make a wait call to the first one.
Want to use a service? No prob. Call the service, download the data, store them if very large. If the data is small, pass them via broadcast. Access them in the activity.
Is that what you wanted?

Related

Java Stack becomes empty for some reason

I'm working on an Android app that is going to call the DarkSky weather API (I have redacted my API key here for obvious reasons). My problem comes when I parse the JSON data and push it to a stack I named dataStack. At the time of pushing the stack I log its size and it shows correctly. However when my code reaches the buildGraph() method, the stack is now empty and all my data has disappeared. What causes the stack to empty?
EDIT: As of 30 minutes after posting I found a workaround. I am now returning the String and parsing it in my MainActivity Android class. However, I still do not know why the stack was being deleted. I would love to know :)
public class MainActivity extends AppCompatActivity {
Button button;
TextView progressLabel;
GraphView graph;
JSONObject jsonObject;
static Stack<DataPoint> dataStack = new Stack<>(); // stack for graph data points
static final String API_URL = "https://api.darksky.net/forecast/API_KEY/42.3611,-71.0570,"; // #TODO: delete API key before comitting to GitHub
static final String URL_TAIL = "?exclude=currently,flags,hourly"; // end of URL
static final long currTime = System.currentTimeMillis() / 1000L; // current UNIX time
static long unixTime = currTime;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
button = findViewById(R.id.button);
progressLabel = findViewById(R.id.progressLabel);
graph = findViewById(R.id.graph);
}
public void loadResults(View view) {
for (int x = 0; x < 2; x++) { // 7 API calls for each of 7 days
new APICall().execute();
unixTime -= 86400; // subtract 24 hours in UNIX time
dataStack.size();
}
buildGraph(); // after all data is gathered, build a graph using it
}
private void buildGraph() {
// #TODO: Method to build graph
Log.i("STACK pop", String.valueOf(dataStack.size()));
}
class APICall extends AsyncTask<Void, Void, String> { // Extend AsyncTask so we don't hijack the main UI thread
protected void onPreExecute() {
// Do stuff before executing the AsyncTask
progressLabel.setText("Fetching Data");
}
protected String doInBackground(Void... urls) {
// Execute background task here
try {
final String FULL_URL = API_URL + unixTime + URL_TAIL; // build the full URL with latest time
URL url = new URL(FULL_URL); // URL for the API call
HttpURLConnection urlConnection = (HttpURLConnection) url.openConnection(); // connection to URL
try {
// tools for reading API results
BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(urlConnection.getInputStream()));
StringBuilder stringBuilder = new StringBuilder();
String line;
// accumulate results
while ((line = bufferedReader.readLine()) != null) {
stringBuilder.append(line).append("\n");
}
bufferedReader.close(); // always close buffered reader
return stringBuilder.toString(); // return results
}
finally {
// inside a finally block so that no matter what we always end a connection that has been started
urlConnection.disconnect(); // end the connection
}
}
catch(Exception ex) {
Log.e("ERROR", ex.getMessage(), ex);
return null;
}
}
protected void onPostExecute(String response) {
// Do stuff after we're finished executing
if (response == null) {
response = "AN ERROR HAS OCCURRED";
}
else {
try {
jsonObject = new JSONObject(response); // create object from our response
JSONArray arr = jsonObject.getJSONObject("daily").getJSONArray("data"); // get data Array
String arrString = arr.getString(0); // full String
String[] splitString = arrString.split(","); // split String into array by comma
String time = splitString[0].substring(8); // time is the first index of the array, use substring to cutout unecessary info
String temp = splitString[11].substring(18);
dataStack.push(new DataPoint(Integer.valueOf(time), Float.valueOf(temp))); // push our data onto the stack as a DataPoint
Log.i("STACK push", String.valueOf(dataStack.toString()));
response = "Data received"; // display this to user
}
catch(Exception ex) {
response = "ERROR DURING JSON PARSING";
}
}
progressLabel.setText(response);
// parse data here
Log.i("INFO", response);
}
}
}
The stack is empty because result isn't in yet. The issue is with your loadResults().
public void loadResults(View view) {
for (int x = 0; x < 2; x++) { // 7 API calls for each of 7 days
new APICall().execute();
unixTime -= 86400; // subtract 24 hours in UNIX time
dataStack.size();
}
buildGraph(); // after all data is gathered, build a graph using it
}
You issued the new APICall().execute(); to request data and update the dataStack and you expect to get the dataStack results 'immediately' inside the same function loadResults()? It's not possible.
One solution is to remove the buildGraph() in loadResults() to inside onPostExecute().

make java wait until variable changes

I want to make my code wait until there is a change anywhere in my class to the variable finaloutcomes. Is there any way to do this? I am carrying this out within an Asynctask, which I posted below.
public HashMap<String,String> checkbetoutcome() {
new LoadAllGamet().execute();
// INSERT CODE HERE
return finaloutcomes;
}
ASYNCTASK
class LoadAllGamet extends AsyncTask<String, String, String> {
#Override
protected void onPreExecute() {
super.onPreExecute();
}
protected String doInBackground(String... args) {
// HttpParams httpParameters = new BasicHttpParams();
// HttpConnectionParams.setConnectionTimeout(httpParameters, 250000);
//HttpConnectionParams.setSoTimeout(httpParameters, 250000);
HttpClient client = new DefaultHttpClient();
HttpPost post = new HttpPost(url_check_bet);
List<NameValuePair> params = new ArrayList<NameValuePair>();
params.add(new BasicNameValuePair("param", bet));
// Log.d("CURRENTITEM", currentitem);
try {
post.setEntity(new UrlEncodedFormEntity(params));
} catch (IOException ioe) {
ioe.printStackTrace();
}
try {
HttpResponse response = client.execute(post);
Log.d("Http Post Responsecxxx:", response.toString());
HttpEntity httpEntity = response.getEntity();
InputStream is = httpEntity.getContent();
JSONObject jObj = null;
String json = "";
client.getConnectionManager().closeExpiredConnections();
try {
BufferedReader reader = new BufferedReader(new InputStreamReader(
is, "iso-8859-1"), 8);
StringBuilder sb = new StringBuilder();
String line = null;
while ((line = reader.readLine()) != null) {
if (!line.startsWith("<", 0)) {
if (!line.startsWith("(", 0)) {
sb.append(line + "\n");
}
}
}
is.close();
json = sb.toString();
json = json.substring(json.indexOf('{'));
// Log.d("sbsssssssssss", json);
try {
jObj = new JSONObject(json);
} catch (JSONException e) {
Log.e("JSON Parser", "Error parsing data " + e.toString());
}
allgames = jObj.getJSONArray("bets");
// Log.d("WHAT IS MY ARRAY?", allgames.toString());
for (Integer i = 0; i < allgames.length(); i++) {
HashMap<String,String> statuses = new HashMap<>();
JSONObject c = allgames.getJSONObject(i);
JSONArray currentbet = c.getJSONArray("bet");
Log.d("Single array",currentbet.toString());
// Storing each json item in variable
for (Integer a = 0; a < currentbet.length();a++) {
JSONObject d = currentbet.getJSONObject(a);
String Result = d.getString("Result");
String id = d.getString("gid");
Log.d("RESULTS",Result);
statuses.put(id, Result);
}
allbetsmap.add(i, statuses);
Log.d("ddd", statuses.toString());
Log.d("AAA", allbetsmap.get(i).toString());
}
} catch (Exception e) {
Log.e("Buffer Error", "Error converting result " + e.toString());
}
}
catch (IOException e) {
e.printStackTrace();
}
return "";
}
#Override
protected void onPostExecute(String param) {
Log.d("SIZE",Integer.toString(allbetsmap.size()));
//ArrayList<Map<String,String>> allbetsmap = new ArrayList<>();
//ArrayList<Map<String,String>> passtocheck = new ArrayList<>();
if (allbetsmap.size() == passtocheck.size()) {
for (int i = 0; i < allbetsmap.size();i++) {
if (allbetsmap.get(i).size() == passtocheck.get(i).size()) {
String finaloutcome = "won";
for (String a : allbetsmap.get(i).keySet()) {
String f = allbetsmap.get(i).get(a);
if(f.equals("null")) {
finaloutcome = "open";
}
else if (! (f.equals(passtocheck.get(i).get(a)))) {
finaloutcome = "lost";
break;
}
}
finaloutcomes.put(Integer.toString(i),finaloutcome);
}
}
}
Log.d("Vital",finaloutcomes.toString());
}
}
Ok, forget what I wrote before. I didn't realize you were writing code for android. Here is an improved version of LoadAllGamet. There are two important things here. 1. define as much as possible locally i.e. inside a method or - if that's not possible - inside the class. 2. return the result instead of putting it into some variable.
class LoadAllGamet extends AsyncTask<String, Void, HashMap<String,String>> {
protected HashMap<String,String> doInBackground(String ... args) {
HashMap<String,String> finaloutcomes = new HashMap<>(),
HashMap<Integer, HashMap<String,String>> allbetsmap = new HashMap<>();
HttpClient client = new DefaultHttpClient();
...
Log.d("SIZE",Integer.toString(allbetsmap.size()));
if (allbetsmap.size() == passtocheck.size()) {
...
}
Log.d("Vital",finaloutcomes.toString());
return finaloutcomes;
}
}
Whenever you want to do something that might take some time you should not run
that in the UI thread of you App since it can block your UI.
Instead run it asynchronously. One way of doing this is to use AsyncTask.
Let's assume you want to do something and while that something is being processed
you also want to update the UI (e.g. progress bars) from time to time. And once you
are finished you want to do something else with the result.
Here is one way of writing this.
void doSomething() {
new AsyncTask<String, Progress, Result>() {
protected Result doInBackground(String... args) {
//some code
publishProgress(values);
//some more code
return result;
}
protected void onProgressUpdate(Progress ... values) {
updateProgessBars(values);
}
protected void onPostExecute(Result result) {
doSomethingElse(result);
}
}.execute();
}
The String in new AsyncTask<String, Progress, Result> is the type of the
arguments to doInBackground. Often however you don't really need that unless
you want to pass arguments into execute.
Progress is the type of the values you want to send to onProgressUpdate. That
one you only need if you want to update your UI while the background processing
is still going on.
Result is of course your result type. Whatever you want to happen after
the doInBackground is finished you write into onPostExecute.

Google Places API: How to get photos and place id from latitude and longitude?

I want to get photos and place_id required by Google Place Details API of my current location.
Search nearby does not return places in my exact location. (current lat/lng returned by android location service).
Radar search requires a keyword. Please suggest.
Per the Google Place Search documentation the three things you need to provide are the KEY, LOCATION and RADIUS. I cut out a bunch of unnecessary code, but here's how I did something similar.
1) Get your current location
private void initializeMapLocation() {
LocationManager locationManager = (LocationManager) this
.getSystemService(Context.LOCATION_SERVICE);
Location lastLocation = locationManager
.getLastKnownLocation(LocationManager.GPS_PROVIDER);
if (lastLocation != null) {
setUserLocation(lastLocation);
}
}
private void setUserLocation(Location location) {
LatLng currentLatLng = new LatLng(location.getLatitude(), location.getLongitude());
mMap.animateCamera(CameraUpdateFactory.newLatLng(currentLatLng));
}
2) Build your search URL. You can add extra parameters like a keyword if you want by appending them on, but it doesn't sound like you want that in this particular case.
private void buildAndInitiateSearchTask(String searchType) {
Projection mProjection = mMap.getProjection();
LatLng mProjectionCenter = mProjection.getVisibleRegion().latLngBounds
.getCenter();
searchURL.append("https://maps.googleapis.com/maps/api/place/nearbysearch/");
searchURL.append("json?");
searchURL.append("location=" + mProjectionCenter.latitude + "," + mProjectionCenter.longitude);
searchURL.append("&radius=" + calculateProjectionRadiusInMeters(mProjection));
searchURL.append("&key=YOUR_KEY_HERE");
new PlaceSearchAPITask().execute(searchURL.toString());
}
private double calculateProjectionRadiusInMeters(Projection projection) {
LatLng farLeft = projection.getVisibleRegion().farLeft;
LatLng nearRight = projection.getVisibleRegion().nearRight;
Location farLeftLocation = new Location("Point A");
farLeftLocation.setLatitude(farLeft.latitude);
farLeftLocation.setLongitude(farLeft.longitude);
Location nearRightLocation = new Location("Point B");
nearRightLocation.setLatitude(nearRight.latitude);
nearRightLocation.setLongitude(nearRight.longitude);
return farLeftLocation.distanceTo(nearRightLocation) / 2 ;
}
3) Send your request and display your results as an AsyncTask
private class PlaceSearchAPITask extends AsyncTask<String, Void, String> {
#Override
protected String doInBackground(String... placesURL) {
StringBuilder placesBuilder = new StringBuilder();
for (String placeSearchURL : placesURL) {
HttpClient placesClient = createHttpClient();
try {
HttpGet placesGet = new HttpGet(placeSearchURL);
HttpResponse placesResponse = placesClient
.execute(placesGet);
StatusLine placeSearchStatus = placesResponse
.getStatusLine();
if (placeSearchStatus.getStatusCode() == 200) {
HttpEntity placesEntity = placesResponse
.getEntity();
InputStream placesContent = placesEntity
.getContent();
InputStreamReader placesInput = new InputStreamReader(
placesContent);
BufferedReader placesReader = new BufferedReader(
placesInput);
String lineIn;
while ((lineIn = placesReader.readLine()) != null) {
placesBuilder.append(lineIn);
}
}
} catch (Exception e) {
e.printStackTrace();
}
}
return placesBuilder.toString();
}
#Override
protected void onPostExecute(String result) {
try {
JSONObject resultObject = new JSONObject(result);
// This is my custom object to hold the pieces of the JSONResult that I want. You would need something else for your particular problem.
mapData = new MapDataSource(resultObject.optJSONArray("results"));
} catch (JSONException e) {
e.printStackTrace();
}
if (mapData != null) {
// TODO - This is where you would add your markers and whatnot.
}
}
}

Efficient way of downloading data in Android App from MySQL

I was just wondering if my code is ok in terms of downloading. My app needs a lot of data from a database so quick download times are crucial. The download time is ok but I think it can be programmed more efficient. Can you have a look at this? This class downloads many different companies and when downloaded they are put in a HashMap corresponding to their category. When finished downloading this class return a HashMap which contains multiple Hashmaps(categories) and in these Hashmaps the downloaded data. Dont mind the actual workflow but please concentrate on the way this class downloads data. Is there a way to do this faster?
public class CompanyDAO {
private static Controller delegate;
private static String companyUrl = "http:// URL HERE";
private Map<Object, Object> companyMap = new HashMap<Object, Object>();
private Map<String, Integer> pinMap = new HashMap<String, Integer>();
public CompanyDAO (Controller _delegate, Map<String, Integer> map) {
delegate = _delegate; //reference to controller
pinMap = map;
}
public void getCompanyData(ArrayList<Object> categoriesArray) {
for (int i = 0; i < categoriesArray.size(); i++) {
Map<String, Object> categoriesInMap = new HashMap<String, Object>();
//ArrayList<Object> categoriesInMapArray = new ArrayList<Object>();
companyMap.put(categoriesArray.get(i), categoriesInMap);
}
this.downloadCompanyData();
}
private void downloadCompanyData() {
companyUrl = companyUrl + delegate.ID;
try {
new DownloadCompanyData().execute(companyUrl).get(10000, TimeUnit.MILLISECONDS);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (ExecutionException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (TimeoutException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
private class DownloadCompanyData extends AsyncTask<String, Void, String> {
#Override
protected String doInBackground(String... urls) {
String response = "";
for (String url : urls) {
DefaultHttpClient client = new DefaultHttpClient();
HttpGet httpGet = new HttpGet(url);
try {
HttpResponse execute = client.execute(httpGet);
InputStream content = execute.getEntity().getContent();
BufferedReader buffer = new BufferedReader(new InputStreamReader(content));
String s = "";
while ((s = buffer.readLine()) != null) {
response += s;
}
} catch (Exception e) {
e.printStackTrace();
}
}
return response;
}
#SuppressWarnings("unchecked")
#Override
protected void onPostExecute(String result) {
JSONArray companyDataArray;
try {
companyDataArray = new JSONArray(result);
for(int i=0;i<companyDataArray.length();i++){
JSONObject id = companyDataArray.getJSONObject(i);
String catName = id.getString(Controller.CAT_NAME);
if (companyMap.get(catName) != null) {
Markers marker = new Markers(new LatLng(id.getDouble("latitude"), id.getDouble("longitude")), id.getString(Controller.CAT_NAME), id.getString(Controller.ID), id.getString(Controller.SUBSCRIPTION), pinMap.get(catName), id.getString(Controller.TITLE), id.getString(Controller.COMPANY_NAME), id.getString(Controller.WWW), id.getString(Controller.STREET), id.getString(Controller.HOUSE_NUMBER), id.getString(Controller.HOUSE_ADD));
((Map<String,Object>) companyMap.get(catName)).put(id.getString(Controller.TITLE), marker.markerInformationMap);
}
}
delegate.setCompanyHashMap(companyMap);
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
}
I guess you're missing the point of the AsyncTask
it's supposed to do all the work in doInBackground() and then use the onPostExecute to deliver it to the UI.
But what you're doing is doing the network operation on doInBackground and doing data parsing on onPostExecute.
Furthermore, a JSON object is a raw data that needs further parsing. You should do all the parsing on the background. For example, let's say your companyData is address, phone number, size and name. You could have a class like this (p.s. I'm writing all this without testing, there will be a little mistake here in there, but you'll get the idea):
public class CompanyData{
private String name, address, phone;
private int size;
public CompanyData(JsonObject jo){
name = jo.getString("name");
address = jo.getString("address");
phone = jo.getString("phone");
size = jo.getInt("size");
}
// put a bunch of get methods here...
// getName(), getAddress(), etc.
}
then on your 'protected Map doInBackground(String... urls) ' you complete the network operation, create the JsonArray, create a Map<String,CompanyData>, loop through the array creating CompanyData objects and placing them into the Map and return the map to your protected void onPostExecute(Map<String,CompanyData> result) and inside the post execute it's just pass this result to the UI.
happy coding.
I always doing something like this..
...
private ProgressDialog pDialog;
ArrayList<HashMap<String, String>> CompanyList;
JSONParser jParser = new JSONParser();
JSONArray Company = null;
static String url_all_company = "http://your_site/files.php";
....
private class CompanyData extends AsyncTask<Void, Void, Void> {
#Override
protected void onPreExecute() {
super.onPreExecute();
pDialog = new ProgressDialog(MainActivity.this);
pDialog.setMessage("Load data..");
pDialog.setIndeterminate(false);
pDialog.setCancelable(true);
pDialog.show();
}
#Override
protected Void doInBackground(Void... params) {
CompanyList = new ArrayList<HashMap<String, String>>();
// Building Parameters if any.. to fetching all data, don't declare any param
List<NameValuePair> param = new ArrayList<NameValuePair>();
param.add(new BasicNameValuePair("uid", uid));
// getting JSON string from URL
JSONObject json = jParser.makeHttpRequest(url_all_company, "POST", param);
// Check your log cat for JSON reponse
Log.d("All Company: ", json.toString());
try {
// Checking for SUCCESS TAG
int success = json.getInt(TAG_SUCCESS);
if (success == 1) {
// Company found
// Getting Array of Company
Company = json.getJSONArray(TAG_COMPANIES);
// looping through All Company
for (int i = 0; i < Company.length(); i++) {
JSONObject json = Company.getJSONObject(i);
// Storing each json item in variable
String id = json.getString(TAG_GID);
String name = json.getString(TAG_NAME);
String jml = json.getString(TAG_EMPLOYEE);
String deskripsi = json.getString(TAG_DESKRIPSI);
String logo = json.getString(TAG_LOGO);
// creating new HashMap
HashMap<String, String> map = new HashMap<String, String>();
// adding each child node to HashMap key => value
map.put(TAG_GID, id);
map.put(TAG_NAME, name);
map.put(TAG_EMPLOYEE, jml);
map.put(TAG_DESKRIPSI, deskripsi);
map.put(TAG_LOGO, logo);
// adding HashList to ArrayList
CompanyList.add(map);
}
} else {
// no CompanyList found
}
} catch (JSONException e) {
e.printStackTrace();
}
return null;
}
#Override
protected void onPostExecute(Void args) {
list=(ListView)findViewById(R.id.list);
// Getting adapter by passing data ArrayList
adapter=new LazyAdapter(MainActivity.this, CompanyList);
list.setAdapter(adapter);
pDialog.dismiss();
}
}

AsyncTask is cancelled at constructor

I have an asynctask that - when executed - is cancelled right away.
My class looks like this:
public class JSONParser extends AsyncTask<String, Void, JSONArray> {
private ListFragment fragment;
#Override
protected JSONArray doInBackground(String... strings) {
JSONArray ja = null;
String string = "";
try {
URL url = new URL(strings[0]);
BufferedReader br = new BufferedReader(new InputStreamReader(url.openStream()));
string = br.readLine();
ja = new JSONArray(string);
} catch (Exception e ) {
Log.w("Special", e.toString());
}
return ja;
}
public JSONParser(ListFragment fragment) {
this.fragment = fragment;
}
#Override
protected void onPostExecute(JSONArray jsonArray) {
try {
ArrayList<HashMap<String ,String>> datalist = new ArrayList<HashMap<String, String>>();
int i = 0;
while (i < jsonArray.length()) {
HashMap<String, String> map = new HashMap<String, String>();
JSONObject tool = jsonArray.getJSONObject(i);
map.put("id", tool.getInt("Id") + "");
map.put("name", tool.getString("Name"));
datalist.add(map);
i++;
}
fragment.setListAdapter(new SimpleAdapter(fragment.getActivity(), datalist, R.layout.tools_list, new String[] {"name"}, new int[] {R.id.text}));
} catch (Exception e) {
e.getMessage();
}
}
}
and from my fragment I'm calling it like this
AsyncTask task = new JSONParser(this).execute("http://10.0.2.2:1288/webservice/gettools.aspx");
Using the debugger I can see that as soon as the constructor is called, it skips to onCancelled() and returns. The URL is valid and working, I get no messages in the Log, and the JSON is valid.
Update: Also I have the required permission and OnCancelled() is called before it enters doInBackground(). doInBackground() is never called.
Any ideas?
I'm using IntelliJ and an AVD with Android 4.0.3.
Do you have set Internet permissions in your AndroidManifest?
Are you sure that in the doInBackground there is no exception fired?
Maybe it could be a better idea to also put the while (i < jsonArray.length()) part in the doInBackground :) (for performance)
Code to read String:
BufferedReader reader = new BufferedReader(yourInputStreamReader,8);
StringBuilder sb = new StringBuilder();
String line = null;
while ((line = reader.readLine()) != null) {
sb.append(line + "\n");
}
oehm...
you are creating your task with an activity object (this) (???)
AsyncTask task = new JSONParser(this).execute("http://10.0.2.2:1288/webservic /gettools.aspx");
but your task expects a View
public JSONParser(ListFragment fragment) {
im surprised that this doesnt throw an exception

Categories

Resources