Как создать PagerAdapter с BaseAdapter из базы данных? - PullRequest
0 голосов
/ 13 декабря 2018

Я хотел бы расширить класс pageAdapter, загрузив данные из базы данных и дополнительно в представлении у меня есть 2 GridView, потому что там я отображаю представление в зависимости от объема данных.Мой вопрос заключается в том, как реализовать конструктор, а класс в ViewPagerAdapter расширяет PageAdapter для извлечения данных из базы данных.Должен ли я ввести курсор в конструктор?

DataBase.java

public class DatabaseHelper extends SQLiteOpenHelper {

SQLiteDatabase db;

public DatabaseHelper(Context context) {
    super(context, "QUIZ", null, 1);
}

@Override
public void onCreate(SQLiteDatabase db) {

    this.db = db;

    db.execSQL("CREATE TABLE Q (_id INTEGER PRIMARY KEY AUTOINCREMENT, " +
            "IMAGE INTEGER, " +
            "QUESTION TEXT, "+
            "ANSWER TEXT);");


    insertData(db, new Item(R.drawable.ic_launcher_background, "Question", "Answer"));
    insertData(db, new Item(R.drawable.ic_launcher_foreground, "Question2", "Answer2"));


}

@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {

    db.execSQL("DROP TABLE IF EXISTS Q");
 onCreate(db);

}

private static void insertData(SQLiteDatabase db, Item item)
{
    ContentValues contentValues = new ContentValues();
    contentValues.put("IMAGE", item.getImage());
    contentValues.put("QUESTION", item.getQuestion());
    contentValues.put("ANSWER", item.getAnswer());
    db.insert("Q", null, contentValues);
}

}

Item.java

public class Item {

int image;
String question;
String answer;


public Item(int image, String question, String answer) {
    this.image = image;
    this.question = question;
    this.answer = answer;
}

public int getImage() {
    return image;
}

public void setImage(int image) {
    this.image = image;
}

public String getQuestion() {
    return question;
}

public void setQuestion(String question) {
    this.question = question;
}

public String getAnswer() {
    return answer;
}

public void setAnswer(String answer) {
    this.answer = answer;
}

}

ViewPagerAdapter

public class ViewPagerAdapter extends PagerAdapter {

private Activity activity;
private LayoutInflater layoutInflater;

List<Item> quizList;


**//What should I put in the constructor and how to write the code so that the data is retrieved from the database?

//This way
/*

public ViewPagerAdapter(Activity activity, Cursor cursor) {
    this.activity = activity;
    this.cursor = cursor;
}

 */**

public ViewPagerAdapter(Activity activity, List<Item> quizList) {
    this.activity = activity;
    this.quizList = quizList;
}

@Override
public int getCount() {
    return quizList.size();
}

@Override
public boolean isViewFromObject(@NonNull View view, @NonNull Object o) {
    return view == o;
}


@NonNull
@Override
public Object instantiateItem(@NonNull ViewGroup container, int position) {

    layoutInflater = (LayoutInflater) activity.getApplicationContext().getSystemService(Context.LAYOUT_INFLATER_SERVICE);

    View itemView = layoutInflater.inflate(R.layout.view_pager_item, container,false);

    ImageView imageView = itemView.findViewById(R.id.imgLogo);
    DisplayMetrics displayMetrics = new DisplayMetrics();
    activity.getWindowManager().getDefaultDisplay().getMetrics(displayMetrics);

    int height = displayMetrics.heightPixels;
    int width = displayMetrics.widthPixels;

    imageView.setMinimumHeight(height);
    imageView.setMinimumWidth(width);

    Picasso.get().load(quizList.get(position).getImage()).placeholder(R.mipmap.ic_launcher).into(imageView);



    GridView gridViewAnswer = itemView.findViewById(R.id.gridViewAnswer);
    GridView gridViewQuestion = itemView.findViewById(R.id.gridViewSuggest);

    //Can I here set my GridViewBaseAdapterAnswer and GridViewBaseAdapterQuestion
    //Adapter in another adapter it's posible?

    // GridViewBaseAdapterAnswer gridViewAdapter = new GridViewAdapter(List<String> answer, Context context, MainActivity mainActivity);
   // gridViewAnswer.setAdapter(gridViewAdapter);

    container.addView(itemView);
    return itemView;
}

@Override
public void destroyItem(@NonNull ViewGroup container, int position, @NonNull Object object) {
    ((ViewPager)container).removeView((View)object);
}

} ​​

ViewPagerAdapter.java

<RelativeLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
android:layout_gravity="center_horizontal"
tools:context=".MainActivity">

<LinearLayout
    android:orientation="vertical"
    android:layout_gravity="center_horizontal"
    android:layout_alignParentTop="true"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:layout_marginBottom="20dp"
    >


    <ImageView
        android:id="@+id/imgLogo"
        android:layout_width="match_parent"
        android:layout_height="200dp" />

    <GridView
        android:id="@+id/gridViewAnswer"
        android:layout_margin="20dp"
        android:padding="4dp"
        android:horizontalSpacing="4dp"
        android:verticalSpacing="4dp"
        android:columnWidth="40dp"
        android:numColumns="auto_fit"
        android:scrollbars="none"
        android:stretchMode="columnWidth"
        android:layout_width="match_parent"
        android:layout_height="wrap_content" />


    <GridView
        android:id="@+id/gridViewSuggest"
        android:layout_margin="20dp"
        android:padding="4dp"
        android:horizontalSpacing="4dp"
        android:verticalSpacing="4dp"
        android:columnWidth="40dp"
        android:numColumns="auto_fit"
        android:scrollbars="none"
        android:stretchMode="columnWidth"
        android:layout_width="match_parent"
        android:layout_height="wrap_content" />

</LinearLayout>

...