我使用volley库从Web服务获取数据,但是当我通过volley响应获取数据时,我想转移到另一个活动,所以我想等到我有连接响应。当我使用AsyncTask
并将传递函数放在后执行中时,第二个活动会启动我在log cat中看到的数据。当我把传递函数放在凌空OnResponse
里面时,活动就会冻结。那么如何等到获得响应并保存数据然后转移到另一个活动才能使用它。
这是代码:
public class Loading_Car_info extends AppCompatActivity {
String appUrl="https://darialkndari5.000webhostapp.com/read_info.php";
String user_id,name,v_date,v_no,qr_code;
String[] phaths;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_loading__car_info);
Bundle b=this.getIntent().getExtras();
MyAsyncTask m=new MyAsyncTask();
m.execute();
}
public void transfer()
{
Bundle b=new Bundle();
b.putStringArray("paths", phaths);
b.putString("name","hi");
b.putString("v_dat","hello");
b.putString("v_no","rrr");
b.putString("qr_code",qr_code);
Intent intent=new Intent(this,User_Info.class);
intent.putExtras(b);
startActivity(intent);
}
public class MyAsyncTask extends AsyncTask<Void, Void, Void> {
@Override
protected void onPreExecute() {
//UI Interaction
}
@Override
protected Void doInBackground(Void... params) {
StringRequest stringRequest = new StringRequest(Request.Method.POST, appUrl, new Response.Listener<String>() {
@Override
public void onResponse(String response) {
boolean move=false;
phaths=new String[response.length()];
try {
JSONObject jsnobject = new JSONObject(response);
JSONArray jsonArray = jsnobject.getJSONArray("ads");
for (int i = 0; i < jsonArray.length(); i++) {
JSONObject student = jsonArray.getJSONObject(i);
v_date=student.getString("v_date");
v_no=student.getString("v_no");
qr_code=student.getString("Qr_code");
name=student.getString("name");
phaths[i]=student.getString("path");
}
} catch (JSONException e) {
e.printStackTrace();
}
}
}, new Response.ErrorListener() {
@Override
public void onErrorResponse(VolleyError error) {
System.out.println("MainActivity 2" + error.toString());
}
}) {
@Override
protected Map<String, String> getParams() throws AuthFailureError {
Map<String, String> params = new HashMap<String, String>();
params.put("id", "3");
return params;
}
};
NotificationData.getmInstance(Loading_Car_info.this).addrequestqueue(stringRequest);
return null;
}
@Override
protected void onPostExecute(Void aVoid) {
transfer();
}
}
}
答案 0 :(得分:2)
您需要在onResponse()
中获取所有数据后致电转移:
try {
JSONObject jsnobject = new JSONObject(response);
JSONArray jsonArray = jsnobject.getJSONArray("ads");
for (int i = 0; i < jsonArray.length(); i++) {
JSONObject student = jsonArray.getJSONObject(i);
v_date=student.getString("v_date");
v_no=student.getString("v_no");
qr_code=student.getString("Qr_code");
name=student.getString("name");
phaths[i]=student.getString("path");
}
transfer();
} catch (JSONException e) {
e.printStackTrace();
}