ListView不会显示片段中的任何数据

时间:2017-07-13 14:20:28

标签: android listview android-fragments simplecursoradapter

我正在尝试实现从数据库获取数据并显示它的SimpleCursorAdapter。直到现在我使用的ArrayAdapter完美无缺。 但是因为我更改了CursorAdapter的代码,所以它在片段上没有显示任何内容。 Cursor将数据存储在ListView

这里是片段类(虽然有很多代码):

public class ForecastFragment extends Fragment implements LoaderManager.LoaderCallbacks<Cursor> 
{


    //ArrayAdapter<String>  mForecastAdapter;
    /**Change to cursor Adapter*/
    SimpleCursorAdapter mForecastAdapter;
    String Cityname;
    /*Loader Id**/
    private String mLocation;
    private final static int FORECAST_LOADER = 0;

    // Projection columns
    private static final String[] FORECAST_COLUMNS = {
            WeatherEntry.TABLE_NAME + "." + WeatherEntry._ID,
            WeatherEntry.COLUMN_DATE,
            WeatherEntry.COLUMN_SHORT_DESC,
            WeatherEntry.COLUMN_MAX_TEMP,
            WeatherEntry.COLUMN_MIN_TEMP,
            WeatherContract.LocationEntry.COLUMN_LOCATION_SETTING,
            WeatherEntry.COLUMN_WEATHER_ID,
            WeatherContract.LocationEntry.COLUMN_COORD_LAT,
            WeatherContract.LocationEntry.COLUMN_COORD_LONG
    };
  // Indices for forecast column
    static final int COL_WEATHER_ID = 0;
    static final int COL_WEATHER_DATE=1;
    static final int COL_WEATHER_DESC=2;
    static final int COL_WEATHER_MAX_TEMP=3;
    static final int COL_WEATHER_MIN_TEMP = 4;
    static final int COL_LOCATION_SETTING =5;
    static final int COL_WEATHER_CONDITION_ID=6;
    static final int COL_COORD_LAT =7;
    static final int COL_COORD_LONG =8;



    public ForecastFragment(){

    }

    @Override
    public void onActivityCreated(@Nullable Bundle savedInstanceState) {
        super.onActivityCreated(savedInstanceState);
        getLoaderManager().initLoader(FORECAST_LOADER,null,this);
    }
    @Override
    public void onCreate(Bundle savedInstanceState){
        super.onCreate(savedInstanceState);
        setHasOptionsMenu(true);
    }

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

    private void updateWeather(){
        FetchWeatherTask weatherTask = new FetchWeatherTask(getContext());
        SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(getActivity());
        String location = prefs.getString(getString(R.string.pref_location_key),getString(R.string.pref_location_default));
        weatherTask.execute(location);
        //  weatherTask.execute("201014");
        //return true;
    }

    @Override
    public void onStart() {
        super.onStart();
        updateWeather();
    }



    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        int id=item.getItemId();
        if(id==R.id.action_refresh)
        {
            updateWeather();
        }
        return super.onOptionsItemSelected(item);
    }


    @Override
    public String toString() {
        return super.toString();
    }

    @Override
    public Loader<Cursor> onCreateLoader(int id, Bundle args)
    {
       /* String locationSetting = Utility.getPreferredLocation(getActivity());


        //Sort Order ; ASC(Date)
        String sortOrder = WeatherEntry.COLUMN_DATE + "ASC";
        Uri weatherForLocationUri = WeatherEntry.buildWeatherLocationWithStartDate(locationSetting, System.currentTimeMillis());*/

        String startDate = WeatherContract.getDbDateString(new java.util.Date());

        // Sort order: Ascending, by date
        String sortOrder = WeatherEntry.COLUMN_DATE + " ASC";

        mLocation = Utility.getPreferredLocation(getActivity());
        Uri weatherForLocationUri = WeatherEntry.buildWeatherLocationWithStartDate(mLocation, System.currentTimeMillis()/*startDate*/);

        return new CursorLoader(getActivity()
                ,weatherForLocationUri
                ,FORECAST_COLUMNS
                ,null
                ,null
                ,sortOrder);

    }

    @Override
    public void onLoadFinished(Loader<Cursor> loader, Cursor data) {
        mForecastAdapter.swapCursor(data);
    }

    @Override
    public void onLoaderReset(Loader<Cursor> loader) {
        mForecastAdapter.swapCursor(null);

    }

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

        String [] forecastArray = {
                "today-sunny-88/63",
                "tomorrow-foggy-70/40",
                "weds-cloudy-72/63",
                "thurs-asteroids-75/65",
                "fri-heavy rain-65/56",
                "sat-day off - 55/55",
                "sun - i dont know- 80/68"
        };

        List<String> weekForecast = new ArrayList<String>(Arrays.asList(forecastArray));

       /* //ArrayAdapter<String>
                mForecastAdapter = new ArrayAdapter<String>(
            //The current context (parent activity)
                getActivity(),

            // ID of list item layout
            R.layout.list_item_forecast,
            // ID of text view
            R.id.list_item_forecast_textview,
            // list of data
            weekForecast
        );*/

       mForecastAdapter = new SimpleCursorAdapter(
               //The current context (parent activity)
               getActivity(),

               // ID of list item layout
               R.layout.list_item_forecast,
               null,
               //column nmaes
               new String[]{
                       WeatherEntry.COLUMN_DATE,
                       WeatherEntry.COLUMN_SHORT_DESC,
                       WeatherEntry.COLUMN_MAX_TEMP,
                       WeatherEntry.COLUMN_MIN_TEMP},

               // ID of text view
               new int[]{
                       R.id.list_item_date_textview,
                       R.id.list_item_forecast_textview,
                       R.id.list_item_high_textview,
                       R.id.list_item_low_textview

               },0

       );
      // forecast bind
        mForecastAdapter.setViewBinder(new SimpleCursorAdapter.ViewBinder() {
            @Override
            public boolean setViewValue(View view, Cursor cursor, int columnIndex) {
                boolean isMetric = Utility.isMetric(getActivity());
                switch (columnIndex) {
                    case COL_WEATHER_MAX_TEMP:
                    case COL_WEATHER_MIN_TEMP:
                        // we have to do some formatting and possibly a conversion
                        ((TextView) view).setText(Utility.formatTemperature(cursor.getDouble(columnIndex), isMetric));
                        return true;
                    case COL_WEATHER_DATE:
                        String dateString = cursor.getString(columnIndex);
                        TextView dateView = (TextView) view;
                        dateView.setText(Utility.formatDate(dateString));
                        return true;
                }

                // If return false, 2 types of binding will occur
                // 1: view is a TextView, SimpleCursorAdapter#setViewText(TextView, String) is called
                // 2: view is a ImageView, SimpleCursorAdapter#setViewImage(ImageView v, String value) is called
                return false;
            }
        });


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

        // for clicking
        listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> adapterView, View view, int position, long l)
            {
               /* String forecast = mForecastAdapter.getItem(position);
               // Toast.makeText(getActivity(),forecast, Toast.LENGTH_SHORT).show();

                Intent intent = new Intent(getActivity(),DetailActivity.class)
                        .putExtra(Intent.EXTRA_TEXT,forecast);

                startActivity(intent);*/

            }
        });


        return rootView;
    }
}

这里是list_item_forecast.xml:

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:minHeight="?android:attr/listPreferredItemHeight"
    android:gravity="center_vertical"
    android:orientation="horizontal"
    >

    <TextView
        android:id="@+id/list_item_date_textview"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:minHeight="?android:attr/listPreferredItemHeight"
        android:gravity="center_vertical"
        android:text="TextView" />

    <TextView
        android:id="@+id/list_item_empty"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_weight="0.08"
        android:minHeight="?android:attr/listPreferredItemHeight"
        android:gravity="center_vertical"
        android:text="-" />

    <TextView
        android:id="@+id/list_item_forecast_textview"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:minHeight="?android:attr/listPreferredItemHeight"
        android:gravity="center_vertical"
        android:layout_weight="0.08"
        />

    <TextView
        android:id="@+id/list_item_emptyview"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:minHeight="?android:attr/listPreferredItemHeight"
        android:gravity="center_vertical"
        android:layout_weight="0.08"
        android:text="-" />

    <TextView
        android:id="@+id/list_item_high_textview"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:minHeight="?android:attr/listPreferredItemHeight"
        android:gravity="center_vertical"
        android:layout_weight="0.08"
         />

    <TextView
        android:id="@+id/list_item_slash"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:minHeight="?android:attr/listPreferredItemHeight"
        android:gravity="center_vertical"
        android:layout_weight="0.08"
        android:text="/" />

    <TextView
        android:id="@+id/list_item_low_textview"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:minHeight="?android:attr/listPreferredItemHeight"
        android:gravity="center_vertical"
        android:layout_weight="0.08"
         />

</LinearLayout>

没有错误。 Logcat显示已从数据库中正确获取数据。 数据库和其他功能正常工作。我只是看不到片段上的任何数据。

有人能帮助我吗?

1 个答案:

答案 0 :(得分:0)

也许你和我犯了同样的错误。片段默认textColor为白色,图像的可见性不可见。因此,您应将文本颜色设置为黑色,并将可见性属性设置为可见;