繁体   English   中英

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

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

尊敬的节目大师们!

我需要有关将方法移动到另一个 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 中删除这些方法),但这会带来一些其他问题,例如 postRequest 中 OnResponse 方法中的 .runOnUiThread 可运行和getResponse - 那些引用 ProfileList.this 而不是动态 Java 类。

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

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

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

编辑:ApiCommunicator添加了ApiCommunicatorListener接口,该接口需要由 ProfileList 活动实现以取回结果并将其分配给 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 活动中实现接口,如下所示:

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

暂无
暂无

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

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