gpt4 book ai didi

java - 使用来自 java 类和方法的数据

转载 作者:行者123 更新时间:2023-12-02 12:55:17 25 4
gpt4 key购买 nike

我有一个入门级问题:

如果有外部java类,假设该类中有一个名为“method1”的方法,该方法内有一个名为“method1”的方法,该方法内有一个覆盖方法“onResponse”,两个变量被设置为“a”和“b” .

在 android mainActivity 中,我从类中调用了该方法,如下所示:

Class1.method1();

调用该方法后,我如何检索这些变量以在 mainActivity 中使用...

谢谢..

public abstract class Class1 extends Context {

final Context mcontext;


public static void method1(final Context mcontext, final String x){


StringRequest stringRequest = new StringRequest(Request.Method.POST, constants.URL, new Response.Listener<String>() {
@Override
public void onResponse(String response) {
try {

JSONObject parentObject = new JSONObject(response);
JSONObject userDetails = parentObject.getJSONObject("data");

//read attributes
String a = userDetails.getString("a");
String b = userDetails.getString("b");



} catch (JSONException e) {


}
}
},
new Response.ErrorListener() {
@Override
public void onErrorResponse(VolleyError error) {
Toast.makeText(mcontext, error.getMessage() ,Toast.LENGTH_LONG).show();
}
}){
@Override
protected Map<String, String> getParams() throws AuthFailureError {
Map<String,String> params = new HashMap<>();
params.put("x", x);
return params;
}
};

requestHandler.getInstance(mcontext).addToRequestQueue(stringRequest);
}

最佳答案

为什么不为 ab 创建包装类

public class Details {
public string a;
public string b;
}

然后在方法1中读取/返回它

public abstract class Class1 extends Context {

final Context mcontext;


public static Details method1(final Context mcontext, final String x){

Details data = new Details;


StringRequest stringRequest = new StringRequest(Request.Method.POST, constants.URL, new Response.Listener<String>() {
@Override
public void onResponse(String response) {
try {

JSONObject parentObject = new JSONObject(response);
JSONObject userDetails = parentObject.getJSONObject("data");

//read attributes
data.a = userDetails.getString("a");
data.b = userDetails.getString("b");



} catch (JSONException e) {


}
}
},
new Response.ErrorListener() {
@Override
public void onErrorResponse(VolleyError error) {
Toast.makeText(mcontext, error.getMessage() ,Toast.LENGTH_LONG).show();
}
}){
@Override
protected Map<String, String> getParams() throws AuthFailureError {
Map<String,String> params = new HashMap<>();
params.put("x", x);
return params;
}
};


requestHandler.getInstance(mcontext).addToRequestQueue(stringRequest);

return data;
}

关于java - 使用来自 java 类和方法的数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44445288/

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