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

Posted

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了将方法移至另一个Java类,并从原始类中调用该方法相关的知识,希望对你有一定的参考价值。

尊敬的程序专家!

我需要将方法移至另一个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);
        }
    }

}

这可以正常工作,但是我想让我的代码整洁。我还将在其他Java类中经常使用POST和GET函数(postRequest和getResponse方法),因此,如果这些方法(包括OkHttpHandler类)适合单独的Java类,那会更好。 ApiCommunicator.java,然后从那里调用方法。

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

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

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

BTW:我正在使用IntelliJ

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

答案

已编辑:ApiCommunicatorListener添加了ApiCommunicator接口,它需要由ProfileList活动实现以获取结果并分配txtResult TextView。

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

以上是关于将方法移至另一个Java类,并从原始类中调用该方法的主要内容,如果未能解决你的问题,请参考以下文章

Android 中如何在java类中调用activity 中的一个方法?

java 中 如何将“一个类的方法 ”作为参数传到“另一个类的方法”中

如何在抽象类中执行java方法?

我如何将所有提交移至另一个分支?

关于Java中子类调用父类方法

Java中多态的理解