Во-первых, я прошу прощения, потому что не знаю, как правильно представить информацию. Я пытался загрузить элемент в ArrayList, находясь внутри метода ".onCreate()" Activity. Первая строка трассировки стека выглядит следующим образом:

java.lang.RuntimeException: Unable to start activity ComponentInfo{com.weslange.Term_Scheduling/com.weslange.Term_Scheduling.Term_ChangingDetails_Activity}: java.lang.UnsupportedOperationException

Строка, вызывающая сбой, выглядит следующим образом:

courseData_List.add( courseData_entry )

У меня был предыдущий успех при загрузке элементов в RecyclerView путем доступа к базе данных SQLite. Мои текущие попытки включают использование метода ".add()" для ArrayList, но я явно делаю это неправильно. Я мог бы немного подумать, пожалуйста.

Спасибо за ваше время.

Term_ChangingDetails_Activity.java:

public class Term_ChangingDetails_Activity extends AppCompatActivity
        implements Term_ChangingDetails_RecyclerView_Adapter.ItemClickListener{

    private Button saveButton;

    int termID;

    EditText termName_EditText;
    Button startingDate_Button;
    Button endingDate_Button;
    Button courseSelection_Button;

    Bundle dataArgument_Bundle_Example;
    DialogFragment startingDateFragment;
    DialogFragment endingDateFragment;

    TermData termData_TransferInfo;
    Database_Handling databaseHandling;

    List< CourseData > courseData_List = Collections.emptyList();

    RecyclerView recyclerView;
    Term_ChangingDetails_RecyclerView_Adapter adapter;


    @Override
    protected void onCreate( Bundle savedInstanceState ) {

        super.onCreate( savedInstanceState );

        //The below line is necessary for showing info at all.
        setContentView( R.layout.activity_term_changingdetails );

        databaseHandling = new Database_Handling( this );


        //&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&
        Intent intent = getIntent();
        final TermData termData_Values = intent.getParcelableExtra( "termData_Parcelable" );
        termID = termData_Values.getTermID();
        //&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&


        //This displays a back button on the ToolBar at the top of the Activity.
        getSupportActionBar().setDisplayHomeAsUpEnabled( true );

        //This just changes the title of the ToolBar.
        getSupportActionBar().setTitle( "Changing Details of This Term" );


        //*****************************************************************
        termName_EditText = findViewById( R.id.termNameXML );
        termName_EditText.setText( termData_Values.getTermName() );

        startingDate_Button = findViewById( R.id.startingDateButtonXML );
        startingDate_Button.setText( termData_Values.getStartingDate() );

        endingDate_Button = findViewById( R.id.endingDateButtonXML );
        endingDate_Button.setText( termData_Values.getEndingDate() );
        //*****************************************************************


        //%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
        //%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
        saveButton = findViewById( R.id.saveButtonXML );
        saveButton.setOnClickListener( new View.OnClickListener() {

            @Override
            public void onClick( View view ) {

                termData_TransferInfo = new TermData( termID,
                        termName_EditText.getText().toString(),
                        startingDate_Button.getText().toString(),
                        endingDate_Button.getText().toString() );

                databaseHandling.updateTermData( termData_TransferInfo );




                //TODO  THERE IS ALSO THE NEED TO UPLOAD JSON DATA FOR THE COURSES AS A STRING TO THE SQLITE DATABASE.
                //TODO  'courseData_List' IS WHERE TO PULL THE DATA FROM THROUGH GSON.




                finish();

            }
        });
        //%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
        //%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%


        courseSelection_Button = findViewById( R.id.courseSelection_ButtonXML );
        courseSelection_Button.setOnClickListener( new View.OnClickListener() {

            //~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
            @Override
            public void onClick( View view ) {

                Intent intent = new Intent( Term_ChangingDetails_Activity.this, Term_CourseSelection_Activity.class );
                CourseData_List_Container courseData_List_Container2 = new CourseData_List_Container( courseData_List );

                intent.putExtra( "course_list_held", courseData_List_Container2 );

                //This code refers to course selection.
                startActivityForResult( intent, 1 );

            }
            //~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

        });


        recyclerView = findViewById( R.id.term_changingdetails_recyclerView_Array_in_XML );

        LinearLayoutManager linearLayoutManager = new LinearLayoutManager( this );


        //+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
        DividerItemDecoration dividerItemDecoration = new DividerItemDecoration(
                recyclerView.getContext(), linearLayoutManager.getOrientation() );

        recyclerView.addItemDecoration( dividerItemDecoration );
        recyclerView.setLayoutManager( linearLayoutManager );
        //+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++



        //==========================================================================================
        //TODO  THERE IS THE NEED TO POPULATE 'courseData_List' FROM SQLITE THROUGH A JSON STRING.
        //Testing purposes.


        if ( databaseHandling.getCourseDataCount() > 0 ) {

            int testInt = databaseHandling.getCourseData( 1 ).getCourseID().intValue();

            Log.v( "SUCCESS???  ", "TESTING TESTING TESTING courseID:  " + testInt );
            System.out.println( "TESTING TESTING TESTING courseID:  " + testInt );

        }


        if ( databaseHandling.getCourseDataCount() > 0 ) {

            CourseData courseData_entry = databaseHandling.getCourseData( 1 );

            //THE BELOW LINE CAUSES A CRASH.
            courseData_List.add( courseData_entry );

        }

        //==========================================================================================



        adapter = new Term_ChangingDetails_RecyclerView_Adapter( this, courseData_List );
        recyclerView.setAdapter( adapter );

    }


    public void reveal_StartingDate_DatePicker( View v ) {

        startingDateFragment = new DatePickerFragment_TERM_StartingDate();
        startingDateFragment.setArguments( dataArgument_Bundle_Example );
        startingDateFragment.show( getFragmentManager(), "starting date picker" );

    }


    public void setStartingDate_in_StartingDate_Button( String startingDate_for_Button ) {

        startingDate_Button.setText( startingDate_for_Button );

    }


    public void reveal_EndingDate_DatePicker( View view ) {

        endingDateFragment = new DatePickerFragment_TERM_EndingDate();
        endingDateFragment.setArguments( dataArgument_Bundle_Example );
        endingDateFragment.show( getFragmentManager(), "ending date picker" );

    }


    public void setEndingDate_in_EndingDate_Button( String endingDate_for_Button ) {

        endingDate_Button.setText( endingDate_for_Button );

    }


    @Override
    protected void onActivityResult( int requestCode, int resultCode, Intent data ) {

        //This code refers to course selection.
        if  ( requestCode == 1 ) {

            //==========================================================================================
            if( resultCode == Activity.RESULT_OK ){

                CourseData_List_Container test_CourseData_Container = data.getParcelableExtra( "course_list_chosen" );

                courseData_List = test_CourseData_Container.getCourseData_List();

                if ( courseData_List.isEmpty() == false ){

                    StringBuilder stringBuilder_Courses_in_List = new StringBuilder();

                    for ( CourseData courseData_Test : courseData_List ) {

                        stringBuilder_Courses_in_List.append( courseData_Test.getCourseID() + " " );

                    }


                    String result = "The following courseID numbers are in 'courseData_List':  " + stringBuilder_Courses_in_List;
                    Toast.makeText( Term_ChangingDetails_Activity.this, result, Toast.LENGTH_LONG ).show();

                }
                else {

                    String result = data.getStringExtra( "result" );
                    Toast.makeText( Term_ChangingDetails_Activity.this, result, Toast.LENGTH_LONG ).show();

                }

            }
            //==========================================================================================

            if ( resultCode == Activity.RESULT_CANCELED ) {

                Toast.makeText( Term_ChangingDetails_Activity.this, "No courses added or removed.",
                        Toast.LENGTH_LONG ).show();

            }
        }
    }


    //This is possibly for a future revision.
    @Override
    public void onItemClick( View view, int position ) {

    }


    @Override
    public void onResume() {

        super.onResume();

        //**************************************************************************
        adapter = new Term_ChangingDetails_RecyclerView_Adapter( this, courseData_List );
        adapter.setClickListener( this );
        recyclerView.setAdapter( adapter );
        //**************************************************************************

        adapter.notifyDataSetChanged();

    }

}
1
Wes Lange 14 Мар 2018 в 06:56

2 ответа

Лучший ответ

{{X0 }} возвращает неизменный список, в который нельзя добавлять элементы.

Использовать это

List< CourseData > courseData_List = new ArrayList<>();

Вместо этого

List< CourseData > courseData_List = Collections.emptyList();

Для получения дополнительной информации прочтите Collections.emptyList() vs. new instance .

1
Nilesh Rathod 14 Мар 2018 в 04:10

Collections.emptyList() возвращает неизменяемый список, который нельзя вызвать добавлением. использовать

new ArrayList() вместо

1
Nilesh Rathod 14 Мар 2018 в 04:08