java


Not able to return string array in AsycTask


If I change to string then it returning string value. But i can't figure out why it is not returning string value. I check all still unable to get it.
Where is my mistake? Thanks in advance.
public class FetchWeatherTask extends AsyncTask<String, Void, String[]> {
private final String LOG_TAG=FetchWeatherTask.class.getSimpleName();
private String[] getWeatherDataFromJson(String forecastJsonStr)
throws JSONException {
// These are the names of the JSON objects that need to beextracted.
final String OWM_LIST = "list";
final String OWM_WEATHER = "weather";
final String OWM_TEMPERATURE = "temp";
final String OWM_MAX = "temp_max";
final String OWM_MIN = "temp_min";
final String OWM_DESCRIPTION = "main";
JSONObject forecastJson = new JSONObject(forecastJsonStr);
JSONArray weatherArray = forecastJson.getJSONArray(OWM_LIST);
JSONObject city=forecastJson.getJSONObject("city");
String name=city.getString("name");
String[] resultStrs = null;
for(int i = 0; i < weatherArray.length(); i++) {
// For now, using the format "Day, description, hi/low"
String description;
JSONObject weatherObject=dayForecast.getJSONArray(OWM_WEATHER).getJSONObject(0);
description = weatherObject.getString(OWM_DESCRIPTION);
// Temperatures are in a child object called "temp". Try not to name variables
// "temp" when working with temperature. It confuses everybody.
JSONObject temperatureObject = dayForecast.getJSONObject(OWM_DESCRIPTION);
double high = temperatureObject.getDouble(OWM_MAX);
double low = temperatureObject.getDouble(OWM_MIN);
highAndLow = formatHighLows(high, low);
//resultStrs[i] = description + " - " + highAndLow;
resultStrs[i]=name;
}
for (String s : resultStrs) {
Log.v(LOG_TAG, "Forecast entry: " + s);
}
return resultStrs;
}
doinbackground also in string[]
#Override
protected String[] doInBackground(String... params) {
//if there is no zip code nothing to look it
if (params.length == 0) {
return null;
}
// These two need to be declared outside the try/catch
// so that they can be closed in the finally block.
HttpURLConnection urlConnection = null;
BufferedReader reader = null;
// Will contain the raw JSON response as a string.
String forecastJsonStr = null;
String appid = "bc1";
try {
// Construct the URL for the OpenWeatherMap query
// Possible parameters are available at OWM's forecast API page, at
// http://openweathermap.org/API#forecast
final String FORECAST_BASE_URL = "http://api.openweathermap.org/data/2.5/forecast/daily?";
final String QUERY_PARAM = "id";
final String APPID = "APPID";
Uri builturi = Uri.parse(FORECAST_BASE_URL).buildUpon()
.appendQueryParameter(QUERY_PARAM, params[0])
.appendQueryParameter(APPID, appid)
.build();
URL URl;
URl = new URL(builturi.toString());
Log.v(LOG_TAG, "BUILT URI" + builturi.toString());
// URL url = new URL("http://api.openweathermap.org/data/2.5/forecast/city?id=524901&APPID=bc16214cbb434f8386d9b0c3d7eebc17");
// Create the request to OpenWeatherMap, and open the connection
urlConnection=(HttpURLConnection) URl.openConnection();
urlConnection.setRequestMethod("GET");
urlConnection.connect();
// Read the input stream into a String
InputStream inputStream = urlConnection.getInputStream();
StringBuffer buffer = new StringBuffer();
if (inputStream == null) {
// Nothing to do.
forecastJsonStr = null;
}
reader = new BufferedReader(new InputStreamReader(inputStream));
String line;
while ((line = reader.readLine()) != null) {
// Since it's JSON, adding a newline isn't necessary (it won't affect parsing)
// But it does make debugging a *lot* easier if you print out the completed
// buffer for debugging.
buffer.append(line + "\n");
}
if (buffer.length() == 0) {
// Stream was empty. No point in parsing.
forecastJsonStr = null;
}
if (buffer.length()!=0){forecastJsonStr = buffer.toString();}
} catch (ProtocolException e) {
e.printStackTrace();
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
Log.e("PlaceholderFragment", "Error ", e);
// If the code didn't successfully get the weather data, there's no point in attempting
// to parse it.
//forecastJsonStr = null;
} finally {
if (urlConnection != null) {
urlConnection.disconnect();
}
if (reader != null) {
try {
reader.close();
} catch (final IOException e) {
Log.e("PlaceholderFragment", "Error closing stream", e);
}
}
}
try {
return getWeatherDataFromJson(forecastJsonStr);
} catch (JSONException e) {
e.printStackTrace();
}
//this will happen if there was an error getting or parsing the document
return null;
}
#Override
protected void onPostExecute(String[] result) {
if (result!=null){
Toast.makeText(getActivity(),"working", Toast.LENGTH_LONG).show();
arrayAdapter.clear();
for (String dayforcast:result){
arrayAdapter.add(dayforcast);
}
}
//i used to figure out it is working or not
// not much significance
if (result==null){
Toast.makeText(getActivity(),"not working", Toast.LENGTH_LONG).show();
}
}
}
//Onpost in string[],asyctask also string[],dolnbackground also string[]
Try to call notifyDataSetChanged on your arrayadapter in onPostExecute after you've added all of your dayforcast elements ;-)

Related Links

What is the recommended application layer to use in 3 tier architecture using Java?
Spring define property of interface no implementation
How to poll file from folder in FIFO order
Scanner hasNextLine() won't evaluate to false
Fast way to write a byte array into a file
Java CardLayout .show() not showing
Hibernate GeneratedValue using GenericGenerator is ignored
1D Array, multiples of 5. Simple but new to coding
Java: create custom exception class package.Exception
What's the point of using XML for Fragments?
Why we are creating variable of type of class?
Java serial reading program returns gibberish
Unable to call method in Different class . (Java/GWT)
SupportMapFragment loading on the main thread and freezing the interface (getMapAsync ignored)
Incorrect cursor when outside of modal JDialog?
How can I count specific word using mapreduce?

Categories

HOME
bluetooth
testng
webpack
dictionary
google-api-php-client
smarty
amazon-ecs
sharepoint-designer
jxls
enterprise-library-5
paradox
gnupg
vifm
numeral.js
collectd
orchardcms
django-simple-history
highlight.js
reactive-cocoa
sms-gateway
java-3d
errorlevel
functional-testing
csrf-protection
realex-payments-api
crystal-reports-2010
h2db
dynamic-featured-image
poltergeist
facebook-access-token
pingfederate
nhapi
filezilla
maxmind
typo3-6.2.x
facebook-apps
webkitspeechrecognition
socialengine
contact-form
karaf
google-qpx-express-api
kendo-ui-grid
wallpaper
io-redirection
file-format
vxworks
restlet
jquery-bootgrid
swisscomdev
ansible-playbook
azure-ml
squib
mapzen
fedex
jsch
avconv
azure-application-gateway
idisposable
diagnostics
linode
yt-project
url-pattern
mathematica-frontend
jwplayer7
skype4py
pickadate
bluemix-app-scan
hsv
collapse
security-testing
remobjects
p2
bigbluebutton
system.reflection
coldbox
android-imagebutton
java-metro-framework
device-manager
php-5.4
flask-cors
aapt
expected-exception
system.net.webexception
industrial
excel-2003
random-seed
plasma
wsdl-2.0
browser-detection
nsnetservice
bluepill
armcc
dotnethighcharts
infobox
yetanotherforum
visitor-statistic
site.master
castle-monorail
xetex
phonon
anti-piracy
genealogy

Resources

Mobile Apps Dev
Database Users
javascript
java
csharp
php
android
MS Developer
developer works
python
ios
c
html
jquery
RDBMS discuss
Cloud Virtualization
Database Dev&Adm
javascript
java
csharp
php
python
android
jquery
ruby
ios
html
Mobile App
Mobile App
Mobile App