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

slider on android home screen
The toLowerCase() Method appears to not work [closed]
Package does not exist when refrencing a java module Android Studio 1.0.1
GroupLayout does not give required result
error highlight in eclipse only partially works
How to Read the data from 2 sheets of same Excel document using Selenium Web driver using TestNG in Java
String with value null and memory allocation [duplicate]
Observed weird behavior with #javax.ws.rs.Encoded
How to get rid of implementing Parcelable for each class in android in order to use it for put extra array list
How do you refresh data in an observable array list?
Java - Hibernate connection database
Creating a list of links with a loop in wicket
Ant build failing when upgrading to weblogic 10.3.6
Does calling new Object( ); twice make the object created by first call eligible for garbage collection?
How to handle this class visibility issue?
How would I go about replacing everything in between multiple layers of parentheses? [duplicate]

Categories

HOME
vim
google-chrome-extension
date
wso2
webpack
cookies
path-finding
hashmap
vmware
relay
octobercms
xmpp
setup-deployment
twitter-bootstrap-4
survey
google-project-tango
callback
angular-ui-bootstrap
alpha
serverspec
contact
cloudkit
nano-server
fancybox-3
numeral.js
php-7.1
worldwind
saxon
shared-hosting
nodatime
introduction
visjs
jasonette
devops
tdd
qhull
pepper
social-media
ping
facebook-apps
libuv
delicious-api
librato
javascriptcore
iframe-resizer
copying
lxd
gammu
cloud-code
dosbox
arena-simulation
wso2carbon
chain-builder
theming
alphabet
idisposable
gabor-filter
lync-client-sdk
django-scheduler
smart-table
rotativa
url-masking
intrusion-detection
player
clang-static-analyzer
jwplayer7
php-internals
goose
tform
tcpserver
execute
jms2
rgeo
drawbitmap
interrupted-exception
skos
e10s
device-orientation
facebook-graph-api-v2.4
gwidgets
tt-news
code-access-security
php-5.4
has-many-through
fluentautomation
android-2.2-froyo
dotnetnuke-5
gridcontrol
mylyn
comaddin
type-equivalence
drools-planner
pvrtc
simba
sublist
tridion-worldserver
errai
ticoredatasync
chrono
wse3.0
boost-filesystem
servicehost
appender
w3wp.exe
fluent-interface
paster
dentrix
ext3
temporal-database
project-hosting
thread-local-storage

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