变量在onClickListeners之间重置为默认值

时间:2019-06-28 22:33:08

标签: java android

我不明白为什么我的变量会重置为默认值。我单击listView,它将变量currentAssessment设置为所检索记录的ID。然后,我单击以删除具有所选ID的记录,并且该记录已被重置。

package com.breathetaichi.classtracker;

import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.AdapterView;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.Toast;

import java.util.ArrayList;
import java.util.List;

public class CourseActivity extends AppCompatActivity {

    private static DBInterface db;
    private static ArrayList<Course> allCourses = new ArrayList<>();
    private static ArrayList<Assessment> allAssessments = new ArrayList<>();
    private static ArrayList<Instructor> allInstructors = new ArrayList<>();
    private int courseCalled;
    private int currentAssessment = -1;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_course);

//        currentAssessment = -1;

        db = new DBInterface(CourseActivity.this);
        db.getWritableDatabase();

        allCourses = db.getCourses();
        allAssessments = db.getAssessments();
        allInstructors = db.getInstructors();

        Bundle extras = getIntent().getExtras();
        courseCalled = extras.getInt("courseID");

        String courseTitle = "";
        int courseTermID = -1;
        int courseInstructorID = -1;
        String courseStartDateStr = "";
        String courseEndDateStr = "";
        String courseStatusStr = "";
        String courseNoteStr = "";
        for(Course course : allCourses) {
            if(course.getId() == courseCalled) {
                courseTitle = course.getTitle();
                courseTermID = course.getTermID();
                courseInstructorID = course.getInstructorID();
                courseStartDateStr = course.getStartDate();
                courseEndDateStr = course.getEndDate();
                courseStatusStr = course.getStatus();
                courseNoteStr = course.getNote();
            }
        }

        EditText courseName = findViewById(R.id.course_title);
        courseName.setText(courseTitle);
        EditText courseStartDate = findViewById(R.id.course_start_date);
        courseStartDate.setText(courseStartDateStr);
        EditText courseEndDate = findViewById(R.id.course_end_date);
        courseEndDate.setText(courseEndDateStr);
        EditText courseStatus = findViewById(R.id.course_status);
        courseStatus.setText(courseStatusStr);
        EditText termEndDate = findViewById(R.id.course_note);
        termEndDate.setText(courseNoteStr);

        int instructorID = courseInstructorID;
        String instructorNameStr = "";
        String instructorPhoneStr = "";
        String instructorEmailStr = "";

        for (Instructor instructor : allInstructors) {
            if(instructor.getId() == instructorID) {
                instructorNameStr = instructor.getName();
                instructorPhoneStr = instructor.getPhone();
                instructorEmailStr = instructor.getEmail();
            }
        }

        EditText instructorName = findViewById(R.id.instructor_name);
        instructorName.setText(instructorNameStr);
        EditText instructorPhone = findViewById(R.id.instructor_phone);
        instructorPhone.setText(instructorPhoneStr);
        EditText instructorEmail = findViewById(R.id.instructor_email);
        instructorEmail.setText(instructorEmailStr);

        List<Assessment> assessmentsInCourse = new ArrayList<>();
        for (Assessment assessment : allAssessments) {
            if(assessment.getCourseID() == courseCalled) {
                assessmentsInCourse.add(assessment);
            }
        }

        String[] titles = new String[assessmentsInCourse.size()];
        final int[] assessmentIDs = new int[assessmentsInCourse.size()];

        int i = 0;
        for(Assessment assessment : assessmentsInCourse) {
            titles[i] = assessment.getTitle();
            assessmentIDs[i] = assessment.getId();
            i++;
        }

        final android.widget.ListAdapter adapter = new ListAdapter(this, titles);
        final ListView lv = findViewById(R.id.assessment_list_view);

        lv.setAdapter(adapter);
        lv.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> adapterView, View view, int position, long id) {

                int currentAssessment = assessmentIDs[(int)id];
                System.out.println("set to clicked id, currentAssessment = " + currentAssessment);

                Assessment assessment = getAssessment(currentAssessment);

                String assessmentNameStr = assessment.getTitle();
                String assessmentTypeStr = assessment.getType();
                String assessmentDueStr = assessment.getDueDate();

                EditText assessmentName = findViewById(R.id.assessment_title);
                assessmentName.setText(assessmentNameStr);
                EditText assessmentType = findViewById(R.id.assessment_type);
                assessmentType.setText(assessmentTypeStr);
                EditText assessmentDue = findViewById(R.id.assessment_due);
                assessmentDue.setText(assessmentDueStr);

                System.out.println("end of onclickListener, currentAssessment = " + currentAssessment);
            }
        });
        System.out.println("After listener, currentAssessment = " + currentAssessment);
    }

    public void deleteCourseButton(View v) {

        if(courseCalled == -1) {
            Toast.makeText(CourseActivity.this,
                    "No saved term to delete,\nplease use back button.",
                    Toast.LENGTH_SHORT).show();

        } else {
            for(Course course : allCourses) {
                if(course.getId() == courseCalled) {
                    db.deleteCourse(courseCalled);
                    TermActivity.numberOfCourses--;
                }
            }
            this.recreate();
        }
    }

    public void saveCourseButton(View v) {

        Course saveCourse = new Course();

        for(Course course : allCourses) {
            if(courseCalled == course.getId()) {
                saveCourse = course;
            }
        }

        String courseTitle;
        int courseTermID = saveCourse.getTermID();
        int courseInstructorID = saveCourse.getInstructorID();
        String courseStartDateStr;
        String courseEndDateStr;
        String courseStatusStr;
        String courseNoteStr;

        EditText courseName = findViewById(R.id.course_title);
        courseTitle = courseName.getText().toString();
        EditText courseStartDate = findViewById(R.id.course_start_date);
        courseStartDateStr = courseStartDate.getText().toString();
        EditText courseEndDate = findViewById(R.id.course_end_date);
        courseEndDateStr = courseEndDate.getText().toString();
        EditText courseStatus = findViewById(R.id.course_status);
        courseStatusStr = courseStatus.getText().toString();
        EditText courseNote = findViewById(R.id.course_note);
        courseNoteStr = courseNote.getText().toString();

        String instructorNameStr;
        String instructorPhoneStr;
        String instructorEmailStr;

        EditText instructorName = findViewById(R.id.instructor_name);
        instructorNameStr = instructorName.getText().toString();
        EditText instructorPhone = findViewById(R.id.instructor_phone);
        instructorPhoneStr = instructorPhone.getText().toString();
        EditText instructorEmail = findViewById(R.id.instructor_email);
        instructorEmailStr = instructorEmail.getText().toString();

        if(courseTitle.isEmpty()
                || courseStartDateStr.isEmpty()
                || courseEndDateStr.isEmpty()
                || courseStatusStr.isEmpty()
                || courseNoteStr.isEmpty()) {

            Toast.makeText(CourseActivity.this, "Please fill course fields.",
                    Toast.LENGTH_SHORT).show();

        } else if(instructorNameStr.isEmpty()
                || instructorPhoneStr.isEmpty()
                || instructorEmailStr.isEmpty()) {

            Toast.makeText(CourseActivity.this, "Please fill instructor fields.",
                    Toast.LENGTH_SHORT).show();
        } else {
            // Check if new course courseCalled is -1 or if not update with id in courseCalled
            if(courseCalled == -1) {
                courseTermID = TermActivity.activeTerm.getId();

                // Insert new instructor and get their ID back
                courseInstructorID = (int) db.insertInstructor(instructorNameStr,
                        instructorPhoneStr, instructorEmailStr);

                courseCalled = (int) db.insertCourse(courseTermID,
                        courseInstructorID, courseTitle, courseStartDateStr,
                        courseEndDateStr, courseStatusStr, courseNoteStr);

                allCourses = db.getCourses();

                Toast.makeText(CourseActivity.this, "New course saved.",
                        Toast.LENGTH_SHORT).show();

                this.recreate();
            } else {
                // Insert new instructor and get their ID back
                courseInstructorID = (int) db.insertInstructor(instructorNameStr,
                        instructorPhoneStr, instructorEmailStr);

                db.updateCourse(courseCalled, courseTermID, courseInstructorID, courseTitle,
                        courseStartDateStr, courseEndDateStr, courseStatusStr, courseNoteStr);

                allCourses = db.getCourses();

                Toast.makeText(CourseActivity.this, "Course updated.",
                        Toast.LENGTH_SHORT).show();

                this.recreate();
            }
        }
    }

    public void saveAssessmentButton(View v) {

        String assessmentNameStr;
        String assessmentTypeStr;
        String assessmentDueStr;

        EditText assessmentName = findViewById(R.id.assessment_title);
        assessmentNameStr = assessmentName.getText().toString();
        EditText assessmentType = findViewById(R.id.assessment_type);
        assessmentTypeStr = assessmentType.getText().toString();
        EditText assessmentDue = findViewById(R.id.assessment_due);
        assessmentDueStr = assessmentDue.getText().toString();

        if(assessmentDueStr.isEmpty() || assessmentNameStr.isEmpty() || assessmentTypeStr.isEmpty()) {
            Toast.makeText(CourseActivity.this, "Please fill all fields.",
                    Toast.LENGTH_SHORT).show();
        } else {
            if (currentAssessment == -1) {

                currentAssessment = (int) db.insertAssessment(courseCalled, assessmentNameStr,
                        assessmentTypeStr, assessmentDueStr);

                allAssessments = db.getAssessments();

                Toast.makeText(CourseActivity.this, "Assessment added.",
                        Toast.LENGTH_SHORT).show();
                this.recreate();
            } else {

                db.updateAssessment(currentAssessment, courseCalled, assessmentNameStr,
                        assessmentTypeStr, assessmentDueStr);

                allAssessments = db.getAssessments();

                Toast.makeText(CourseActivity.this, "Assessment updated.",
                        Toast.LENGTH_SHORT).show();
                this.recreate();
            }
        }
    }

    public void newAssessmentButton(View v) {

        EditText assessmentName = findViewById(R.id.assessment_title);
        assessmentName.setText("");
        EditText assessmentType = findViewById(R.id.assessment_type);
        assessmentType.setText("");
        EditText assessmentDue = findViewById(R.id.assessment_due);
        assessmentDue.setText("");

        currentAssessment = -1;
    }

    public void deleteAssessmentButton(View v) {
        System.out.println("start of deleteAssessmentButton, currentAssessment = " + currentAssessment);
        if(currentAssessment == -1) {
            System.out.println("currentAssessment = " + currentAssessment);

            EditText assessmentName = findViewById(R.id.assessment_title);
            assessmentName.setText("");
            EditText assessmentType = findViewById(R.id.assessment_type);
            assessmentType.setText("");
            EditText assessmentDue = findViewById(R.id.assessment_due);
            assessmentDue.setText("");

            Toast.makeText(CourseActivity.this, "No assessment chosen.",
                    Toast.LENGTH_SHORT).show();
        } else {
            System.out.println("sending to delete assessment id: " + currentAssessment);
            long result = db.deleteAssessment(currentAssessment);

            if(result == -1) {
                Toast.makeText(CourseActivity.this, "Assessment NOT deleted.",
                        Toast.LENGTH_SHORT).show();

            } else {
                Toast.makeText(CourseActivity.this, "Assessment deleted.  result = " + result,
                        Toast.LENGTH_SHORT).show();

                allAssessments = db.getAssessments();

                this.recreate();
            }
        }
    }

    public Assessment getAssessment(int id) {
        Assessment assessment = new Assessment();

        for(Assessment asmt : allAssessments) {
            if(asmt.getId() == id) {
                assessment = asmt;
            }
        }
        return assessment;
    }
}

我已经检查并重新检查了代码,在单击listView和单击Delete按钮(应重置活动)之间找不到任何位置。这是在listView onClick之后自动发生的吗?还有另一种方式来跟踪ID吗?

1 个答案:

答案 0 :(得分:3)

您似乎有两个currentAssessment变量。一个是该类专用的,另一个是局限于onItemClick范围内的。一旦onItemClick退出,您就失去了该分配,在您引用currentAssessment的其他任何地方,它都是属于该类的那个,仍为-1。

解决方法是为currentAssessment使用类onItemClick

lv.setOnItemClickListener(new AdapterView.OnItemClickListener() {
        @Override
        public void onItemClick(AdapterView<?> adapterView, View view, int position, long id) {

            currentAssessment = assessmentIDs[(int)id];
            System.out.println("set to clicked id, currentAssessment = " + currentAssessment);

            Assessment assessment = getAssessment(currentAssessment);

            String assessmentNameStr = assessment.getTitle();
            String assessmentTypeStr = assessment.getType();
            String assessmentDueStr = assessment.getDueDate();

            EditText assessmentName = findViewById(R.id.assessment_title);
            assessmentName.setText(assessmentNameStr);
            EditText assessmentType = findViewById(R.id.assessment_type);
            assessmentType.setText(assessmentTypeStr);
            EditText assessmentDue = findViewById(R.id.assessment_due);
            assessmentDue.setText(assessmentDueStr);

            System.out.println("end of onclickListener, currentAssessment = " + currentAssessment);
        }
    });