如何将数据从数据库移动到我的ViewPager?

时间:2018-03-27 07:28:51

标签: android database android-viewpager cursor

使用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();
    }

}

}

带有实现Fragment和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屏幕。我无法通过创建片段将光标值移动到类。我读到了将数据输入List并从那里移动的方法,将所需位置的数量移到FragmentPager,但它没有完全解决。有人能够知道一种简单而优雅的方法来解决这个问题吗?

1 个答案:

答案 0 :(得分:0)

实例化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...
        }
    }