gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-01 19:59:45 28 4
gpt4 key购买 nike

尊敬的程序专家!

我需要帮助将方法移动到另一个 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/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com