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

标签 java android intellij-idea

尊敬的程序专家!

我需要帮助将方法移动到另一个 Java 类。

我有一个名为 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);
        }
    }

}

这工作没有任何问题,但我想让我的代码干净整洁。 我将经常使用 POST 和 GET 函数(postRequest 和 getResponse 方法),也在其他 Java 类中使用,所以我想,如果这些方法(包括 OkHttpHandler 类)到一个单独的 Java 类(例如ApiCommunicator.java,并从那里调用方法。

我找到了很多关于如何重构的信息,但这只是删除了当前的 ProfileList.java 类。

我还尝试将方法(postRequest、getResponse 和 OkHttpHandler 复制到 ApiCommunicator.java(然后从 ProfileList.java 中删除这些方法),但这会带来一些其他问题,例如 OnResponse 方法中的 .runOnUiThread 可运行在 postRequest 和 getResponse 中 - 它们引用 ProfileList.this 而不是动态 Java 类。

所以我的问题是:如何将方法从一个类移动到另一个类,并从原始类调用该方法?

顺便说一句:我正在使用 IntelliJ

我希望有人能帮我解决这个问题。

最佳答案

已编辑:ApiCommunicator 添加了 ApiCommunicatorListener 接口(interface),该接口(interface)需要由 ProfileList Activity 实现以获取结果并将其分配给 txtResult。

您可以像这样创建 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);
    }
}

之后,您需要在 ProfileList Activity 中实现接口(interface),如下所示:

public class ProfileList extends AppCompatActivity implements ApiCommunicator.ApiCommunicatorListener {

然后您要将这两个方法添加到 ProfileList 中:

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

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

最后使用 ApiCommunicator:

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

关于java - 将方法移动到另一个Java类,并从原始类中调用该方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59011554/

相关文章:

java - Intellij 未导入更新的 jar

java - SonarQube IntelliJ 插件如何对新代码运行检查

java - facebook like 按钮点击时显示空白页面

android - ImageView 填充 parent 的宽度或高度,但保持纵横比

java - Android 使用一个微调器和两个适配器

java - 如何下载快照版本?

java - IntelliJ 编译错误 zip END header 未找到

java - 如何在 Java 9 的运行时访问 javax.annotation.Resource

java - 如何从 jar 库中包含 JSP

java - (ORMLite - android) 直接设置外键字段