我开始构建一个android应用程序(顺便说一句,我是android的新手,对Java并不熟悉)。我希望它对服务器执行GET-Request,获取一个json,然后对该json执行某些操作。
下面的代码可以正常工作,但是它很长,我可以想象在实现此活动中的几个按钮后,这真是一团糟
public class secondActivity extends Activity implements OnClickListener {
@Override
public void onCreate(final Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
this.setContentView(R.layout.login_formular);
View v = findViewById(R.id.button2);
v.setOnClickListener(this);
}
@Override
public void onClick(View v) {
if(v.getId() == R.id.button2) {
OkHttpClient client = new OkHttpClient();
String url="https://example.com/json";
Request request= new Request.Builder()
.url(url)
.build();
client.newCall(request).enqueue(new Callback() {
@Override
public void onFailure(Call call, IOException e) {
e.printStackTrace();
}
@Override
public void onResponse(Call call, Response response) throws IOException {
if(response.isSuccessful()){
final String res= response.body().string();
final Gson gson= new Gson();
final Employee employee=gson.fromJson(res, Employee.class);
secondActivity.this.runOnUiThread(new Runnable() {
@Override
public void run() {
TextView txt= findViewById(R.id.txt3);
txt.setText("employee: " + employee.name);
}
});
}
}
});
}
}
}
我的想法是将http和onclick事件内部的代码外包给新类,但此函数不起作用。
该请求运行正常,但我的员工仅存在于onResponse中,我不知道如何退回该请求。
getEmployeeName.java
public class getEmployeeName {
public static String reqName(){
OkHttpClient client = new OkHttpClient();
String url="https://example.com/json";
Request request= new Request.Builder()
.url(url)
.build();
client.newCall(request).enqueue(new Callback() {
@Override
public void onFailure(Call call, IOException e) {
e.printStackTrace();
}
@Override
public void onResponse(Call call, Response response) throws IOException {
if(response.isSuccessful()){
String res= response.body().string();
Gson gson= new Gson();
Employee employee=gson.fromJson(res, Employee.class);
}
}
});
return employee;
}
}
secondActivity.java
public void onClick(View v) {
if(v.getId() == R.id.button2) {
String name = getEmployeeName.reqName();
secondActivity.this.runOnUiThread(new Runnable() {
@Override
public void run() {
TextView txt= findViewById(R.id.txt3);
txt.setText("employee: " + name);
}
});
}
}
我做错了什么? 谢谢 阿米特(Amit)