Java 在AlertDialog中使用上下文函数从MainActivity获取方法时出现问题

Java 在AlertDialog中使用上下文函数从MainActivity获取方法时出现问题,java,android,database,oop,Java,Android,Database,Oop,我的MainActivity()中有这段代码,用于计算总记录数并读取它 public void countRecords() { int recordCount = new TableControllerStudent(this).count(); TextView textViewRecordCount = (TextView) findViewById(R.id.textViewRecordCount); textViewRecordCount.setText(re

我的MainActivity()中有这段代码,用于计算总记录数并读取它

public void countRecords() {
    int recordCount = new TableControllerStudent(this).count();

    TextView textViewRecordCount = (TextView) findViewById(R.id.textViewRecordCount);
    textViewRecordCount.setText(recordCount + " records found.");

}

public void readRecords() {

    LinearLayout linearLayoutRecords = (LinearLayout) findViewById(R.id.linearLayoutRecords);
    linearLayoutRecords.removeAllViews();

    List<ObjectStudent> students = new TableControllerStudent(this).read();

    if (students.size() > 0) {

        for (ObjectStudent obj : students) {

            int id = obj.id;
            String studentFirstname = obj.firstname;
            String studentEmail = obj.email;

            String textViewContents = studentFirstname + " - " + studentEmail;

            TextView textViewStudentItem= new TextView(this);
            textViewStudentItem.setPadding(0, 10, 0, 10);
            textViewStudentItem.setText(textViewContents);
            textViewStudentItem.setTag(Integer.toString(id));

            linearLayoutRecords.addView(textViewStudentItem);
        }

    }

    else {

        TextView locationItem = new TextView(this);
        locationItem.setPadding(8, 8, 8, 8);
        locationItem.setText("No records yet.");

        linearLayoutRecords.addView(locationItem);
    }
}
错误日志:

2020-01-31 11:39:18.357 12917-12917/com.example.coba_crud_db_1 E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.example.coba_crud_db_1, PID: 12917
java.lang.ClassCastException: com.android.internal.policy.DecorContext cannot be cast to com.example.coba_crud_db_1.MainActivity
    at com.example.coba_crud_db_1.OnClickListenerCreateStudent$1.onClick(OnClickListenerCreateStudent.java:46)
    at androidx.appcompat.app.AlertController$ButtonHandler.handleMessage(AlertController.java:167)
    at android.os.Handler.dispatchMessage(Handler.java:106)
    at android.os.Looper.loop(Looper.java:201)
    at android.app.ActivityThread.main(ActivityThread.java:6810)
    at java.lang.reflect.Method.invoke(Native Method)
    at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:547)
    at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:873)
    2020-01-31 11:39:18.417 12917-12917/com.example.coba_crud_db_1 I/Process: Sending signal. PID: 
    12917 SIG: 9
问题出现在((MainActivity)上下文中;和((MainActivity)上下文);我想是吧。
我尝试了不同的代码,但它不起作用,如果im添加新记录,它将被强制关闭。

您能分享显示警报拨号的代码吗?此外,将上下文转换为活动也不是一个好的做法。当您有一个很大的代码库,并且同一个对话框会被多次使用时,这将是一个问题。最好创建一个接口并传递给alertdialog,并在活动/片段中使用接口回调。

如果在主活动中使用Alert Dialog方法,请尝试此操作

new AlertDialog.Builder(MainActivity.this)
            .setView(formElementsView)
            .setTitle("Create Student")
            .setPositiveButton("Add",
                    new DialogInterface.OnClickListener() {
                        getApplicationContext()
                        public void onClick(DialogInterface dialog, int id) {
                            String studentFirstname = editTextStudentFirstname.getText().toString();
                            String studentEmail = editTextStudentEmail.getText().toString();

                            ObjectStudent objectStudent = new ObjectStudent();
                            objectStudent.firstname= studentFirstname;
                            objectStudent.email= studentEmail;

                            boolean createSuccessful = new TableControllerStudent(context).create(objectStudent);

                            if(createSuccessful){
                                Toast.makeText(context, "Student information was saved.", Toast.LENGTH_SHORT).show();

                            }else{
                                Toast.makeText(context, "Unable to save student information.", Toast.LENGTH_SHORT).show();
                            }
                            ((MainActivity)context).countRecords();
                            ((MainActivity)context).readRecords();
                            dialog.cancel();
                        }
                    }).show();

onClickListenerCreateStudion
内创建构造函数,并将活动的引用传递给构造函数,如:

public class OnClickListenerCreateStudent implements View.OnClickListener {

    MainActivity activity;

    public OnClickListenerCreateStudent(MainActivity activity)
    {
        this.activity=activity;
    }

    @Override
    public void onClick(View view) {
      //  final Context context = view.getRootView().getContext();

        LayoutInflater inflater = (LayoutInflater) activity.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
        final View formElementsView = inflater.inflate(R.layout.student_input_form, null, false);

        final EditText editTextStudentFirstname = (EditText) formElementsView.findViewById(R.id.editTextStudentFirstname);
        final EditText editTextStudentEmail = (EditText) formElementsView.findViewById(R.id.editTextStudentEmail);

        new AlertDialog.Builder(activity)
                .setView(formElementsView)
                .setTitle("Create Student")
                .setPositiveButton("Add",
                        new DialogInterface.OnClickListener() {
                            public void onClick(DialogInterface dialog, int id) {
                                String studentFirstname = editTextStudentFirstname.getText().toString();
                                String studentEmail = editTextStudentEmail.getText().toString();

                                ObjectStudent objectStudent = new ObjectStudent();
                                objectStudent.firstname= studentFirstname;
                                objectStudent.email= studentEmail;

                                boolean createSuccessful = new TableControllerStudent(context).create(objectStudent);

                                if(createSuccessful){
                                    Toast.makeText(context, "Student information was saved.", Toast.LENGTH_SHORT).show();

                                }else{
                                    Toast.makeText(context, "Unable to save student information.", Toast.LENGTH_SHORT).show();
                                }
                                ((MainActivity)context).countRecords();
                                dialog.cancel();
                            }
                        }).show();
    }
}
我不知道您在哪里设置了
onClickListenerCreateStudion
,但称之为:

view.setOnClickListener(new OnClickListenerCreateStudent(mainActivityReference));

您可以添加OnListenerCreateStudio定义的完整代码,也可以从调用OnListenerCreateStudentAvoid的位置使用“this”作为上下文来创建小部件,并使用getActivityContext()来避免内存泄漏。使用“(MainActivity)上下文也是如此,请改用getApplicationContext()。通过这种方式,您应该避免创建和保存无用的引用以及糟糕的上下文用法。我已经将其编辑为完整代码@surajvaishnavy,您在那里实例化了OnClickListenerCreateStuden?我没有找到新的onClickListenerCreateStudion()@Rildira请检查我的答案,如果您遇到任何问题,请告诉我。
view.setOnClickListener(new OnClickListenerCreateStudent(mainActivityReference));