代码之家  ›  专栏  ›  技术社区  ›  Spike Johnson

如何将数据从DB移动到ViewPager?

  •  0
  • Spike Johnson  · 技术社区  · 6 年前

    用DB初始化并实现适配器。

    public class MainActivity extends AppCompatActivity {//implements 
    View.OnClickListener{
    
    ArrayList<String> titles = new ArrayList<>();
    
    ArrayAdapter arrayAdapter;
    
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
    
    
        ListView listView = findViewById(R.id.listView);
    arrayAdapter = new ArrayAdapter(this, android.R.layout.simple_list_item_1, 
    titles);
        listView.setAdapter(arrayAdapter);
    
        try {
    
            SQLiteDatabase myDatabase = this.openOrCreateDatabase("Places", 
    MODE_PRIVATE, null);
    
            myDatabase.execSQL("CREATE TABLE IF NOT EXISTS places (name VARCHAR, 
    time INT(2), solo INT(1), id INTEGER PRIMARY KEY)");
    
            myDatabase.execSQL("INSERT INTO places (name, time, solo) VALUES 
    ('One', 23, 1)");
            myDatabase.execSQL("INSERT INTO places (name, time, solo) VALUES 
    ('Two', 24, 2)");
            myDatabase.execSQL("INSERT INTO places (name, time, solo) VALUES 
    ('Three', 22, 1)");
            myDatabase.execSQL("INSERT INTO places (name, time, solo) VALUES 
    ('Four', 02, 2)");
    
            Cursor c = myDatabase.rawQuery("SELECT * FROM places WHERE solo = 
    1", null);
    
            int nameIndex = c.getColumnIndex("name");
            int timeIndex = c.getColumnIndex("time");
            int soloIndex = c.getColumnIndex("solo");
            int idIndex = c.getColumnIndex("id");
    
    
    
            if (c.moveToFirst()) {
                titles.clear();
                do {
                    titles.add(c.getString(nameIndex));
    
    
    
                } while (c.moveToNext());
                arrayAdapter.notifyDataSetChanged();
            }
            c.close();
            myDatabase.execSQL("DELETE FROM places");
    
        }
        catch (Exception e) {
    
            e.printStackTrace();
        }
    
    }
    
    }
    

    使用实现片段和PagerAdapter初始化:

    public class MyGallery extends AppCompatActivity {
    
    private SectionsPagerAdapter mSectionsPagerAdapter;
    
    private ViewPager mViewPager;
    
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_my_gallery);
    
        // Create the adapter that will return a fragment for each of the three
        // primary sections of the activity.
        mSectionsPagerAdapter = new 
    SectionsPagerAdapter(getSupportFragmentManager());
    
        // Set up the ViewPager with the sections adapter.
        mViewPager = (ViewPager) findViewById(R.id.container);
        mViewPager.setAdapter(mSectionsPagerAdapter);
    
    }
    
    
    /**
     * A placeholder fragment containing a simple view.
     */
    public static class PlaceholderFragment extends Fragment {
        /**
         * The fragment argument representing the section number for this
         * fragment.
         */
        private static final String ARG_SECTION_NUMBER = "section_number";
    
        public PlaceholderFragment() {
        }
    
        /**
         * Returns a new instance of this fragment for the given section
         * number.
         */
        public static PlaceholderFragment newInstance(int sectionNumber) {
            PlaceholderFragment fragment = new PlaceholderFragment();
            Bundle args = new Bundle();
            args.putInt(ARG_SECTION_NUMBER, sectionNumber);
            fragment.setArguments(args);
            return fragment;
        }
    
        @Override
        public View onCreateView(LayoutInflater inflater, ViewGroup container,
                                 Bundle savedInstanceState) {
            View rootView = inflater.inflate(R.layout.fragment_my_gallery, 
    container, false);
            TextView textView = (TextView) 
    rootView.findViewById(R.id.section_label);
            textView.setText(getString(R.string.section_format, 
    getArguments().getInt(ARG_SECTION_NUMBER)));
            return rootView;
        }
    }
    
    /**
     * A {@link FragmentPagerAdapter} that returns a fragment corresponding to
     * one of the sections/tabs/pages.
     */
    public class SectionsPagerAdapter extends FragmentPagerAdapter {
    
        public SectionsPagerAdapter(FragmentManager fm) {
            super(fm);
        }
    
        @Override
        public Fragment getItem(int position) {
            // getItem is called to instantiate the fragment for the given page.
            // Return a PlaceholderFragment (defined as a static inner class 
    below).
            return PlaceholderFragment.newInstance(position + 1);
        }
    
        @Override
        public int getCount() {
            // Show 3 total pages.
            return 3;
        }
    }
    }
    

    我正在尝试将名为“name”(nameIndex)的字段从数据库移动到viewpager屏幕。我无法在创建片段时将光标值移动到类。我读到了有关将数据输入列表的方法,并从列表中移动到所需位置的编号到FragmentPager,但它并没有完全起作用。有人能知道一个简单而优雅的方法来解决这个问题吗?

    1 回复  |  直到 6 年前
        1
  •  1
  •   grabarz121    6 年前

    实例化FragmentPagerAdapter时,将ArrayList作为参数传递给适配器构造函数

    mSectionsPagerAdapter = new
                    SectionsPagerAdapter(getSupportFragmentManager(), titles);
    
            // Set up the ViewPager with the sections adapter.
            mViewPager = (ViewPager) findViewById(R.id.container);
            mViewPager.setAdapter(mSectionsPagerAdapter);
    

    在适配器中,使用引用,并从数组中获取字符串,如

    public class SectionsPagerAdapter extends FragmentPagerAdapter {
    
        private ArrayList<String> strings;
    
        public SectionsPagerAdapter(FragmentManager fm, ArrayList<String> strings) {
            super(fm);
    
            this.strings = strings;
        }
    
        @Override
        public Fragment getItem(int position) {
    
            return PlaceholderFragment.newInstance(position + 1, strings.get(position + 1));
        }
    
        @Override
        public int getCount() {
    
            return strings.size();
        }
    }
    

    最后,在Fragment类中,将其作为参数传递,并从onCreate方法中作为全局变量获取

    public static class PlaceholderFragment extends Fragment {
        /**
         * The fragment argument representing the section number for this
         * fragment.
         */
        private static final String ARG_SECTION_NUMBER = "section_number";
    
        private String title;
    
        public PlaceholderFragment() {
        }
    
        /**
         * Returns a new instance of this fragment for the given section
         * number.
         */
        public static PlaceholderFragment newInstance(int sectionNumber, String title) {
            PlaceholderFragment fragment = new PlaceholderFragment();
            Bundle args = new Bundle();
            args.putInt(ARG_SECTION_NUMBER, sectionNumber);
            args.putString("key", title);
            fragment.setArguments(args);
            return fragment;
        }
    
        @Override
        public void onCreate(@Nullable Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
    
            title = getArguments().getString("key");
        }
    
        @Override
        public View onCreateView(LayoutInflater inflater, ViewGroup container,
                                 Bundle savedInstanceState) {
            View rootView = inflater.inflate(R.layout.fragment_my_gallery,
                    container, false);
            TextView textView = (TextView)
                    rootView.findViewById(R.id.section_label);
            textView.setText(getString(R.string.section_format,
                    getArguments().getInt(ARG_SECTION_NUMBER)));
            return rootView;
        }
    }
    

    笔记为了更好地控制代码,如果片段数量有限,应该使用 switch 陈述使命感 position + 1 在您的情况下,当超过数组的索引时,适配器可能会引发nullpointerexception。您可以使用 viewPager.setCurrentItem(position); ,带有switch语句的FragmentPagerAdapter示例如下所示

    @Override
        public Fragment getItem(int position) {
    
            switch (position) {
    
                case 0:
                    return PlaceholderFragment.newInstance(position, strings.get(position));
                case 1:
                    return PlaceholderFragment.newInstance(position, strings.get(position));
                case 2:
                    return PlaceholderFragment.newInstance(position, strings.get(position));
                    default:
                        return something...
            }
        }