简体   繁体   English

将方法移动到另一个 Java 类,并从原始类中调用该方法

[英]Move method to another Java class, and call the method from the original class

Dear valued program gurus!尊敬的节目大师们!

I need help on moving a method to another Java class.我需要有关将方法移动到另一个 Java 类的帮助。

I am having a Java class called ProfileList.java containing the following code:我有一个名为 ProfileList.java 的 Java 类,其中包含以下代码:

package dk.timeleft.versionone;

import androidx.appcompat.app.AppCompatActivity;

import android.os.AsyncTask;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
import android.widget.Toast;

import org.json.JSONException;
import org.json.JSONObject;

import java.io.IOException;

import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.FormBody;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.RequestBody;
import okhttp3.Response;

public class ProfileList extends AppCompatActivity {

    Button btnGet;
    Button btnPost;
    TextView txtResult;

    public String url;
    public String postUrl;


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

        btnGet = (Button) findViewById(R.id.btnGet);
        btnPost = (Button) findViewById(R.id.btnPost);
        txtResult = (TextView) findViewById(R.id.txtResult);


        btnGet.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                txtResult.setText("Retrieving GET-data");
                url = "https://kairosplanner.com/api/timeleft.php";
                try {
                    getResponse();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        });

        btnPost.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                txtResult.setText("Retrieving POST-data");

                postUrl = "https://kairosplanner.com/api/timeleft2.php/";
                RequestBody postBody = new FormBody.Builder()
                        .add("first_name", "Hans")
                        .add("last_name", "Schmidt")
                        .build();
                try {
                    postRequest(postUrl, postBody);
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        });

    }

    void postRequest(String postUrl, RequestBody postBody) throws IOException {

        OkHttpClient client = new OkHttpClient();

        Request request = new Request.Builder()
                .url(postUrl)
                .post(postBody)
                .build();

        client.newCall(request).enqueue(new Callback() {
            @Override
            public void onFailure(Call call, IOException e) {
                call.cancel();
            }

            @Override
            public void onResponse(Call call, Response response) throws IOException {

                final String myResponse = response.body().string();

                ProfileList.this.runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        try {
                            JSONObject json = new JSONObject(myResponse);
                            //txtString.setText("First Name: "+json.getJSONObject("data").getString("first_name") + "\nLast Name: " + json.getJSONObject("data").getString("last_name"));
                            txtResult.setText(json.toString());
                        } catch (JSONException e) {
                            e.printStackTrace();
                        }
                    }
                });

            }
        });
    }


    void getResponse() throws IOException {

        OkHttpClient client = new OkHttpClient();

        Request request = new Request.Builder()
                .url(url)
                .build();

        client.newCall(request).enqueue(new Callback() {
            @Override
            public void onFailure(Call call, IOException e) {
                call.cancel();
            }

            @Override
            public void onResponse(Call call, Response response) throws IOException {

                final String myResponse = response.body().string();

                ProfileList.this.runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        try {

                            JSONObject json = new JSONObject(myResponse);
                            //txtString.setText("First Name: "+json.getJSONObject("data").getString("first_name") + "\nLast Name: " + json.getJSONObject("data").getString("last_name"));
                            txtResult.setText(json.toString());
                            Toast.makeText(ProfileList.this,"Hello",Toast.LENGTH_SHORT).show();

                        } catch (JSONException e) {
                            e.printStackTrace();
                        }
                    }
                });

            }
        });
    }

    public class OkHttpHandler extends AsyncTask<String, Void, String> {

        OkHttpClient client = new OkHttpClient();

        @Override
        protected String doInBackground(String... params) {

            Request.Builder builder = new Request.Builder();
            builder.url(params[0]);
            Request request = builder.build();

            try {
                Response response = client.newCall(request).execute();
                return response.body().string();
            } catch (Exception e) {
                e.printStackTrace();
            }
            return null;
        }

        @Override
        protected void onPostExecute(String s) {
            super.onPostExecute(s);
            //txtString.setText(s);
        }
    }

}

This is working without any problems, but I'd like to have my code clean an neat.这工作没有任何问题,但我想让我的代码干净整洁。 I will be using the POST and GET functions (postRequest and getResponse methods) often, also in other Java classes, so it would be better, I guess, if those methods, including the OkHttpHandler class, to a separate Java class, eg ApiCommunicator.java, and call the methods from there.我将经常使用 POST 和 GET 函数(postRequest 和 getResponse 方法),也在其他 Java 类中使用,所以我想,如果将这些方法(包括 OkHttpHandler 类)用于单独的 Java 类(例如 ApiCommunicator)会更好。 java,并从那里调用方法。

I found a lot of information on how to refactor, but that just deletes the current ProfileList.java class.我找到了很多关于如何重构的信息,但这只会删除当前的 ProfileList.java 类。

I also tried just to copy the methods (postRequest, getResponse and OkHttpHandler to ApiCommunicator.java (and afterwards delete these methods from ProfileList.java), but that gives a few other problems, eg the .runOnUiThread runnable within the OnResponse method in postRequest and getResponse - those refer to ProfileList.this in stead of a dynamic Java class.我还尝试将方法(postRequest、getResponse 和 OkHttpHandler 复制到 ApiCommunicator.java(然后从 ProfileList.java 中删除这些方法),但这会带来一些其他问题,例如 postRequest 中 OnResponse 方法中的 .runOnUiThread 可运行和getResponse - 那些引用 ProfileList.this 而不是动态 Java 类。

So my question is: how do I move a method from one class to another, and call the method from the original class?所以我的问题是:如何将方法从一个类移动到另一个类,并从原始类中调用该方法?

BTW: I am using IntelliJ顺便说一句:我正在使用 IntelliJ

I hope somebody can help me with this problem.我希望有人能帮助我解决这个问题。

EDITED: Added ApiCommunicatorListener interface to ApiCommunicator that needs to be implemented by ProfileList activity to get the result back and assign it to txtResult.编辑:ApiCommunicator添加了ApiCommunicatorListener接口,该接口需要由 ProfileList 活动实现以取回结果并将其分配给 txtResult。

You could create your ApiCommunicator class like so:你可以像这样创建你的 ApiCommunicator 类:

public class ApiCommunicator<T extends AppCompatActivity & ApiCommunicator.ApiCommunicatorListener> {

    private T activity;

    public ApiCommunicator(T activity) {
        this.activity = activity;
    }

    public void postRequest(String postUrl, RequestBody postBody) throws IOException {

        OkHttpClient client = new OkHttpClient();

        Request request = new Request.Builder()
                .url(postUrl)
                .post(postBody)
                .build();

        client.newCall(request).enqueue(new Callback() {
            @Override
            public void onFailure(Call call, IOException e) {
                call.cancel();
            }

            @Override
            public void onResponse(Call call, Response response) throws IOException {

                final String myResponse = response.body().string();

                activity.runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        try {
                            JSONObject json = new JSONObject(myResponse);
                            activity.postRequestResult(json.toString());
                        } catch (JSONException e) {
                            e.printStackTrace();
                        }
                    }
                });

            }
        });
    }

    public void getResponse() throws IOException {

        OkHttpClient client = new OkHttpClient();

        Request request = new Request.Builder()
                .url(url)
                .build();

        client.newCall(request).enqueue(new Callback() {
            @Override
            public void onFailure(Call call, IOException e) {
                call.cancel();
            }

            @Override
            public void onResponse(Call call, Response response) throws IOException {

                final String myResponse = response.body().string();

                activity.runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        try {
                            JSONObject json = new JSONObject(myResponse);
                            activity.getResponseResult(json.toString());
                        } catch (JSONException e) {
                            e.printStackTrace();
                        }
                    }
                });

            }
        });
    }

    public interface ApiCommunicatorListener {
        void postRequestResult(String result);
        void getResponseResult(String result);
    }
}

After that, you need to implement the interface in ProfileList activity like so:之后,您需要在 ProfileList 活动中实现接口,如下所示:

public class ProfileList extends AppCompatActivity implements ApiCommunicator.ApiCommunicatorListener {

Then you're gonna add those two methods to ProfileList:然后你要把这两个方法添加到 ProfileList 中:

@Override
public void postRequestResult(String result) {
    txtResult.setText(result);
}

@Override
public void getResponseResult(String result) {
    txtResult.setText(result);
}

And finally use ApiCommunicator:最后使用 ApiCommunicator:

ApiCommunicator apiCommunicator = new ApiCommunicator<>(this);
apiCommunicator.postRequest(...);
apiCommunicator.getRequest(...);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM