2017-08-18 26 views
0

我试图将我的Volley响应分配给一个变量,所以我可以使用意图将值传递给另一个活动。如何将我的排球反应变为变量,以便我可以使用意图将值传递给另一个活动?

我想知道为什么我的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

+0

如果你想做任何主线程相关的工作,然后尝试使用'runOnUiThread()'方法 –

回答

1

您应该执行启动新的活动OnResponse Volley Request的回调方法的代码,因为如Bob所说,Volley请求是异步的,并且您希望在此请求完成时转到下一个活动。

1

Volley在后台线程中异步执行请求。因此,在主线程执行的顺序是这样的:

  1. getPhoneContacts();
  2. 凌空开始在辅助线程的网络请求
  3. ActivityPopulistoListView开始与空值theMatchingContacts
  4. 排球请求已完成,并在onResponse中设置了theMatchingContacts的值。

所以你的时候开始的PopulistoListViewActivitytheMatchingContacts值仍然null,因为排球请求尚未完成。

相关问题