如何将我的 Volley 响应转换为变量,以便可以使用意图将该值传递给另一个活动?



我正在尝试将我的 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 在后台线程中异步执行请求。所以主线程中的执行顺序将是这样的:

  1. getPhoneContacts();被称为
  2. Volley 在工作线程中启动网络请求
  3. 下一个ActivityPopulistoListView以空值开始theMatchingContacts
  4. 凌空请求完成并在onResponse中设置theMatchingContacts的值。

所以当你开始PopulistoListViewActivity时,theMatchingContacts的值仍然是null,因为 Volley 请求还没有完成。

最新更新