Skip to content

Instantly share code, notes, and snippets.

@itsashis4u
Last active April 2, 2016 10:41
Show Gist options
  • Save itsashis4u/080d9859866382dcf1c069a0496a6230 to your computer and use it in GitHub Desktop.
Save itsashis4u/080d9859866382dcf1c069a0496a6230 to your computer and use it in GitHub Desktop.
ArrayAdapter error
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
android:id="@+id/WeatherFragmentContainer"
tools:context="com.example.sunshine.MainActivity">
</LinearLayout>
04-02 15:37:31.206 26307-26307/com.example.sunshine I/MainActivity: onOptionsItemSelected: Bhubaneswar, India
04-02 15:37:31.207 26307-26307/com.example.sunshine I/Executed: onOptionsItemSelected:
04-02 15:37:31.209 26307-27196/com.example.sunshine V/FetchWeatherTask: Built Urihttp://api.openweathermap.org/data/2.5/forecast/daily?q=Bhubaneswar%2C%20India%20&mode=json&units=metric&cnt=7&APPID=b12a1d9fc46f8e8b02f28bb2fa58dfe7
04-02 15:37:31.643 26307-27196/com.example.sunshine E/FetchWeatherTask: Forecast String {"city":{"id":1275817,"name":"Bhubaneshwar","coord":{"lon":85.833328,"lat":20.23333},"country":"IN","population":0},"cod":"200","message":0.0344,"cnt":7,"list":[{"dt":1459576800,"temp":{"day":31.38,"min":27.37,"max":31.38,"night":27.37,"eve":29.94,"morn":31.38},"pressure":1020.12,"humidity":73,"weather":[{"id":500,"main":"Rain","description":"light rain","icon":"10d"}],"speed":5.66,"deg":194,"clouds":8},{"dt":1459663200,"temp":{"day":31.92,"min":27.04,"max":32.07,"night":27.46,"eve":30.14,"morn":27.04},"pressure":1023.52,"humidity":72,"weather":[{"id":800,"main":"Clear","description":"clear sky","icon":"01d"}],"speed":6.71,"deg":210,"clouds":0},{"dt":1459749600,"temp":{"day":31.99,"min":27.8,"max":31.99,"night":28.36,"eve":29.95,"morn":27.8},"pressure":1022.18,"humidity":72,"weather":[{"id":800,"main":"Clear","description":"clear sky","icon":"01d"}],"speed":8.16,"deg":209,"clouds":0},{"dt":1459836000,"temp":{"day":35.16,"min":29.46,"max":35.16,"night":30.49,"eve":33.76,"morn":29.46},"pressure":1017.87,"humidity":0,"weather":[{"id":500,"main":"Rain","description":"light rain","icon":"10d"}],"speed":6.78,"deg":223,"clouds":24,"rain":0.43},{"dt":1459922400,"temp":{"day":35.92,"min":28.94,"max":35.92,"night":30.06,"eve":34.48,"morn":28.94},"pressure":1018.37,"humidity":0,"weather":[{"id":500,"main":"Rain","description":"light rain","icon":"10d"}],"speed":5.34,"deg":228,"clouds":6,"rain":0.26},{"dt":1460008800,"temp":{"day":35.93,"min":27.96,"max":35.93,"night":29.6,"eve":33.99,"morn":27.96},"pressure":1019.84,"humidity":0,"weather":[{"id":800,"main":"Clear","description":"clear sky","icon":"01d"}],"speed":3.71,"deg":202,"clouds":18},{"dt":1460095200,"temp":{"day":35.44,"min":28.61,"max":35.44,"night":28.99,"eve":33.36,"morn":28.61},"pressure":1020.84,"humidity":0,"weather":[{"id":500,"main":"Rain","description":"light rain","icon":"10d"}],"speed":3.42,"deg":225,"clouds":0,"rain":0.43}]}
04-02 15:37:31.643 26307-27196/com.example.sunshine V/FetchWeatherTask: doInBackground: {"city":{"id":1275817,"name":"Bhubaneshwar","coord":{"lon":85.833328,"lat":20.23333},"country":"IN","population":0},"cod":"200","message":0.0344,"cnt":7,"list":[{"dt":1459576800,"temp":{"day":31.38,"min":27.37,"max":31.38,"night":27.37,"eve":29.94,"morn":31.38},"pressure":1020.12,"humidity":73,"weather":[{"id":500,"main":"Rain","description":"light rain","icon":"10d"}],"speed":5.66,"deg":194,"clouds":8},{"dt":1459663200,"temp":{"day":31.92,"min":27.04,"max":32.07,"night":27.46,"eve":30.14,"morn":27.04},"pressure":1023.52,"humidity":72,"weather":[{"id":800,"main":"Clear","description":"clear sky","icon":"01d"}],"speed":6.71,"deg":210,"clouds":0},{"dt":1459749600,"temp":{"day":31.99,"min":27.8,"max":31.99,"night":28.36,"eve":29.95,"morn":27.8},"pressure":1022.18,"humidity":72,"weather":[{"id":800,"main":"Clear","description":"clear sky","icon":"01d"}],"speed":8.16,"deg":209,"clouds":0},{"dt":1459836000,"temp":{"day":35.16,"min":29.46,"max":35.16,"night":30.49,"eve":33.76,"morn":29.46},"pressure":1017.87,"humidity":0,"weather":[{"id":500,"main":"Rain","description":"light rain","icon":"10d"}],"speed":6.78,"deg":223,"clouds":24,"rain":0.43},{"dt":1459922400,"temp":{"day":35.92,"min":28.94,"max":35.92,"night":30.06,"eve":34.48,"morn":28.94},"pressure":1018.37,"humidity":0,"weather":[{"id":500,"main":"Rain","description":"light rain","icon":"10d"}],"speed":5.34,"deg":228,"clouds":6,"rain":0.26},{"dt":1460008800,"temp":{"day":35.93,"min":27.96,"max":35.93,"night":29.6,"eve":33.99,"morn":27.96},"pressure":1019.84,"humidity":0,"weather":[{"id":800,"main":"Clear","description":"clear sky","icon":"01d"}],"speed":3.71,"deg":202,"clouds":18},{"dt":1460095200,"temp":{"day":35.44,"min":28.61,"max":35.44,"night":28.99,"eve":33.36,"morn":28.61},"pressure":1020.84,"humidity":0,"weather":[{"id":500,"main":"Rain","description":"light rain","icon":"10d"}],"speed":3.42,"deg":225,"clouds":0,"rain":0.43}]}
04-02 15:37:31.657 26307-27196/com.example.sunshine V/FetchWeatherTask: Forecast entry: Sat Apr 02 - Rain - 31/27
04-02 15:37:31.657 26307-27196/com.example.sunshine V/FetchWeatherTask: Forecast entry: Sun Apr 03 - Clear - 32/27
04-02 15:37:31.657 26307-27196/com.example.sunshine V/FetchWeatherTask: Forecast entry: Mon Apr 04 - Clear - 32/28
04-02 15:37:31.657 26307-27196/com.example.sunshine V/FetchWeatherTask: Forecast entry: Tue Apr 05 - Rain - 35/29
04-02 15:37:31.657 26307-27196/com.example.sunshine V/FetchWeatherTask: Forecast entry: Wed Apr 06 - Rain - 36/29
04-02 15:37:31.657 26307-27196/com.example.sunshine V/FetchWeatherTask: Forecast entry: Thu Apr 07 - Clear - 36/28
04-02 15:37:31.657 26307-27196/com.example.sunshine V/FetchWeatherTask: Forecast entry: Fri Apr 08 - Rain - 35/29
04-02 15:37:31.657 26307-27196/com.example.sunshine V/FetchWeatherTask: doInBackground: Check result[Sat Apr 02 - Rain - 31/27, Sun Apr 03 - Clear - 32/27, Mon Apr 04 - Clear - 32/28, Tue Apr 05 - Rain - 35/29, Wed Apr 06 - Rain - 36/29, Thu Apr 07 - Clear - 36/28, Fri Apr 08 - Rain - 35/29]
04-02 15:37:31.657 26307-26307/com.example.sunshine V/FetchWeatherTask: onPostExecute: Check result object[Sat Apr 02 - Rain - 31/27, Sun Apr 03 - Clear - 32/27, Mon Apr 04 - Clear - 32/28, Tue Apr 05 - Rain - 35/29, Wed Apr 06 - Rain - 36/29, Thu Apr 07 - Clear - 36/28, Fri Apr 08 - Rain - 35/29]
04-02 15:37:31.658 26307-26307/com.example.sunshine D/AndroidRuntime: Shutting down VM
04-02 15:37:31.668 26307-26307/com.example.sunshine E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.example.sunshine, PID: 26307
java.lang.NullPointerException: Attempt to invoke virtual method 'void android.widget.ArrayAdapter.clear()' on a null object reference
at com.example.sunshine.WeatherFragment$FetchWeatherTask.onPostExecute(WeatherFragment.java:351)
at com.example.sunshine.WeatherFragment$FetchWeatherTask.onPostExecute(WeatherFragment.java:146)
at android.os.AsyncTask.finish(AsyncTask.java:651)
at android.os.AsyncTask.-wrap1(AsyncTask.java)
at android.os.AsyncTask$InternalHandler.handleMessage(AsyncTask.java:668)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:148)
at android.app.ActivityThread.main(ActivityThread.java:5443)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:728)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:618)
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
android:padding="@dimen/activity_horizontal_margin"
tools:context=".WeatherFragment">
<!-- TODO: Update blank fragment layout -->
<EditText
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:id="@+id/location_city"
android:hint="Enter the city for info"/>
<TextView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:padding="@dimen/activity_horizontal_margin"
android:text="Here follows a list"/>
<ListView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:id="@+id/listView1">
</ListView>
</LinearLayout>
package com.example.sunshine;
import android.net.Uri;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.widget.EditText;
public class MainActivity extends AppCompatActivity implements WeatherFragment.OnFragmentInteractionListener {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
if (savedInstanceState == null) {
getSupportFragmentManager()
.beginTransaction()
.add(R.id.WeatherFragmentContainer, new WeatherFragment())
.commit();
}
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.main, menu);
return super.onCreateOptionsMenu(menu);
}
@Override
public boolean onOptionsItemSelected(MenuItem item){
int id = item.getItemId();
if(id == R.id.action_refresh){
WeatherFragment w = new WeatherFragment();
w.locationCity = (EditText) findViewById(R.id.location_city);
String locale = w.locationCity.getText().toString();
WeatherFragment.FetchWeatherTask weatherTask = w.new FetchWeatherTask();
Log.i("MainActivity", "onOptionsItemSelected: "+locale);
weatherTask.execute(locale);
Log.i("Executed", "onOptionsItemSelected: ");
return true;
}
return super.onOptionsItemSelected(item);
}
@Override
public void onFragmentInteraction(Uri uri) {
}
}
package com.example.sunshine;
import android.content.Context;
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.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.EditText;
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.MalformedURLException;
import java.net.ProtocolException;
import java.net.URL;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
/**
* A simple {@link Fragment} subclass.
* Activities that contain this fragment must implement the
* {@link WeatherFragment.OnFragmentInteractionListener} interface
* to handle interaction events.
* Use the {@link WeatherFragment#newInstance} factory method to
* create an instance of this fragment.
*/
public class WeatherFragment extends Fragment {
// TODO: Rename parameter arguments, choose names that match
// the fragment initialization parameters, e.g. ARG_ITEM_NUMBER
private static final String ARG_PARAM1 = "param1";
private static final String ARG_PARAM2 = "param2";
private ArrayAdapter<String> mAdapter;
// TODO: Rename and change types of parameters
private String mParam1;
private String mParam2;
public EditText locationCity;
private OnFragmentInteractionListener mListener;
public WeatherFragment() {
// Required empty public constructor
}
/**
* Use this factory method to create a new instance of
* this fragment using the provided parameters.
*
* @param param1 Parameter 1.
* @param param2 Parameter 2.
* @return A new instance of fragment WeatherFragment.
*/
// TODO: Rename and change types and number of parameters
public static WeatherFragment newInstance(String param1, String param2) {
WeatherFragment fragment = new WeatherFragment();
Bundle args = new Bundle();
args.putString(ARG_PARAM1, param1);
args.putString(ARG_PARAM2, param2);
fragment.setArguments(args);
return fragment;
}
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
if (getArguments() != null) {
mParam1 = getArguments().getString(ARG_PARAM1);
mParam2 = getArguments().getString(ARG_PARAM2);
}
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
View view = inflater.inflate(R.layout.fragment_weather, container, false);
String[] forecastArray = {"Mon 6/23 - Sunny - 31/17",
"Tue 6/24 - Foggy - 21/8",
"Wed 6/25 - Cloudy - 22/17",
"Thurs 6/26 - Rainy - 18/11",
"Fri 6/27 - Foggy - 21/10",
"Sat 6/28 - TRAPPED IN WEATHERSTATION - 23/18",
"Sun 6/29 - Sunny - 20/7"};
List<String> weekForecast = new ArrayList<>(Arrays.asList(forecastArray));
mAdapter = new ArrayAdapter<>(getActivity(), android.R.layout.simple_list_item_1, weekForecast );
mAdapter.notifyDataSetChanged();
ListView listView = (ListView) view.findViewById(R.id.listView1);
Log.d("Log", "If listview is null "+listView);
listView.setAdapter(mAdapter);
return view;
}
@Override
public void onAttach(Context context) {
super.onAttach(context);
if (context instanceof OnFragmentInteractionListener) {
mListener = (OnFragmentInteractionListener) context;
} else {
throw new RuntimeException(context.toString()
+ " must implement OnFragmentInteractionListener");
}
}
@Override
public void onDetach() {
super.onDetach();
mListener = null;
}
/**
* This interface must be implemented by activities that contain this
* fragment to allow an interaction in this fragment to be communicated
* to the activity and potentially other fragments contained in that
* activity.
* <p/>
* See the Android Training lesson <a href=
* "http://developer.android.com/training/basics/fragments/communicating.html"
* >Communicating with Other Fragments</a> for more information.
*/
public interface OnFragmentInteractionListener {
// TODO: Update argument type and name
void onFragmentInteraction(Uri uri);
}
public class FetchWeatherTask extends AsyncTask<String, Void, String[]> {
private final String LOG_TAG = FetchWeatherTask.class.getSimpleName();
/* The date/time conversion code is going to be moved outside the asynctask later,
* so for convenience we're breaking it out into its own method now.
*/
private String getReadableDateString(long time){
// Because the API returns a unix timestamp (measured in seconds),
// it must be converted to milliseconds in order to be converted to valid date.
SimpleDateFormat shortenedDateFormat = new SimpleDateFormat("EEE MMM dd");
return shortenedDateFormat.format(time);
}
/**
* Prepare the weather high/lows for presentation.
*/
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);
return roundedHigh + "/" + roundedLow;
}
/**
* Take the String representing the complete forecast in JSON Format and
* pull out the data we need to construct the Strings needed for the wireframes.
*
* Fortunately parsing is easy: constructor takes the JSON string and converts it
* into an Object hierarchy for us.
*/
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);
// OWM returns daily forecasts based upon the local time of the city that is being
// asked for, which means that we need to know the GMT offset to translate this data
// properly.
// Since this data is also sent in-order and the first day is always the
// current day, we're going to take advantage of that to get a nice
// normalized UTC date for all of our weather.
Time dayTime = new Time();
dayTime.setToNow();
// we start at the day returned by local time. Otherwise this is a mess.
int julianStartDay = Time.getJulianDay(System.currentTimeMillis(), dayTime.gmtoff);
// now we work exclusively in UTC
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);
}
return resultStrs;
}
@Override
protected String[] doInBackground(String... params) {
if(params.length == 0){
return null;
}
HttpURLConnection urlConnection = null;
BufferedReader reader = null;
String format = "json";
String units = "metric";
int numDays = 7;
String forecastJSONStr = null;
try {
final String BASE_URL = "http://api.openweathermap.org/data/2.5/forecast/daily?";
final String QUERY_PARAM = "q";
final String FORMAT_PARAM = "mode";
final String UNITS_PARAM = "units";
final String COUNT_PARAM = "cnt";
final String APPID_PARAM = "APPID";
Uri builtUri = Uri.parse(BASE_URL).buildUpon()
.appendQueryParameter(QUERY_PARAM, params[0])
.appendQueryParameter(FORMAT_PARAM, format)
.appendQueryParameter(UNITS_PARAM, units)
.appendQueryParameter(COUNT_PARAM, Integer.toString(numDays))
.appendQueryParameter(APPID_PARAM, BuildConfig.OWMAPIKey)
.build();
URL url = new URL(builtUri.toString());
Log.v(LOG_TAG, "Built Uri"+ builtUri.toString());
urlConnection = (HttpURLConnection) url.openConnection();
urlConnection.setRequestMethod("GET");
urlConnection.connect();
InputStream inputStream = urlConnection.getInputStream();
StringBuilder buffer = new StringBuilder();
if(inputStream == null){
forecastJSONStr = null;
}
if(inputStream != null){
reader = new BufferedReader(new InputStreamReader(inputStream));
}
String line;
if(reader != null){
while((line = reader.readLine()) != null){
buffer.append(line).append('\n');
}
}
if(buffer.length() == 0){
forecastJSONStr = null;
}
forecastJSONStr = buffer.toString();
Log.e(LOG_TAG, "Forecast String " + forecastJSONStr);
} catch (ProtocolException | MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
Log.e(LOG_TAG, "onCreateView: Error", e);
forecastJSONStr = null;
}finally {
if(urlConnection != null){
urlConnection.disconnect();
}
if(reader != null){
try {
reader.close();
} catch (final IOException e) {
Log.e(LOG_TAG, "Error closing stream ", e);
}
}
}
try {
if(forecastJSONStr != null){
Log.v(LOG_TAG, "doInBackground: "+forecastJSONStr);
String[] results= getWeatherDataFromJson(forecastJSONStr, numDays);
Log.v(LOG_TAG, "doInBackground: Check result" +Arrays.toString(results));
return results;
// return getWeatherDataFromJson(forecastJSONStr, numDays);
}
else{
Log.e(LOG_TAG, "Check your internet!" );
}
}catch (JSONException e){
Log.e(LOG_TAG, e.getMessage(), e);
e.printStackTrace();
}
return null;
}
@Override
protected void onPostExecute(String[] result) {
Log.v(LOG_TAG, "onPostExecute: Check result object" + Arrays.toString(result));
Log.i(LOG_TAG, "onPostExecute: "+mAdapter);
mAdapter.clear();
mAdapter.addAll(result);
// if(result != null){
//// for(String dayForecastStr : result) {
//// mAdapter.add(dayForecastStr);
//// }
//
// }
// super.onPostExecute(result);
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment