带有SimpleCursorAdapter的ListView仅显示第一个值

时间:2014-09-29 18:51:02

标签: android listview simplecursoradapter

尝试从simplecursoradaptor填写listview,它将添加到视图中的所有内容是光标的第一个条目,尽管光标确实包含所有数据....

编辑:为了测试,我尝试将其更改为填充静态数据的ArrayAdapter,并获得相同的结果。

更多编辑:此外,我尝试使用ListFragment和android.R.layout.simple_list_item_1,但结果仍然相同。

它的代码是

AllWeeksFragment

import android.app.Activity;
import android.app.Fragment;
import android.content.Context;
import android.database.Cursor;
import android.graphics.Color;
import android.os.Bundle;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.ListView;
import android.widget.SimpleCursorAdapter;

import us.emanon.timecard.db.HoursDataSource;

public class AllWeeksFragment 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";

    // TODO: Rename and change types of parameters
    private String mParam1;
    private String mParam2;

    private OnFragmentInteractionListener mListener;

    private HoursDataSource dataSource = HoursDataSource.getInstance(getActivity());
    private Cursor mCursor;

    // TODO: Rename and change types of parameters
    public static AllWeeksFragment newInstance(String param1, String param2) {
        AllWeeksFragment fragment = new AllWeeksFragment();
        Bundle args = new Bundle();
        args.putString(ARG_PARAM1, param1);
        args.putString(ARG_PARAM2, param2);
        fragment.setArguments(args);
        return fragment;
    }

    /**
     * Mandatory empty constructor for the fragment manager to instantiate the
     * fragment (e.g. upon screen orientation changes).
     */
    public AllWeeksFragment() {
    }

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        if (getArguments() != null) {
            mParam1 = getArguments().getString(ARG_PARAM1);
            mParam2 = getArguments().getString(ARG_PARAM2);
        }
        dataSource.open();
        mCursor = dataSource.getAllWeeks();
        dataSource.displayCursor(mCursor);
    }

    ListView mListView;

    private void displayList() {

        Log.d(getClass().getSimpleName(), "count=" + mCursor.getCount());
        String[] from = new String[] {
                "_id",
                "weekHours"
        };

        int[] to = new int[] {
                R.id.allWeek,
                R.id.allHours
        };

        MyCursorAdapter adapter = new MyCursorAdapter(
                getActivity(),
                R.layout.row_layout,
                mCursor,
                from,
                to,
                0
        );

        mListView.setAdapter(adapter);
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.fragment_all_weeks, container, false);
        mListView = (ListView)view.findViewById(R.id.all_list);
        mListView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                if (null != mListener) {
                    mListener.onFragmentInteraction(id);
                }
            }
        });
        displayList();
        return view;
    }

    @Override
    public void onAttach(Activity activity) {
        super.onAttach(activity);
        try {
            mListener = (OnFragmentInteractionListener) activity;
        } catch (ClassCastException e) {
            throw new ClassCastException(activity.toString()
                + " must implement OnFragmentInteractionListener");
        }
    }

    @Override
    public void onDetach() {
        super.onDetach();
        mListener = null;
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        dataSource.close();
    }

    /**
    * 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
        public void onFragmentInteraction(Long id);
    }

    //extend the SimpleCursorAdapter to create a custom class where we
    //can override the getView to change the row colors
    private class MyCursorAdapter extends SimpleCursorAdapter{

        public MyCursorAdapter(Context context, int layout, Cursor c,
                String[] from, int[] to, int flags) {
            super(context, layout, c, from, to, flags);
        }


        @Override
        public View getView(int position, View convertView, ViewGroup parent) {

            Log.d(getClass().getSimpleName(), "position="+position);
            //get reference to the row
            View view = super.getView(position, convertView, parent);
            //check for odd or even to set alternate colors to the row background
            if(position % 2 == 0){
                view.setBackgroundColor(Color.rgb(238, 233, 233));
            }
            else {
                view.setBackgroundColor(Color.rgb(255, 255, 255));
            }
            return view;
        }
    }
}

row_layout.xml

<?xml version="1.0" encoding="utf-8"?>

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" android:orientation="horizontal" android:layout_width="match_parent" android:layout_height="wrap_content"
    android:id="@+id/allWeekRow">

    <TextView
        android:layout_width="0dp"
        android:layout_height="wrap_content"
        android:textAppearance="?android:attr/textAppearanceMedium"
        android:id="@+id/allWeek"
        android:layout_weight="0.5" />

    <TextView
        android:layout_width="0dp"
        android:layout_height="wrap_content"
        android:textAppearance="?android:attr/textAppearanceMedium"
        android:id="@+id/allHours"
        android:layout_weight="0.5" />
</LinearLayout>

HoursDataSource

public void displayCursor(Cursor c) {
    int i=1;
    String[] cols = c.getColumnNames();
    Log.d(getClass().getSimpleName(), "count="+c.getCount());
    while(c.moveToNext()) {
        for(String col : cols) {
            Log.d(getClass().getSimpleName(), i + " " + col + "=" + c.getString(c.getColumnIndex(col)));
        }
        i++;
    }
}
/*
 * TODO: attach YearTable as db1;
 * TODO: attach HOURS as db2;
 * TODO: select wkStart, wkEnd, payWeek as _id, (SUM(hMinutes) - SUM(lunch))/60.0 as weekHours from HOURS b inner join YearTable a on a.wkNum = b.payWeek group by b.payWeek order by b.payWeek ASC
 */
public Cursor getAllWeeks() {
    Cursor c = null;
    String query = "select payWeek as _id, (SUM(hMinutes) - SUM(lunch))/60.0 as weekHours from hours group by payWeek order by payWeek ASC";
    try {
        c = mDatabase.rawQuery(query, null);
    } catch (SQLException e) {
        Log.e(getClass().getSimpleName(), e.toString());
    }
    return c;
}

fragment_all_weeks.xml

<?xml version="1.0" encoding="utf-8"?>

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:id="@+id/listFrame">

    <LinearLayout
        android:orientation="horizontal"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:id="@+id/all_header"
        android:layout_alignParentTop="true">

        <TextView
            android:layout_width="0dp"
            android:layout_height="wrap_content"
            android:textAppearance="?android:attr/textAppearanceLarge"
            android:text="@string/Week"
            android:id="@+id/textView"
            android:layout_weight="0.5"
            android:textStyle="bold"
            android:gravity="center_horizontal" />

        <TextView
            android:layout_width="0dp"
            android:layout_height="wrap_content"
            android:textAppearance="?android:attr/textAppearanceLarge"
            android:text="@string/Hours"
            android:id="@+id/textView2"
            android:layout_weight="0.5"
            android:textStyle="bold"
            android:gravity="center_horizontal" />
    </LinearLayout>

    <ListView
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:id="@+id/all_list"
        android:layout_alignParentLeft="false"
        android:layout_marginLeft="0dp"
        android:layout_alignParentTop="false"
        android:layout_marginTop="0dp"
        android:layout_below="@+id/all_header"
        android:layout_alignLeft="@+id/all_header" />
</RelativeLayout>
来自MainActivity的

:(导航抽屉布局)

    case 3:
        fragment = AllWeeksFragment.newInstance(null, null);
        tag = "all";
        fragmentManager.beginTransaction()
                .replace(R.id.container, fragment, tag)
                .addToBackStack("home")
                .commit();
        break;

带有一些调试的logcat输出说一切都在那里....

09-29 14:34:46.345  24370-24370/us.emanon.timecard D/HoursDataSource﹕ count=4
09-29 14:34:46.345  24370-24370/us.emanon.timecard D/HoursDataSource﹕ 1 _id=34
09-29 14:34:46.345  24370-24370/us.emanon.timecard D/HoursDataSource﹕ 1 weekHours=11.75
09-29 14:34:46.345  24370-24370/us.emanon.timecard D/HoursDataSource﹕ 2 _id=35
09-29 14:34:46.345  24370-24370/us.emanon.timecard D/HoursDataSource﹕ 2 weekHours=7
09-29 14:34:46.345  24370-24370/us.emanon.timecard D/HoursDataSource﹕ 3 _id=36
09-29 14:34:46.345  24370-24370/us.emanon.timecard D/HoursDataSource﹕ 3 weekHours=8.75
09-29 14:34:46.345  24370-24370/us.emanon.timecard D/HoursDataSource﹕ 4 _id=37
09-29 14:34:46.345  24370-24370/us.emanon.timecard D/HoursDataSource﹕ 4 weekHours=55.25
09-29 14:34:46.355  24370-24370/us.emanon.timecard D/AllWeeksFragment﹕ count=4
09-29 14:34:46.365  24370-24370/us.emanon.timecard D/MyCursorAdapter﹕ position=0
09-29 14:34:46.375  24370-24370/us.emanon.timecard D/MyCursorAdapter﹕ position=0
09-29 14:34:46.375  24370-24370/us.emanon.timecard D/MyCursorAdapter﹕ position=0
09-29 14:34:46.375  24370-24370/us.emanon.timecard D/MyCursorAdapter﹕ position=0
09-29 14:34:46.375  24370-24370/us.emanon.timecard D/MyCursorAdapter﹕ position=0

enter image description here

我尝试过移动它们,将它们放在不同的地方(onCreate,onCreateView等),将局部变量更改为字段等等,所有内容都给出了相同的结果。我确信这很简单,但我坦率地说找不到它。

0 个答案:

没有答案