从JSON对象填充Fragment ListVIew

时间:2015-07-26 15:26:33

标签: android json listview android-fragments android-handler

我不知道错误在哪里,logcat没有显示任何内容

应用程序无法启动,我只是收到应用程序停止了。它不会打开。

这个片段存在问题。我试图通过JOSN从免费天气API收到的数据填充listview。我使用自定义对象HourlyForecast,其中包含有关温度,降水量,天气图标和时间的数据。

public class Tab3 extends Fragment {
Typeface weatherFont;

TextView timeField;
TextView precipitationField;
TextView temperatureField;
TextView weatherIcon;
ListView listView;
MyAdapter adapter;

ArrayList<HourlyForecast> hourlyForecastArrayList = new ArrayList<>();

Handler handler;

@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    weatherFont = Typeface.createFromAsset(getActivity().getAssets(), "fonts/weather.ttf");
    updateWeatherData("Belgrade");


}

@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
    View v = inflater.inflate(R.layout.tab3, container, false);

    timeField = (TextView) v.findViewById(R.id.time_hourly_field);
    weatherIcon = (TextView) v.findViewById(R.id.weather_hourly_icon);
    precipitationField = (TextView) v.findViewById(R.id.precipitation_hourly_field);
    temperatureField = (TextView) v.findViewById(R.id.temperature_hourly_field);
    weatherIcon.setTypeface(weatherFont);
    listView = (ListView) v.findViewById(R.id.my_list);
    adapter = new MyAdapter(getActivity(), hourlyForecastArrayList);
    listView.setAdapter(adapter);


    return v;
}

private void updateWeatherData(final String city) {
    new Thread() {
        public void run() {
            final JSONObject json = RemoteFetch.getJSON(getActivity(), city, 2);
            if (json == null) {
                handler.post(new Runnable() {
                    public void run() {
                        Toast.makeText(getActivity(),
                                getActivity().getString(R.string.place_not_found),
                                Toast.LENGTH_LONG).show();
                    }
                });
            } else {
                handler.post(new Runnable() {
                    public void run() {
                        renderWeather(json);
                    }
                });
            }
        }
    }.start();
}

private void renderWeather(JSONObject json) {
    try {


        JSONArray listObjects = json.getJSONArray("list");
        for (int i = 0; i < listObjects.length(); i++) {
            DateFormat df = DateFormat.getDateTimeInstance();
            String time = df.format(new Date(json.getLong("dt") * 1000));

            String precipitation = listObjects.getJSONObject(i).getString("rain");

            String temperature = listObjects.getJSONObject(i).getJSONObject("main").getString("temp");

            int weatherIconId = listObjects.getJSONObject(i).getJSONArray("weather").getInt(0);

            HourlyForecast hourlyForecast = new HourlyForecast(time, precipitation, temperature, weatherIconId);
            hourlyForecastArrayList.add(hourlyForecast);

        }


    } catch (Exception e) {
        Log.e("SimpleWeather", "One or more fields not found in the JSON data");
        Toast.makeText(getActivity(), "No JSON data found", Toast.LENGTH_LONG).show();
    }
}

private void setWeatherIcon(int actualId, int day_night) {
    int id = actualId / 100;
    String icon = "";
    if (actualId == 800) {
        long currentTime = new Date().getTime();
        if (day_night == 1) {
            icon = getActivity().getString(R.string.weather_sunny);
        } else if (day_night == 2) {
            icon = getActivity().getString(R.string.weather_clear_night);
        }
    } else {
        switch (id) {
            case 2:
                icon = getActivity().getString(R.string.weather_thunder);
                break;
            case 3:
                icon = getActivity().getString(R.string.weather_drizzle);
                break;
            case 7:
                icon = getActivity().getString(R.string.weather_foggy);
                break;
            case 8:
                icon = getActivity().getString(R.string.weather_cloudy);
                break;
            case 6:
                icon = getActivity().getString(R.string.weather_snowy);
                break;
            case 5:
                icon = getActivity().getString(R.string.weather_rainy);
                break;
        }
    }
    weatherIcon.setText(icon);
}




class MyAdapter extends ArrayAdapter<HourlyForecast> {
    ArrayList<HourlyForecast> hourlyForecastArrayListInAdapter = new ArrayList<>();

    public MyAdapter(Context context, ArrayList<HourlyForecast> hourlyForecasts) {
        super(context, R.layout.row_hourly);
        hourlyForecastArrayListInAdapter = hourlyForecasts;
    }

    @Override
    public View getView(int position, View convertView, ViewGroup parent) {
        LayoutInflater inflater = getActivity().getLayoutInflater();
        View rowView = inflater.inflate(R.layout.row_hourly, null, true);

        HourlyForecast forecastInAdapter = hourlyForecastArrayListInAdapter.get(position);
        timeField.setText(forecastInAdapter.getTime());
        precipitationField.setText(forecastInAdapter.getPrecipitation());
        temperatureField.setText(forecastInAdapter.getTemperature());


        setWeatherIcon(forecastInAdapter.getWeatherIconId(), 1);


        return rowView;
    }
}

}

这是一个logcat

java.lang.NullPointerException
        at com.slobx.slobodan.weathermob.Tab3.onCreateView(Tab3.java:61)
        at android.support.v4.app.Fragment.performCreateView(Fragment.java:1789)
        at android.support.v4.app.FragmentManagerImpl.moveToState(FragmentManager.java:955)
        at android.support.v4.app.FragmentManagerImpl.moveToState(FragmentManager.java:1138)
        at android.support.v4.app.BackStackRecord.run(BackStackRecord.java:740)
        at android.support.v4.app.FragmentManagerImpl.execPendingActions(FragmentManager.java:1501)
        at android.support.v4.app.FragmentManagerImpl.executePendingTransactions(FragmentManager.java:490)
        at android.support.v4.app.FragmentStatePagerAdapter.finishUpdate(FragmentStatePagerAdapter.java:163)
        at android.support.v4.view.ViewPager.populate(ViewPager.java:1105)
        at android.support.v4.view.ViewPager.populate(ViewPager.java:951)
        at android.support.v4.view.ViewPager.onMeasure(ViewPager.java:1473)
        at android.view.View.measure(View.java:15172)
        at android.widget.LinearLayout.measureVertical(LinearLayout.java:833)
        at android.widget.LinearLayout.onMeasure(LinearLayout.java:574)
        at android.view.View.measure(View.java:15172)
        at android.view.ViewGroup.measureChildWithMargins(ViewGroup.java:4814)
        at android.widget.FrameLayout.onMeasure(FrameLayout.java:310)
        at android.support.v7.internal.widget.ContentFrameLayout.onMeasure(ContentFrameLayout.java:124)
        at android.view.View.measure(View.java:15172)
        at android.view.ViewGroup.measureChildWithMargins(ViewGroup.java:4814)
        at android.widget.LinearLayout.measureChildBeforeLayout(LinearLayout.java:1390)
        at android.widget.LinearLayout.measureVertical(LinearLayout.java:681)
        at android.widget.LinearLayout.onMeasure(LinearLayout.java:574)
        at android.view.View.measure(View.java:15172)
        at android.view.ViewGroup.measureChildWithMargins(ViewGroup.java:4814)
        at android.widget.FrameLayout.onMeasure(FrameLayout.java:310)
        at android.view.View.measure(View.java:15172)
        at android.view.ViewGroup.measureChildWithMargins(ViewGroup.java:4814)
        at android.widget.LinearLayout.measureChildBeforeLayout(LinearLayout.java:1390)
        at android.widget.LinearLayout.measureVertical(LinearLayout.java:681)
        at android.widget.LinearLayout.onMeasure(LinearLayout.java:574)
        at android.view.View.measure(View.java:15172)
        at android.view.ViewGroup.measureChildWithMargins(ViewGroup.java:4814)
        at android.widget.FrameLayout.onMeasure(FrameLayout.java:310)
        at com.android.internal.policy.impl.PhoneWindow$DecorView.onMeasure(PhoneWindow.java:2148)
        at android.view.View.measure(View.java:15172)
        at android.view.ViewRootImpl.performMeasure(ViewRootImpl.java:1848)
        at android.view.ViewRootImpl.measureHierarchy(ViewRootImpl.java:1100)
        at android.view.ViewRootImpl.performTraversals(ViewRootImpl.java:1273)
        at android.view.ViewRootImpl.doTraversal(ViewRootImpl.java:998)
        at android.view.ViewRootImpl$TraversalRunnable.run(ViewRootImpl.java:4212)
        at android.view.Choreographer$CallbackRecord.run(Choreographer.java:725)
        at android.view.Choreographer.doCallbacks(Choreographer.java:555)
        at android.view.Choreographer.doFrame(Choreographer.java:525)
        at android.view.Choreographer$FrameDisplayEventReceiver.run(Choreographer.java:711)
        at android.os.Handler.handleCallback(Handler.java:615)
        at android.os.Handler.dispatchMessage(Handler.java:92)
        at android.os.Looper.loop(Looper.java:137)
        at android.app.ActivityThread.main(ActivityThread.java:4745)
        at java.lang.reflect.Method.invokeNative(Native Method)
        at java.lang.reflect.Method.invoke(Method.java:511)
        at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:786)
        at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:553)
        at dalvik.system.NativeStart.main(Native Method)

1 个答案:

答案 0 :(得分:0)

这可能来自NullPointerException无法实例化TextView

检查您的布局R.layout.tab3,确保ID TextView的{​​{1}}确实存在。