Trouble pulling SQLite data to an array and populating TextViews in android studio

I have an application that allows students to create terms, courses, and assessments. The information that they input is stored in an SQLite database. One of the requirements for the application is that students have the ability to view course details, term details, and assessment details.

I have a SELECT query to pull course information from the database and a CourseDetailActivity class designed to display that data in an activity.xml file. It all works except it will always display the last entry to the database as opposed to the selected course. I cannot figure out why.

The course is selected via an image in the CourseViewHolder

Here are the relevant code snippets:

Database SELECT query:

    public List<String> getCourseDetails() {
    String selectedCourse = CourseViewHolder.courseTitle.getText().toString();
    String sql = "SELECT  *   FROM " +  TABLE_COURSES + " WHERE " + COURSE_TITLE + " LIKE " + "'%" + selectedCourse + "%'";
    SQLiteDatabase db = this.getReadableDatabase();
    List<String> courseDetails = new ArrayList<String>();
    Cursor cursor = db.rawQuery(sql, null);
    if(cursor.moveToFirst()){
        do{
            courseDetails.add(cursor.getString(0));
            courseDetails.add(cursor.getString(1));
            courseDetails.add(cursor.getString(2));
            courseDetails.add(cursor.getString(3));
            courseDetails.add(cursor.getString(4));
            courseDetails.add(cursor.getString(5));
            courseDetails.add(cursor.getString(6));
            courseDetails.add(cursor.getString(7));
            courseDetails.add(cursor.getString(8));
        }while (cursor.moveToNext());
    }
    cursor.close();
    db.close();

    return courseDetails;
}

This is the full code from the CourseDetailActivity class:

    public class CourseDetailActivity  extends AppCompatActivity {

private static final String TAG = CourseActivity.class.getSimpleName();

private TermTrackerDatabase mDatabase;
private ArrayList<Courses> allCourses=new ArrayList<>();
private ArrayList<Terms> allTermTitles=new ArrayList<>();
private CourseAdapter mAdapter;
private AdapterView<Adapter> statusSpinner;
private static List<String> getCourseDetails;
private List<String> mArrayList;

TextView title;
TextView start;
TextView end;
TextView status;
TextView name;
TextView phone;
TextView email;
TextView term;

@Override
protected void onCreate(Bundle savedInstanceState) {
    this.getSupportActionBar().setDisplayHomeAsUpEnabled(true);
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_course_details);

    title = (TextView) findViewById(R.id.course_title);
    start = (TextView) findViewById(R.id.course_start);
    end = (TextView) findViewById(R.id.course_end);
    status = (TextView) findViewById(R.id.course_status);
    name = (TextView) findViewById(R.id.instructor_name);
    phone = (TextView) findViewById(R.id.instructor_phone);
    email = (TextView) findViewById(R.id.instructor_email);
    term = (TextView) findViewById(R.id.term);

    TermTrackerDatabase db = new TermTrackerDatabase(getApplicationContext());
    List<String> courseDetails = db.getCourseDetails();

    title.setText(courseDetails.get(1));
    start.setText(courseDetails.get(2));
    end.setText(courseDetails.get(3));
    status.setText(courseDetails.get(4));
    name.setText(courseDetails.get(5));
    phone.setText(courseDetails.get(6));
    email.setText(courseDetails.get(7));
    term.setText(courseDetails.get(8));
};

private void addTaskDialog(){
    LayoutInflater inflater = LayoutInflater.from(this);
    View subView = inflater.inflate(R.layout.add_course_layout, null);


    final EditText titleField = subView.findViewById(R.id.enter_title);
    final EditText startField = subView.findViewById(R.id.enter_start);
    final EditText endField = subView.findViewById(R.id.enter_end);
    final Spinner statusSpinner = subView.findViewById(R.id.status_spinner);
    final EditText nameField = subView.findViewById(R.id.enter_name);
    final EditText phoneField = subView.findViewById(R.id.enter_phone);
    final EditText emailField = subView.findViewById(R.id.enter_email);
    final Spinner termSpinner = subView.findViewById(R.id.term_spinner);

    Spinner status_spinner = subView.findViewById(R.id.status_spinner);
  status_spinner.setOnItemSelectedListener((AdapterView.OnItemSelectedListener) this);
    ArrayAdapter<CharSequence> adapter = ArrayAdapter.createFromResource(this,
            R.array.status_array, android.R.layout.simple_spinner_item);
    adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
    status_spinner.setAdapter(adapter);

    TermTrackerDatabase db = new TermTrackerDatabase(getApplicationContext());
    List<String> termTitles = db.getTermTitles();

    Spinner term_spinner = subView.findViewById(R.id.term_spinner);
    ArrayAdapter<String> dataAdapter = new ArrayAdapter<>(this, android.R.layout.simple_spinner_item, termTitles);

    dataAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);

    term_spinner.setAdapter(dataAdapter);


    AlertDialog.Builder builder = new AlertDialog.Builder(this);

    builder.setTitle("Add New Course");
    builder.setView(subView);

    builder.create();

    builder.setPositiveButton("ADD COURSE", new DialogInterface.OnClickListener() {

        @Override
        public void onClick(DialogInterface dialog, int which) {
            final String title = titleField.getText().toString();
            final String start = startField.getText().toString();
            final String end = endField.getText().toString();
            final String status = statusSpinner.getSelectedItem().toString();
            final String name = nameField.getText().toString();
            final String phone = phoneField.getText().toString();
            final String email = emailField.getText().toString();
            final String term = termSpinner.getSelectedItem().toString();


            if(TextUtils.isEmpty(title)){
                Toast.makeText(CourseDetailActivity.this, "Something went wrong. Check your input values", Toast.LENGTH_LONG).show();
            }
            else{
                Courses newCourse = new Courses(title, start, end, status, name, phone, email, term);
                mDatabase.addCourse(newCourse);

                finish();
                startActivity(getIntent());
            }
        }
    });

    builder.setNegativeButton("CANCEL", new DialogInterface.OnClickListener() {
        @Override
        public void onClick(DialogInterface dialog, int which) {
            Toast.makeText(CourseDetailActivity.this, "Task cancelled", Toast.LENGTH_LONG).show();
        }
    });
    builder.show();

}


@Override
public boolean onOptionsItemSelected(MenuItem item) {
    switch (item.getItemId()) {
        case android.R.id.home:
            onBackPressed();
            return true;
    }

    return super.onOptionsItemSelected(item);
}}

And finally, the CourseAdapter class:

    public class CourseAdapter extends RecyclerView.Adapter<CourseViewHolder> implements Filterable {

private Context context;
private ArrayList<Courses> listCourses;
private ArrayList<Courses> mArrayList;

private TermTrackerDatabase mDatabase;

public CourseAdapter(Context context, ArrayList<Courses> listCourses) {
    this.context = context;
    this.listCourses = listCourses;
    this.mArrayList=listCourses;
    mDatabase = new TermTrackerDatabase(context);
}

@Override
public CourseViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
    View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.courses_list_layout, parent, false);
    return new CourseViewHolder(view);
}

@Override
public void onBindViewHolder(CourseViewHolder holder, int position) {
    final Courses courses = listCourses.get(position);
    Button editCourse;

    holder.courseTitle.setText(courses.getCourseTitle());
    holder.courseStart.setText(courses.getCourseStart());
    holder.courseEnd.setText(courses.getCourseEnd());

    String str1 = CourseViewHolder.courseTitle.getText().toString();
    String str2 = CourseViewHolder.courseStart.getText().toString();
    String str3 = CourseViewHolder.courseEnd.getText().toString();

    holder.viewCourse.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {

            Intent intent = new Intent(context, CourseDetailActivity.class);

            intent.putExtra("title_key", str1);
            intent.putExtra("start_key", str2);
            intent.putExtra("end_key", str3);

            context.startActivity(intent);
        }
    });

    holder.editCourse.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            editTaskDialog(courses);
        }
    });

    holder.deleteCourse.setOnClickListener(new View.OnClickListener() {

        @Override
        public void onClick(View view) {

            AlertDialog.Builder builder = new AlertDialog.Builder(context);
            builder.setTitle("Confirm Course Deletion");
            builder.create();

            builder.setPositiveButton("DELETE COURSE", new DialogInterface.OnClickListener() {
                @Override
                public void onClick(DialogInterface dialog, int which) {

                    //delete row from database
                    mDatabase.deleteCourse(courses.getId());
                    Toast.makeText(context, "Course deleted.", Toast.LENGTH_LONG).show();

                    //refresh the activity page.
                    ((Activity) context).finish();
                    context.startActivity(((Activity) context).getIntent());
                }
            });


            builder.setNegativeButton("CANCEL", new DialogInterface.OnClickListener() {
                @Override
                public void onClick(DialogInterface dialog, int which) {
                    Toast.makeText(context, "Delete cancelled", Toast.LENGTH_LONG).show();
                }
            });
            builder.show();
        }
    });
}

public class CourseDetailViewHolder {

}


    @Override
public Filter getFilter() {

    return new Filter() {
        @Override
        protected FilterResults performFiltering(CharSequence charSequence) {

            String charString = charSequence.toString();

            if (charString.isEmpty()) {

                listCourses = mArrayList;
            } else {

                ArrayList<Courses> filteredList = new ArrayList<>();

                for (Courses courses : mArrayList) {

                    if (courses.getCourseTitle().toLowerCase().contains(charString)) {

                        filteredList.add(courses);
                    }
                }

                listCourses = filteredList;
            }

            FilterResults filterResults = new FilterResults();
            filterResults.values = listCourses;
            return filterResults;
        }

        @Override
        protected void publishResults(CharSequence charSequence, FilterResults filterResults) {
            listCourses = (ArrayList<Courses>) filterResults.values;
            notifyDataSetChanged();
        }
    };
}


@Override
public int getItemCount() {
    return listCourses.size();
}


void editTaskDialog(final Courses courses){
    LayoutInflater inflater = LayoutInflater.from(context);
    View subView = inflater.inflate(R.layout.add_course_layout, null);

    final EditText titleField = subView.findViewById(R.id.enter_title);
    final EditText startField = subView.findViewById(R.id.enter_start);
    final EditText endField = subView.findViewById(R.id.enter_end);
    final Spinner statusSpinner =  subView.findViewById(R.id.status_spinner);
    final EditText instructorNameField = subView.findViewById(R.id.enter_name);
    final EditText instructorPhoneField = subView.findViewById(R.id.enter_phone);
    final EditText instructorEmailField = subView.findViewById(R.id.enter_email);
    final Spinner termSpinner = subView.findViewById(R.id.term_spinner);

    if(courses != null){
        titleField.setText(courses.getCourseTitle());
        startField.setText(String.valueOf(courses.getCourseStart()));
        endField.setText(String.valueOf(courses.getCourseEnd()));
        instructorNameField.setText(String.valueOf(courses.getInstructorName()));
        instructorPhoneField.setText(String.valueOf(courses.getInstructorPhone()));
        instructorEmailField.setText(String.valueOf(courses.getInstructorEmail()));
    }

    AlertDialog.Builder builder = new AlertDialog.Builder(context);
    builder.setTitle("Edit Course");
    builder.setView(subView);
    builder.create();

    builder.setPositiveButton("EDIT COURSE", new DialogInterface.OnClickListener() {
        @Override
        public void onClick(DialogInterface dialog, int which) {
            final String courseTitle = titleField.getText().toString();
            final String courseStart = startField.getText().toString();
            final String courseEnd = endField.getText().toString();
            final String status = statusSpinner.getSelectedItem().toString();
            final String instructorName = instructorNameField.getText().toString();
            final String instructorPhone = instructorPhoneField.getText().toString();
            final String instructorEmail = instructorEmailField.getText().toString();
            final String termTitle = termSpinner.getSelectedItem().toString();

            if(TextUtils.isEmpty(courseTitle)){
                Toast.makeText(context, "Something went wrong. Check your input values", Toast.LENGTH_LONG).show();
            }
            else{
                mDatabase.updateCourse(new Courses(courses.getId(), courseTitle, courseStart, courseEnd, status, instructorName, instructorPhone, instructorEmail, termTitle));
                //refresh the activity
                ((Activity)context).finish();
                context.startActivity(((Activity)context).getIntent());
            }
        }
    });

    builder.setNegativeButton("CANCEL", new DialogInterface.OnClickListener() {
        @Override
        public void onClick(DialogInterface dialog, int which) {
            Toast.makeText(context, "Task cancelled", Toast.LENGTH_LONG).show();
        }
    });
    builder.show();
}}

If I have only one course in the database, it works fine. If I add another course to the database, it always selects the last entry; Regardless of which course, the user selects.

I suspect the error lay in the

   String selectedCourse = CourseViewHolder.courseTitle.getText().toString();

Any guidance would be much appreciated. Thanks in advance for your expertise.

Leave a Comment