如何将我的排球反应变为变量,以便我可以使用意图将值传递给另一个活动?
问题描述:
我试图将我的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
答
您应该执行启动新的活动OnResponse
Volley Request的回调方法的代码,因为如Bob所说,Volley请求是异步的,并且您希望在此请求完成时转到下一个活动。
答
Volley在后台线程中异步执行请求。因此,在主线程执行的顺序是这样的:
-
getPhoneContacts();
叫 - 凌空开始在辅助线程的网络请求
- 下
Activity
PopulistoListView
开始与空值theMatchingContacts
- 排球请求已完成,并在
onResponse
中设置了theMatchingContacts
的值。
所以你的时候开始的PopulistoListView
Activity
的theMatchingContacts
值仍然null
,因为排球请求尚未完成。
如果你想做任何主线程相关的工作,然后尝试使用'runOnUiThread()'方法 –