【问题标题】:Filling ListView in Fragments with SQLite cursor adapter使用 SQLite 游标适配器在 Fragments 中填充 ListView
【发布时间】:2014-07-09 21:48:20
【问题描述】:

我在运行代码时在片段上填充 ListView 时遇到问题。我的 MainActivity 类中有 3 个片段。问题是我想在我的片段上创建一个 ListView 然后显示它。问题是代码没有运行(查看 catlog)。任何人都明白为什么:

public class DocumentItemFragment extends Fragment {

    private OnFragmentInteractionListener mListener;

    public DocumentItemFragment() {
        // Required empty public constructor
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
            Bundle savedInstanceState) {
        // Inflate the layout for this fragment
        populateListView();
        return inflater.inflate(R.layout.fragment_document_item, container, false);
    }


    private void populateListView() {
        SQLiteHelper sqlh = new SQLiteHelper(getActivity().getBaseContext());
        SQLiteDatabase db = sqlh.getWritableDatabase();

        String query = "SELECT  * FROM invdokg";
        Cursor cursor = db.rawQuery(query, null);

        String[] fromFieldNames = new String[]
        {SQLiteHelper.KEY_ID,SQLiteHelper.KEY_NAZIV, SQLiteHelper.KEY_DATUM};

        int[] toViewIDs = new int[]
        {R.id.docItemId, R.id.docItemNaziv,R.id.docItemDate};
        SimpleCursorAdapter myCursorAdapter;

        myCursorAdapter = new SimpleCursorAdapter(getActivity().getBaseContext(), R.layout.docitem_layout, cursor, fromFieldNames, toViewIDs, 0);
        ListView myList = (ListView) getActivity().findViewById(R.id.docListView);
        myList.setAdapter(myCursorAdapter);
    }

    // TODO: Rename method, update argument and hook method into UI event
    public void onButtonPressed(Uri uri) {
        if (mListener != null) {
            mListener.onFragmentInteraction(uri);
        }
    }

    @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;
    }

    /**
     * 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(Uri uri);
    }

}

还有我的主要活动:

public class MainActivity extends Activity 
implements BlankFragment.OnFragmentInteractionListener,
ExportImportFragment.OnFragmentInteractionListener,
            HistoryFragment.OnFragmentInteractionListener{
    private DrawerLayout mDrawerLayout;
    private ListView mDrawerList;
    private ActionBarDrawerToggle mDrawerToggle;

    // nav drawer title
    private CharSequence mDrawerTitle;

    // used to store app title
    private CharSequence mTitle;

    // slide menu items
    private String[] navMenuTitles;
    private TypedArray navMenuIcons;

    private ArrayList<NavDrawerItem> navDrawerItems;
    private NavDrawerListAdapter adapter;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        //SharedPreferences settings = PreferenceManager.getDefaultSharedPreferences(this);
        //String userTheme = settings.getString("pref_key_apptheme_list", "Theme_Dark");


        mTitle = mDrawerTitle = getTitle();

        // load slide menu items
        navMenuTitles = getResources().getStringArray(R.array.nav_drawer_items);

        // nav drawer icons from resources
        navMenuIcons = getResources()
                .obtainTypedArray(R.array.nav_drawer_icons);

        mDrawerLayout = (DrawerLayout) findViewById(R.id.drawer_layout);
        mDrawerList = (ListView) findViewById(R.id.list_slidermenu);

        navDrawerItems = new ArrayList<NavDrawerItem>();

        // adding nav drawer items to array
        // InvDokG
        navDrawerItems.add(new NavDrawerItem(navMenuTitles[0], navMenuIcons.getResourceId(0, -1)));
        // ImportExport
        navDrawerItems.add(new NavDrawerItem(navMenuTitles[1], navMenuIcons.getResourceId(1, -1)));
        // History
        navDrawerItems.add(new NavDrawerItem(navMenuTitles[2], navMenuIcons.getResourceId(2, -1), true, "22")); 

        // Recycle the typed array
        navMenuIcons.recycle();

        mDrawerList.setOnItemClickListener(new SlideMenuClickListener());

        // setting the nav drawer list adapter
        adapter = new NavDrawerListAdapter(getApplicationContext(),
                navDrawerItems);
        mDrawerList.setAdapter(adapter);

        // enabling action bar app icon and behaving it as toggle button
        getActionBar().setDisplayHomeAsUpEnabled(true);
        getActionBar().setHomeButtonEnabled(true);

        mDrawerToggle = new ActionBarDrawerToggle(this, mDrawerLayout,
                R.drawable.ic_drawer, //nav menu toggle icon
                R.string.app_name, // nav drawer open - description for accessibility
                R.string.app_name // nav drawer close - description for accessibility
        ) {
            public void onDrawerClosed(View view) {
                getActionBar().setTitle(mTitle);
                // calling onPrepareOptionsMenu() to show action bar icons
                invalidateOptionsMenu();
            }

            public void onDrawerOpened(View drawerView) {
                getActionBar().setTitle(mDrawerTitle);
                // calling onPrepareOptionsMenu() to hide action bar icons
                invalidateOptionsMenu();
            }
        };
        mDrawerLayout.setDrawerListener(mDrawerToggle);

        if (savedInstanceState == null) {
            // on first time display view for first nav item
            displayView(0);
        }


        // SQL Lite**********************************************************************************       
        SQLiteHelper db = new SQLiteHelper(this);

        /**
         * CRUD Operations
         * */
        // add Books
        db.addInvDokG(new InvDokG("Android Application Development Cookbook", new Date()));   
        db.addInvDokG(new InvDokG("Android Programming: The Big Nerd Ranch Guide", new Date()));       
        db.addInvDokG(new InvDokG("Learn Android App Development", new Date()));

        // get all invdokgs
        List<InvDokG> list = db.getAllInvDokGs();

        // delete one invdokg
        db.deleteInvDokG(list.get(0));

        // get all invdokgs
        db.getAllInvDokGs();
    }

    /**
     * Slide menu item click listener
     * */
    private class SlideMenuClickListener implements
            ListView.OnItemClickListener {
        @Override
        public void onItemClick(AdapterView<?> parent, View view, int position,
                long id) {
            // display view for selected nav drawer item
            displayView(position);
        }
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        getMenuInflater().inflate(R.menu.main, menu);
        return true;
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        // toggle nav drawer on selecting action bar app icon/title
        if (mDrawerToggle.onOptionsItemSelected(item)) {
            return true;
        }
        // Handle action bar actions click
        Intent intent;
        switch (item.getItemId()) {
        case R.id.action_settings:
            intent = new Intent(this, SettingsActivity.class);
            startActivity(intent);
            return true;
        case R.id.action_about:
            intent = new Intent(this, AboutActivity.class);
            startActivity(intent);
            return true;
        default:
            return super.onOptionsItemSelected(item);
        }
    }

    /* *
     * Called when invalidateOptionsMenu() is triggered
     */
    @Override
    public boolean onPrepareOptionsMenu(Menu menu) {
        // if nav drawer is opened, hide the action items
        boolean drawerOpen = mDrawerLayout.isDrawerOpen(mDrawerList);
        menu.findItem(R.id.action_settings).setVisible(!drawerOpen);
        return super.onPrepareOptionsMenu(menu);
    }

    /**
     * Diplaying fragment view for selected nav drawer list item
     * */
    private void displayView(int position) {
        // update the main content by replacing fragments
        Fragment fragment = null;
        switch (position) {
        case 0:
//          Intent i = new Intent(getBaseContext(), ItemListActivity.class);                      
//          //i.putExtra("key", value); //Optional parameters
//          startActivity(i);
            fragment = new BlankFragment();
            break;
        case 1:
            fragment = new ExportImportFragment();
            break;
        case 2:
            fragment = new HistoryFragment();
            break;
        default:
            break;
        }

        if (fragment != null) {
            FragmentTransaction transaction=getFragmentManager().beginTransaction();
            transaction.replace(R.id.frame_container,fragment);
            transaction.addToBackStack(null);
            transaction.setTransition(FragmentTransaction.TRANSIT_FRAGMENT_FADE);
            transaction.commit();

            // update selected item and title, then close the drawer
            mDrawerList.setItemChecked(position, true);
            mDrawerList.setSelection(position);
            setTitle(navMenuTitles[position]);
            mDrawerLayout.closeDrawer(mDrawerList);
        } else {
            // error in creating fragment
            Log.e("MainActivity", "Error in creating fragment");
        }
    }

    @Override
    public void setTitle(CharSequence title) {
        mTitle = title;
        getActionBar().setTitle(mTitle);
    }

    /**
     * When using the ActionBarDrawerToggle, you must call it during
     * onPostCreate() and onConfigurationChanged()...
     */

    @Override
    protected void onPostCreate(Bundle savedInstanceState) {
        super.onPostCreate(savedInstanceState);
        // Sync the toggle state after onRestoreInstanceState has occurred.
        mDrawerToggle.syncState();
    }

    @Override
    public void onConfigurationChanged(Configuration newConfig) {
        super.onConfigurationChanged(newConfig);
        // Pass any configuration change to the drawer toggls
        mDrawerToggle.onConfigurationChanged(newConfig);
    }

    @Override
    public void onFragmentInteraction(Uri uri) {
        // TODO Auto-generated method stub

    }
}

我的 mainactivity.xml:

<android.support.v4.widget.DrawerLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    android:id="@+id/drawer_layout"
    android:layout_width="match_parent"
    android:layout_height="match_parent">

    <!-- Framelayout to display Fragments -->
    <FrameLayout
        android:id="@+id/frame_container"
        android:layout_width="match_parent"
        android:layout_height="match_parent" />

    <!-- Listview to display slider menu -->
    <ListView
        android:id="@+id/list_slidermenu"
        android:layout_width="240dp"
        android:layout_height="match_parent"
        android:layout_gravity="start"
        android:choiceMode="singleChoice"
        android:divider="@color/list_divider"
        android:dividerHeight="1dp"        
        android:listSelector="@drawable/list_selector"
        android:background="@color/list_background"/>
</android.support.v4.widget.DrawerLayout>

我的片段 XML:

<FrameLayout 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"
    tools:context=".MainActivity" >

    <ListView
        android:id="@+id/docListView"
        android:layout_width="match_parent"
        android:layout_height="wrap_content" >
    </ListView>

</FrameLayout>

【问题讨论】:

    标签: android sqlite listview android-fragments


    【解决方案1】:

    你能详细解释你的问题吗? 您可以在这里使用 ListFragment 作为基础。到目前为止,就我所见,你搞砸了布局(请给你的 XML 提供实际名称,以便其他人可以看到正在使用的资源)。

    一件事:

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
            Bundle savedInstanceState) {
        // Inflate the layout for this fragment
        populateListView();
        return inflater.inflate(R.layout.fragment_document_item, container, false);
    }
    

    假设 fragment_document_item 是您的片段 XML,您必须将 ListView 命名为 @android:id/list

    您在目录日志中遇到什么错误? R.layout.docitem_layout 到底是什么?

    Rgds

    毛毛虫

    【讨论】:

    • fragment_document_item 是片段 XML。 docitem_layout 是我的列表项的自定义布局样式。 docitem_layout 有 {R.id.docItemId, R.id.docItemNaziv,R.id.docItemDate};上面的项目。为什么我称它为列表?如果您在初始化光标后再次看到代码。所以这应该将它绑定到列表视图? ListView myList = (ListView)getActivity().findViewById(R.id.docListView);
    • 更多详情请参阅developer.android.com/reference/android/app/ListFragment.html。我的理解是 ListView 在布局中搜索这个特定的 id。如果它丢失,它应该创建一个警告或错误。到目前为止,您的 docitem_layout 看起来不错。就在几天前,我遇到了一个非常相似的问题 btw :) 你的确切问题是什么?你什么都看不见吗?程序没有启动/崩溃吗?
    • 它没有崩溃,也没有运行 SQLite 函数。控制台没有显示它正在被调用。
    • 在您的活动中,您没有在任何地方使用您的片段 DocumentItemFragment - 它应该如何开始?
    猜你喜欢
    • 1970-01-01
    • 2015-11-22
    • 1970-01-01
    • 2016-11-12
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-02-10
    相关资源
    最近更新 更多