如何在类onResponse之外访问字符串值“data”。总是我使用Toast外部类响应显示为null。
String data;
JsonObjectRequest objectRequest = new JsonObjectRequest(Request.Method.GET, url, null, new Response.Listener<JSONObject>() {
@Override
public void onResponse(JSONObject response) {
try {
data = response.getString("name"));
} catch (JSONException e) {
e.printStackTrace();
}
}
}, new Response.ErrorListener() {
@Override
public void onErrorResponse(VolleyError error) {
Toast.makeText(getApplicationContext(), error.toString(),Toast.LENGTH_SHORT).show();
}
});
RequestQueue queue = Volley.newRequestQueue(this);
queue.add(objectRequest);
}
Toast.makeText(getApplicationContext(),“Display:”+ data,Toast.LENGTH_SHORT).show();
答案 0 :(得分:1)
您可能在错误的时间访问“数据”,尝试在设置后直接显示toast,如果它在那里显示为null,则数据确实为空。 (&gt;和&lt;显示空字符串,如果它是空的。)
public class MainActivityPresenterTest {
private MainActivityPresenter mMainActivityPresenter;
private MainActivity mMainActivity;
@Mock
private WebService mockedService;
@Mock
private Call<List<Post>> mockedCall;
@Captor
private ArgumentCaptor<Callback<List<Post>>> captor;
@Before
public void setUp(){
MockitoAnnotations.initMocks(this);
//create presenter class
mMainActivityPresenter = new MainActivityPresenter();
//create activity class
mMainActivity = new MainActivity();
//set activity to presenter
mMainActivityPresenter.setActivity(mMainActivity);
//set web service
mMainActivityPresenter.setWebService(mockedService);
}
@Test
public void testWebServiceResponse(){
mMainActivityPresenter.downloadPostsList();
Mockito.verify(mockedService).getData().enqueue(captor.capture());
List<Post> testPosts = new ArrayList<>();
Post post1 = new Post();
Post post2 = new Post();
Post post3 = new Post();
testPosts.add(post1);
testPosts.add(post2);
testPosts.add(post3);
captor.getValue().onResponse(mockedCall, Response.success(testPosts));
assertTrue(mMainActivity.getAdapter().getItemCount() == 3);
}
}
答案 1 :(得分:0)
JsonObjectRequest
我假设是一个凌空请求是一个异步任务。因此它将运行后台线程和UI线程上的代码运行为结束。这就是data
变量为空的原因。
Volley结果返回主线程上的回调,因此您可以直接显示toast或在回调方法中执行Update UI。
JsonObjectRequest objectRequest = new JsonObjectRequest(Request.Method.GET, url, null, new Response.Listener<JSONObject>() {
@Override
public void onResponse(JSONObject response) {
try {
String data = response.getString("name"));
Toast.makeText(getApplicationContext(), "Display: " + data,Toast.LENGTH_SHORT).show();
} catch (JSONException e) {
e.printStackTrace();
}
}
}, new Response.ErrorListener() {
@Override
public void onErrorResponse(VolleyError error) {
Toast.makeText(getApplicationContext(), error.toString(),Toast.LENGTH_SHORT).show();
}
});
注意: - 如果您之前要定义变量data
,则必须将其作为实例变量(类级别)。因为你不能在内部类中使用非最终局部变量,即Response.Listener
。