代码之家  ›  专栏  ›  技术社区  ›  Samir

如何重用不同类中的方法

  •  2
  • Samir  · 技术社区  · 7 年前

    我有一个authenticateID方法,它在数据库中搜索以找到匹配项并执行一些操作。我想这需要很长时间来解释,所以下面是我的代码:

    public boolean authenticateStudentID() {
    
        boolean success = true;
    
        final String studentID = etStudentID.getText().toString().trim();
        final String module = etModule.getText().toString().trim();
        final String degree = etDegree.getText().toString().trim();
        final String room = etRoom.getText().toString().trim();
        final String email = etEmail.getText().toString().trim();
        final String fullname = etfullname.getText().toString().trim();
        final String loginID = etLoginID.getText().toString().trim();
    
        if (success) {
            databaseRef.addListenerForSingleValueEvent(new ValueEventListener() {
                public void onDataChange(DataSnapshot dataSnapshot) {
                    for (DataSnapshot snapshot : dataSnapshot.getChildren()) { // wtf is this advanecd for loop
                        //map string string because our key is a string and value is a string, map has a key and value object
                        Map<String, String> map = (Map) snapshot.getValue();
                        if (map != null) { //if the values and keys are not null
                            String studentIDMatch = map.get("studentID");
    
                          //  Log.v("E_VALUE", "students ID entered : " + studentIDMatch);
                          //  Log.v("E_VALUE", "students ID from db: " + studentID);
                            if (studentID.equals(studentIDMatch)) {
                                String uniqueKey = databaseRef.push().getKey();
    
                                NewStudentAccounts sam = new NewStudentAccounts
                                        (studentID, loginID, email, fullname, module, degree, room);
    
                                databaseRef.child(uniqueKey).setValue(sam);
    
                                Toast.makeText(getApplicationContext(), "Your account registration has been successful!", Toast.LENGTH_SHORT).show();
                                startActivity(new Intent(getApplicationContext(), LoginActivity.class));
                            } else {
                                Toast.makeText(getApplicationContext(), "Invalid Student Credentials Entered!!", Toast.LENGTH_SHORT).show();
                            }
                        }
                    }
                }
    
                @Override
                public void onCancelled(DatabaseError databaseError) {
                }
            });
        }
        return success;
    

    我想知道如何在另一个类中重用此方法,而不是复制和粘贴代码。请引导我,我真的很感激。

    private void addNewStudent() {
    
        findViewById(R.id.buttonAddStudent).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
    
                View addStudentActivityDialog = LayoutInflater.from(LecturerAccount.this).inflate(R.layout.activity_add_student,null);
    
                etStudentName = addStudentActivityDialog.findViewById(R.id.editTextStudentName);
                etStudentUserID = addStudentActivityDialog.findViewById(R.id.editTextStudentUserID);
    
                AlertDialog.Builder addStudentBuilder = new AlertDialog.Builder(LecturerAccount.this);
    
                addStudentBuilder.setMessage("STAR").setView(addStudentActivityDialog).setPositiveButton("Ok", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialogInterface, int i) {
                        String studentName = etStudentName.getText().toString();
                        String studentID = etStudentUserID.getText().toString();
    
                        registerActivity = new RegisterActivity(); //calling the instance of the class here
    
                        if (registerActivity.authenticateStudentID() == true){
                            studentarray.add(studentName);
                        }
    
                    }
                }).setNegativeButton("cancel", null).setCancelable(false);
                AlertDialog newStudentDialog = addStudentBuilder.create();
                newStudentDialog.show();
            }
        });
    
    }
    

    我的if语句在这里调用函数,我在这里完全不知道。

    4 回复  |  直到 7 年前
        1
  •  1
  •   AbdulAli    7 年前

    自从 onDataChange(DataSnapshot dataSnapshot) 是来自的异步回调事件 firebase 您必须实现自己的回调方法才能获得结果通知。

    一种方法是使用接口。

    创建单独的类身份验证

    public class Auth {
    
    public static void authenticateStudentID(final String studentID, final AuthListener listener) {
    
        DatabaseReference databaseRef = FirebaseDatabase.getInstance().getReference("your reference");
    
        databaseRef.addListenerForSingleValueEvent(new ValueEventListener() {
            public void onDataChange(DataSnapshot dataSnapshot) {
                for (DataSnapshot snapshot : dataSnapshot.getChildren()) { // wtf is this advanecd for loop
                    //map string string because our key is a string and value is a string, map has a key and value object
                    Map<String, String> map = (Map) snapshot.getValue();
                    if (map != null) { //if the values and keys are not null
                        String studentIDMatch = map.get("studentID");
    
                        if (studentID.equals(studentIDMatch)) {
    
                            if (listener != null)
                                listener.onAuthSuccess();
    
    
                        } else {
    
                            if (listener != null)
                                listener.onAuthFailure();
                        }
                    }
                }
            }
    
            @Override
            public void onCancelled(DatabaseError databaseError) {
                if (listener != null)
                    listener.onAuthFailure();
            }
        });
    }
    
    public interface AuthListener {
        void onAuthSuccess();
    
        void onAuthFailure();
    }
    

    }

    然后打电话过来

    Auth.authenticateStudentID(studentId, new Auth.AuthListener() {
            @Override
            public void onAuthSuccess() {
    
            }
    
            @Override
            public void onAuthFailure() {
    
            }
        });
    

    在需要的地方

        2
  •  1
  •   Sudhanshu Vohra    7 年前

    因为要重用的方法首先应该是“public”。这仅仅意味着它可以在该项目的其他类中公开访问。公开后,您可以使用类名简单地引用它。

    以下是一个例子:

    Class2 instance = new Class2();
    instance.publicMehtodToBeAcessedInThisClass(any parameters);
    

    但在您的情况下,您只需将代码复制并粘贴到另一个类文件。 原因:因为您正在从Java文件的布局文件中提取数据,这将导致应用程序崩溃。或者您应该进一步模块化代码,并通过创建一个单独的函数来获取所有这些数据来处理这个问题。否则,仅将一个方法从一个类复制粘贴到另一个类不会使应用程序遇到任何性能问题或延迟。

        3
  •  0
  •   Zeta Reticuli    7 年前

    访问修饰符不正确。好的旧java文档会比我更好地解释: access modifiers

    要访问它,必须创建如下实例:

    YourClass yourClass = new YourClass();
    yourCLass.authenticateStudentID();
    

    YourClass通常是粘贴代码所在的文件的名称。

        4
  •  0
  •   Prisoner    7 年前

    根据您所展示的内容,您需要处理两个问题:

    1. 如前所述 private 在重用方面对您没有多大好处。

    2. 看起来像 databaseRef 对象是类属性。因此,您需要传入它,而不是依赖该类的class属性,因为您想从另一个类使用它。(或者您可以将此方法 数据库参考 属性,并使您的两个类从中继承。)

    一般来说,请思考您的方法需要什么 ,然后是什么 需要 这样做。这些应该决定如何使该方法从代码的其他部分更可用。