Load Data in a fragment in Android

0

I'm doing an app in Android Studio to answer forms, the app generates a PageView with the number of categories that are in a table and each time a "page" is generated you should print the name of the category in which it is, until here there is no problem, the problem comes when placing on each "page" the questions according to each category, in other words, I can not find the way to print the questions of each category in my fragment , I have tried in several ways, but they do not work and in my last attempt for what I researched, it only triggered in a memory overflow, someone knows How can I put the questions by their category in my fragment ? Here is the code of the activity:

public class ActivityQuestion extends FragmentActivity implements FragmentSwipe.OnFragmentInteractionListener {

    private SectionsPagerAdapter mSectionsPagerAdapter;
    private ViewPager mViewPager;
    private ImageView logoImage;
    TextView category;
    ArrayList<Question> questionsArray;
ArrayList<Question> arrayAnswerType;
ArrayList<Answer> answerArray;
ArrayList<Categories> categoriesList;
ArrayList<Categories> categoriesArrayList;
DrawComponents drawComponents;
DrawVideo drawVideo;
DrawPhoto drawPhoto;
DrawFirm firm;
DrawDateHour calendar;
DrawAudioComponent audioComponent;
DatabaseHelper dbconnection;
Canvas canvas;
// var FOR GENERATE COMPONENTS
int day, month, year, hour, minute;
LinearLayout contenedor;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_question);
    logoImage = (ImageView) findViewById(R.id.profileLogo);
    contenedor = (LinearLayout) findViewById(R.id.contenedor);
    category = (TextView) findViewById(R.id.category);
    questionsArray = new ArrayList<Question>();
    arrayAnswerType = new ArrayList<Question>();
    categoriesArrayList = new ArrayList<Categories>();
    answerArray = new ArrayList<Answer>();
    categoriesList = new ArrayList<Categories>();
    drawComponents = new DrawComponents();
    calendar = new DrawDateHour();
    firm = new DrawFirm();
    audioComponent = new DrawAudioComponent();
    drawVideo = new DrawVideo();
    drawPhoto = new DrawPhoto();
    dbconnection = new DatabaseHelper(getApplicationContext());

    if (!SaveSharedPreference.getStringKeyValue(this, SaveSharedPreference.KEY_ORGANIZATION_IMAGE_PATH).equals("")) {
        Bitmap b = SaveSharedPreference.loadImageFromStorage(SaveSharedPreference.getStringKeyValue(this, SaveSharedPreference.KEY_ORGANIZATION_IMAGE_PATH), SaveSharedPreference.ORGANIZATION_NAME);
        if (b != null) {
            logoImage.setImageBitmap(b);
        }
    }

    mSectionsPagerAdapter = new SectionsPagerAdapter(getSupportFragmentManager());
    mViewPager = (ViewPager) findViewById(R.id.container);

    //ESTO GENERA LA CANTIDAD DEFRAGMENTOS DE MANERA DINÁMICA

    Intent params = getIntent();

    String idform = params.getStringExtra("idForm");

    getQuestionsbyFormId(Long.parseLong(idform));
       // Log.d("Hola", );
        readCategories();


//        getQuestionsbyFormId(Long.parseLong(idform));
  //      getQuestionsbyCategoryId(Long.parseLong(idform));


        mViewPager.setAdapter(mSectionsPagerAdapter);
        //GENERATE VIEWPAGER
}

//lectura de categorias para el control de ViewPager
public void readCategories()
{
    Cursor c = dbconnection.readCategory();
    while(c.moveToNext())
    {
        Categories categories = new Categories();
        categories.setId_category(c.getString(c.getColumnIndex("id_category")));
        categories.setCategory(c.getString(c.getColumnIndex("category")));

        categoriesList.add(categories);
    }
}

//Método para la lectura de todas las questions y las answer de la base de datos conforme al id del formulario
public void getQuestionsbyFormId(Long id) {

    Cursor cursorAns;
    Cursor c = dbconnection.readQuest(id);
    while (c.moveToNext()) {
        Question question = new Question();
        question.setId_question(c.getString(c.getColumnIndex("id_question")));
        question.setId_category(c.getString(c.getColumnIndex("id_category")));
        question.setQuestion(c.getString(c.getColumnIndex("question")));
        question.setRequired(c.getString(c.getColumnIndex("required")));

        cursorAns = dbconnection.readAnswerbyQuestionId(Long.parseLong(question.getId_question()));

        while (cursorAns.moveToNext()) {
            Answer answer = new Answer();
            answer.setId_answer_type(cursorAns.getString(cursorAns.getColumnIndex("id_answer_type")));
            answerArray.add(answer);
        }
        question.setAnswers(answerArray);
       // arrayAnswerType.add(question);
        questionsArray.add(question);
    }

}

@Override
public void onFragmentInteraction() {

}

public class SectionsPagerAdapter extends FragmentPagerAdapter {

    public SectionsPagerAdapter(FragmentManager fm) {
        super(fm);
    }

    @Override
    public android.support.v4.app.Fragment getItem(int position) {
        //método del swipe para pasar entre preguntas
        FragmentSwipe fragment = new FragmentSwipe();

        fragment.setCategory(categoriesList.get(position).getCategory());

        String[] iterationQuestion =  new String[questionsArray.size()];

        for (int i = 0; i <= questionsArray.size(); i++){
           // iterationQuestion[i] = questionsArray.get(i).getQuestion();
            Log.d("quest", questionsArray.get(i).getQuestion());
        }
        Log.d("prueba", "no funciona");
        String[] iterationIdCat = new String[questionsArray.size()];
           for (int n = 0; n<questionsArray.size(); n++)
            Log.d("hola", iterationIdCat[n]);

            for (int i = 0; i <= questionsArray.size(); i++)
        {
            iterationIdCat[i] = questionsArray.get(i).getId_category();
            Log.d("idCat", iterationIdCat[i]);
        }
return fragment;
    }

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

        @Override
        public CharSequence getPageTitle(int position) {
            return null;
        }
    }

}

Here is the code of my fragment :

public class FragmentSwipe extends Fragment implements FragmentAnswerTypeOne.OnFragmentInteractionListener{
    // the fragment initialization parameters, e.g. ARG_ITEM_NUMBER
    private static final String ARG_PARAM1 = "param1";
    private static final String ARG_PARAM2 = "param2";

    private String mParam1;
    private String mParam2;
    private TextView tv_question;
    private String question;
    private String category;
    DrawComponents options;
    DatabaseHelper dbconnection;

    ArrayList<Question> questionsArray;
    ArrayList<Question> arrayAnswerType;
    ArrayList<Answer> answerArray;
    ArrayList<Categories> categoriesList;

    LinearLayout layout;
    ScrollView scrollFragment;
    LinearLayout contenedor;


    private OnFragmentInteractionListener mListener;

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

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

    public void setCategory(String category)
    {
        this.category = category;
    }


    public static FragmentSwipe newInstance(String param1, String param2) {
        FragmentSwipe fragment = new FragmentSwipe();
        Bundle args = new Bundle();
        args.putString(ARG_PARAM1, param1);
        args.putString(ARG_PARAM2, param2);
        fragment.setArguments(args);
        return fragment;
    }

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        if (getArguments() != null) {
            mParam1 = getArguments().getString(ARG_PARAM1);
            mParam2 = getArguments().getString(ARG_PARAM2);

            questionsArray = new ArrayList<Question>();
            arrayAnswerType = new ArrayList<Question>();
            answerArray = new ArrayList<Answer>();
            categoriesList = new ArrayList<Categories>();

            dbconnection = new DatabaseHelper(getActivity());
        }
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        View rootView = inflater.inflate(R.layout.fragment_fragment_swipe, container, false);
        TextView tv_quetion = (TextView) rootView.findViewById(R.id.tv_question);
        TextView category = (TextView) rootView.findViewById(R.id.category);
        category.setText(this.category);
        layout = (LinearLayout) rootView.findViewById(R.id.contenedor);
        ScrollView scrollFragment = (ScrollView) rootView.findViewById(R.id.scrollFragment);

        tv_quetion.setText(this.question);//cambiar this.category por this.question

        contenedor = new LinearLayout(getActivity());

       // readQuestions(Long.parseLong());

        return rootView;

    }

    // TODO: Rename method, update argument and hook method into UI event

    public void onButtonPressed() {
        if (mListener != null) {
            mListener.onFragmentInteraction();
        }
    }

    @Override
    public void onAttach(Context context) {
        super.onAttach(context);
        if (context instanceof OnFragmentInteractionListener) {
            mListener = (OnFragmentInteractionListener) context;
        } else {
            throw new RuntimeException(context.toString()
                    + " must implement OnFragmentInteractionListener");
        }
    }

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

    @Override
    public void onFragmentInteraction(Uri uri) {

    }

    public interface OnFragmentInteractionListener {
        void onFragmentInteraction();
    }

}

This is the last thing that LogCat gives me:

  

09-20 08: 20: 19.516 4297-4297 / mx.com.stesso.appstesso D / quest: Question   1 text line       Question 2 paragraph       Question 3 address       Question 4 email       Question 5 phone       Question 6 cell phone       question 7 textarea       question 8 list       question 9 selection list       question 10 checkbox       Question 11 radio 09-20 08: 20: 19.517 4297-4297 / mx.com.stesso.appstesso D / quest: Question 12 numeric       Question 13 date       Question 14 hour       Question 15 date and time       question 16 hyperlink       Firm       Image       video       Audio       location 09-20 08: 20: 19.519 4297-4297 / mx.com.stesso.appstesso D / AndroidRuntime: Shutting down VM 09-20 08: 20: 19.541   4297-4297 / mx.com.stesso.appstesso E / AndroidRuntime: FATAL EXCEPTION:   main       Process: mx.com.stesso.appstesso, PID: 4297       java.lang.IndexOutOfBoundsException: Index: 21, Size: 21           at java.util.ArrayList.get (ArrayList.java:411)           at mx.com.stesso.appstesso.ActivityQuestion $ SectionsPagerAdapter.getItem (ActivityQuestion.java:197)           at android.support.v4.app.FragmentPagerAdapter.instantiateItem (FragmentPagerAdapter.java:102)           at android.support.v4.view.ViewPager.addNewItem (ViewPager.java:1002)           at android.support.v4.view.ViewPager.populate (ViewPager.java:1150)           at android.support.v4.view.ViewPager.populate (ViewPager.java:1084)           at android.support.v4.view.ViewPager.onMeasure (ViewPager.java:1614)           at android.view.View.measure (View.java:19883)           at android.support.constraint.ConstraintLayout.internalMeasureChildren (ConstraintLayout.java:1212)           at android.support.constraint.ConstraintLayout.onMeasure (ConstraintLayout.java:1552)           at android.view.View.measure (View.java:19883)           at android.view.ViewGroup.measureChildWithMargins (ViewGroup.java:6087)           at android.widget.FrameLayout.onMeasure (FrameLayout.java:185)           at android.view.View.measure (View.java:19883)           at android.view.ViewGroup.measureChildWithMargins (ViewGroup.java:6087)           at android.widget.LinearLayout.measureChildBeforeLayout (LinearLayout.java:1464)           at android.widget.LinearLayout.measureVertical (LinearLayout.java:758)           at android.widget.LinearLayout.onMeasure (LinearLayout.java:640)           at android.view.View.measure (View.java:19883)           at android.view.ViewGroup.measureChildWithMargins (ViewGroup.java:6087)           at android.widget.FrameLayout.onMeasure (FrameLayout.java:185)           at com.android.internal.policy.DecorView.onMeasure (DecorView.java:689)           at android.view.View.measure (View.java:19883)           at android.view.ViewRootImpl.performMeasure (ViewRootImpl.java:2293)           at android.view.ViewRootImpl.measureHierarchy (ViewRootImpl.java:1384)           at android.view.ViewRootImpl.performTraversals (ViewRootImpl.java:1637)           at android.view.ViewRootImpl.doTraversal (ViewRootImpl.java:1272)           at android.view.ViewRootImpl $ TraversalRunnable.run (ViewRootImpl.java:6408)           at android.view.Choreographer $ CallbackRecord.run (Choreographer.java:874)           at android.view.Choreographer.doCallbacks (Choreographer.java:686)           at android.view.Choreographer.doFrame (Choreographer.java:621)           at android.view.Choreographer $ FrameDisplayEventReceiver.run (Choreographer.java:860)           at android.os.Handler.handleCallback (Handler.java:751)           at android.os.Handler.dispatchMessage (Handler.java:95)           at android.os.Looper.loop (Looper.java:154)           at android.app.ActivityThread.main (ActivityThread.java:6196)           at java.lang.reflect.Method.invoke (Native Method)           at com.android.internal.os.ZygoteInit $ MethodAndArgsCaller.run (ZygoteInit.java:888)           at com.android.internal.os.ZygoteInit.main (ZygoteInit.java:778)

I will appreciate your help in advance

    
asked by DarkMifnight 20.09.2018 в 15:23
source

0 answers