Anonymous Anonymous - 2 months ago 23
Android Question

Arrayadapter add method not accepting string values

I am running an app on Android Studio and while adding string values to arrayadapter object, I get null pointer exception. My exact relevant code is:

protected void onPostExecute(String[] result) {

List<String> wordList = new ArrayList<>();
wordList = Arrays.asList(result);
if(wordList!= null)
{
for(String forecast: wordList)
{
Log.v(LOG_TAG,"forecast value: "+forecast);
mForecastAdapter.add(forecast);
}
// mForecastAdapter.addAll(wordList);

}
Log.v(LOG_TAG,"Sorry!! Result is null");

}


I tried with
addAll()
method as well, but for that I need to upgrade to API 11. So that is not an option. For Information: This result variable is not empty and in logs, I do get correct value of forecast every time I execute this set of code.
The exception that I get is:
java.lang.NullPointerException: Attempt to invoke virtual method 'void android.widget.ArrayAdapter.add(java.lang.Object)' on a null object reference

Here's my code:

package com.example.khatri.sunshine.app;

import android.net.Uri;
import android.os.AsyncTask;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.text.format.Time;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.ListView;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
public class ForecastFragment extends Fragment {
String[] resultfinal = new String[100];
public ForecastFragment() {
}
ArrayAdapter<String> mForecastAdapter;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
// Add this line in order for this fragment to handle menu events.
setHasOptionsMenu(true);
}

@Override
public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {
inflater.inflate(R.menu.forecastfragment, menu);
}

@Override
public boolean onOptionsItemSelected(MenuItem item) {

int id = item.getItemId();
if (id == R.id.action_refresh) {

FetchWeatherTask fetchWeatherTask = new FetchWeatherTask();
fetchWeatherTask.execute("94043");
}
return super.onOptionsItemSelected(item);
}

@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {

View rootView = inflater.inflate(R.layout.fragment_main, container, false);
List<String> weekForecast = new ArrayList<String>();
weekForecast.add("Today-Sunny-88/63");
weekForecast.add("Tomorrow FOggy 77/46");
weekForecast.add("Day after sunny again 45/34");
weekForecast.add("Thur-foggy again 65/34");
weekForecast.add("Fri afternoon rainy 76/32");
weekForecast.add("Sat happy sat 65/12");
weekForecast.add("Day after sunny again 45/34");
weekForecast.add("Thur-foggy again 65/34");
weekForecast.add("Fri afternoon rainy 76/32");
weekForecast.add("Sat happy sat 65/12");

ArrayAdapter<String> mForecastAdapter = new ArrayAdapter<String>(
getContext(),
R.layout.list_item_forecast,
R.id.list_item_forecast_textview,
weekForecast);

ListView listView = (ListView) rootView.findViewById(R.id.listview_forecast);
listView.setAdapter(mForecastAdapter);


return rootView;

}

public class FetchWeatherTask extends AsyncTask<String, Void, String[]> {
private final String LOG_TAG = FetchWeatherTask.class.getSimpleName();

protected String[] doInBackground(String... params) {

HttpURLConnection urlConnection = null;
BufferedReader reader = null;

// Will contain the raw JSON response as a string.
String forecastJsonStr = null;

String format = "json";
String units = "metric";
int numDays = 7;
String appid = "c70ffaa8bf3c10556dc3e82d72d23677";

try {

final String FORECAST_BASE_URL = "http://api.openweathermap.org/data/2.5/forecast/daily?";
final String FORMAT_PARAM = "mode";
final String QUERY_PARAM = "q";
final String UNITS_PARAM = "units";
final String DAYS_PARAM = "cnt";
final String APPID_PARAM = "appid";

Uri builtUri = Uri.parse(FORECAST_BASE_URL).buildUpon()
.appendQueryParameter(QUERY_PARAM, params[0])
.appendQueryParameter(FORMAT_PARAM, format)
.appendQueryParameter(UNITS_PARAM, units)
.appendQueryParameter(DAYS_PARAM, Integer.toString(numDays))
.appendQueryParameter(APPID_PARAM, appid)
.build();

URL url = new URL(builtUri.toString());

Log.v(LOG_TAG, "Built URI " + builtUri.toString());

// 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) {

buffer.append(line + "\n");
}

if (buffer.length() == 0) {
// Stream was empty. No point in parsing.
forecastJsonStr = null;
}
forecastJsonStr = buffer.toString();

Log.v(LOG_TAG, "forecast JSON string: " + forecastJsonStr);
} catch (Exception e) {
Log.e("PlaceholderFragment", "Error ", e);

forecastJsonStr = null;
} finally {
if (urlConnection != null) {
urlConnection.disconnect();
}
if (reader != null) {
try {
resultfinal = getWeatherDataFromJson(forecastJsonStr, numDays);
reader.close();
} catch (final IOException e) {
Log.e("PlaceholderFragment", "Error closing stream", e);
}
catch (JSONException jsonexception)
{
Log.e(LOG_TAG,"JSON Exception",jsonexception);
}
}
}
return resultfinal;
}



private String getReadableDateString(long time) {
SimpleDateFormat shortenedDateFormat = new SimpleDateFormat("EEE MMM dd");
return shortenedDateFormat.format(time);
}

private String formatHighLows(double high, double low) {
// For presentation, assume the user doesn't care about tenths of a degree.
long roundedHigh = Math.round(high);
long roundedLow = Math.round(low);

String highLowStr = roundedHigh + "/" + roundedLow;
return highLowStr;
}


private String[] getWeatherDataFromJson(String forecastJsonStr, int numDays)
throws JSONException {

// These are the names of the JSON objects that need to be extracted.
final String OWM_LIST = "list";
final String OWM_WEATHER = "weather";
final String OWM_TEMPERATURE = "temp";
final String OWM_MAX = "max";
final String OWM_MIN = "min";
final String OWM_DESCRIPTION = "main";

JSONObject forecastJson = new JSONObject(forecastJsonStr);
JSONArray weatherArray = forecastJson.getJSONArray(OWM_LIST);


Time dayTime = new Time();
dayTime.setToNow();


int julianStartDay = Time.getJulianDay(System.currentTimeMillis(), dayTime.gmtoff);


dayTime = new Time();

String[] resultStrs = new String[numDays];
for(int i = 0; i < weatherArray.length(); i++) {
// For now, using the format "Day, description, hi/low"
String day;
String description;
String highAndLow;

// Get the JSON object representing the day
JSONObject dayForecast = weatherArray.getJSONObject(i);

// The date/time is returned as a long. We need to convert that
// into something human-readable, since most people won't read "1400356800" as
// "this saturday".
long dateTime;
// Cheating to convert this to UTC time, which is what we want anyhow
dateTime = dayTime.setJulianDay(julianStartDay+i);
day = getReadableDateString(dateTime);

// description is in a child array called "weather", which is 1 element long.
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_TEMPERATURE);
double high = temperatureObject.getDouble(OWM_MAX);
double low = temperatureObject.getDouble(OWM_MIN);

highAndLow = formatHighLows(high, low);
resultStrs[i] = day + " - " + description + " - " + highAndLow;

}

for (String s : resultStrs) {
Log.v(LOG_TAG, "Forecast entry: " + s);
}
//onPostExecute(resultStrs);

return resultStrs;



}

@Override
protected void onPostExecute(String[] result) {

List<String> wordList = new ArrayList<>();
wordList = Arrays.asList(result);
if(wordList!= null)
{

// mForecastAdapter.add(result.toString());
for(String forecast: wordList)
{
Log.v(LOG_TAG,"forecast value: "+forecast);
mForecastAdapter.add(forecast);
}
// mForecastAdapter.addAll(wordList);

}
Log.v(LOG_TAG,"Sorry!! Reuslt is null");

}


}


}

Answer

when you take global variable then you just initialize first time and you use in you whole class. I hope this will help you and you got your solution.

public class ForecastFragment extends Fragment {

        ArrayAdapter<String> mForecastAdapter;


        @Override
        public View onCreateView(LayoutInflater inflater, ViewGroup container,Bundle savedInstanceState) {

        ......
        mForecastAdapter = new ArrayAdapter<String>(
                            getContext(),
                            R.layout.list_item_forecast,
                            R.id.list_item_forecast_textview,
                            weekForecast);

        .....       
        }
    }
Comments