我有一个入门级问题:
如果有外部java类让我们说'Class1'在这个类里面有一个叫做'method1'的方法,在这个方法里面有Override方法'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);
}
答案 0 :(得分:1)
为什么不为a
和b
public class Details {
public string a;
public string b;
}
然后在method1
中读取/返回它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;
}
答案 1 :(得分:0)
如果要返回多个值,则应使用称为Intent的Android方式 但如果你坚持 你可以使用Array或ArrayList返回类型作为内部内部方法
class Class1{
public static ArrayList<Object> method1(){
return onResponse();
}
public static ArrayList<Object> onResponse(){
return arrayList<Object>;
} }
但我仍然没有理由不使用Intent