我正在尝试将我的 Volley 响应分配给一个变量,这样我就可以使用 intent 将该值传递给另一个活动。
我想知道为什么我的theMatchingContacts
字符串在 logcat 中显示null
。我看到了the matching contacts are null
我theMatchingContacts
在我的活动顶部声明:
public class VerifyUserPhoneNumber extends AppCompatActivity {
String theMatchingContacts;
如果用户已注册该应用程序,则在onCreate
:
else {
getPhoneContacts();
// then start the next activity
Intent myIntent = new Intent(VerifyUserPhoneNumber.this, PopulistoListView.class);
//we need phoneNoofUser so we can get user_id and corresponding
//reviews in the next activity
myIntent.putExtra("keyName", phoneNoofUser);
myIntent.putExtra("JsonArrayMatchingContacts", theMatchingContacts);
System.out.println("phonenoofuser" + phoneNoofUser);
System.out.println("the matching contacts are " + theMatchingContacts);
VerifyUserPhoneNumber.this.startActivity(myIntent);
我看phoneNoofUser
好吧,这行得通。但对于theMatchingContacts
它打印null
.并且函数getPhoneContacts()
发生在Intents
部分调用下面的凌空代码之前,所以getMatchingContacts
应该初始化,对吧?
再往下看,我的凌空代码是:
StringRequest stringRequest = new StringRequest(Request.Method.POST, CHECKPHONENUMBER_URL,
new Response.Listener<String>() {
@Override
public void onResponse(String response) {
System.out.println(response);
theMatchingContacts = response.toString();
System.out.println(theMatchingContacts );
etc...etc...
response
打印正确。theMatchingContacts
也是如此,在代码的凌空部分。我无法将 Intents 代码放入 Volley 调用中,因为我的活动在调用之前需要执行其他操作startActivity
您应该在 Volley Request 的回调方法中执行启动新 Activity 的代码OnResponse
因为,正如 Bob 所说,Volley Request 是异步的,您希望在此请求完成后转到下一个 Activity。
Volley 在后台线程中异步执行请求。所以主线程中的执行顺序将是这样的:
getPhoneContacts();
被称为- Volley 在工作线程中启动网络请求
- 下一个
Activity
PopulistoListView
以空值开始theMatchingContacts
- 凌空请求完成并在
onResponse
中设置theMatchingContacts
的值。
所以当你开始PopulistoListView
Activity
时,theMatchingContacts
的值仍然是null
,因为 Volley 请求还没有完成。