如何重用来自不同类的方法

时间:2018-01-01 01:54:13

标签: java android firebase code-reuse

我有一个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 个答案:

答案 0 :(得分:1)

As the method you want to reuse should be "public" first of all. It simply means that it can be publically accessed among other classes of that project. And after making it public you can simply refer it using the class name.

Here is an example of this :

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

But in your case, you will have to copy and paste the code to another class file only. Reason: Because you are fetching data from the layout file of your Java file and this will crash the app. Either you should further modularize your code and handle this by making a separate function for fetching all this data. Otherwise, copy pasting only a method from one class to another will not make your application run into any performance issue or lags.

答案 1 :(得分:1)

由于int wallChoosen=rand_a_b( 1, 3);是来自onDataChange(DataSnapshot dataSnapshot)的异步回调事件,因此您必须实现自己的回调方法以获得结果通知。

一种方法是使用接口。

创建一个单独的类Auth

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();
}

需要的地方

答案 2 :(得分:0)

访问修饰符不正确。好老的java doc会比我更好解释: access modifiers

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

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

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

答案 3 :(得分:0)

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

  1. 如上所述,拥有private在重复使用方面并没有那么好。

  2. 看起来databaseRef对象是一个类属性。所以你需要传入它,而不是依赖于该类的class属性,因为你想从另一个类中使用它。 (或者你可以将这个方法和databaseRef属性放在一个超类中,让你的两个类继承它。)

  3. 一般而言 - 考虑您的方法需要做什么,然后需要做什么。这些应该决定如何使代码的其他部分更方便地使用该方法。