2016-06-11 5 views
0

Volley 라이브러리에 초보자인데 JSON에서 생성하는 API에서 데이터를 가져 오는 간단한 Android 앱을 만들고 있습니다. 디버깅 후 아래에 언급 된이 특정 기능 fetchAccD 만 Android Volley의 지연 문제가 있습니다. 이 액티비티 내의 다른 기능과 JsonObjectRequest을 의미하는 기타 활동은 완벽하게 작동합니다.Volley : JsonObjectRequest의 onResponse 지연 요청

{ 
    "Account": { 
     "remarks": "NIL" 
     "uname": "admin" 
     "pword": null // value not to be shown 
     "key": 1316451 
     "name": "msummons sudo" 
    } 
} 

여기 그 다음은 fetchAccD 방법 후 실행되는 곳이 onCreate로 진행

JsonObjectRequest jsonObjectRequest = new JsonObjectRequest(Request.Method.GET, urlConstruct, 
     new Response.Listener<JSONObject>() 

@Override 
protected void onCreate(Bundle savedInstanceState) { 
    super.onCreate(savedInstanceState); 
    setContentView(R.layout.activity_dashboard); 
    uName = getIntent().getStringExtra("username"); 
    // reset session 
    authidCoDe = 0; 

    // invoke session 
    Account account = fetchAccD(uName); 

    if (account != null) { 
     authidCoDe = account.getKey(); 
     ... 


// init user details before loading 
private final Account fetchAccD (String userN) { 
    final Account account = new Account(); 
    requestQueue = null; 
    requestQueue = Volley.newRequestQueue(this); 
    String urlConstruct = *json url*; 

    JsonObjectRequest jsonObjectRequest = new JsonObjectRequest(Request.Method.GET, urlConstruct, 
      new Response.Listener<JSONObject>() { 
       @Override 
       public void onResponse(JSONObject response) { 
        try { 
         JSONArray jsonArray = response.getJSONArray("Account"); 
         JSONObject jsonObject = jsonArray.getJSONObject(0); 
         account.setUname(jsonObject.optString("uname")); 
        // account.setPword(jsonObject.optString("pword")); 
         account.setKey(jsonObject.optInt("key")); 
         account.setName(jsonObject.optString("name")); 
         account.setRemarks(jsonObject.optString("remarks")); 
         requestQueue.stop(); 
        } 
        catch (JSONException e) { 
         Toast.makeText(getApplicationContext(), "Fetch failed!", Toast.LENGTH_SHORT).show(); 
         requestQueue.stop(); 
        } 
       } 
      }, new Response.ErrorListener() { 
     @Override 
     public void onErrorResponse(VolleyError error) { 
      Toast.makeText(getApplicationContext(), "Fetch failed!", Toast.LENGTH_SHORT).show(); 
      requestQueue.stop(); 
     } 
    }); 
    requestQueue.add(jsonObjectRequest); 
    return account; 
} 

fetchAccD 호출 코드가 완벽하게 실행 내 현재 코드의

if (account != null) { 
    authidCoDe = account.getKey(); 
    ... 

fetchAccD 메소드의 onResponse 메소드의 나머지 부분으로 돌아 가기 전에. 내가 JSON을 가져 오기 위해 내 대부분의 기능에 대한 JsonObjectRequest GET을 사용했습니다

@Override 
public void onResponse(JSONObject response) { 
    try { 
     JSONArray jsonArray = response.getJSONArray("Account"); 
     ... 

,이 문제는 단지 fetchAccD 기능에 발생합니다. 감사!

답변

0

onResponse은 비동기 적으로 서버가 응답을 반환 할 때 호출됩니다.

그래서 당신은이 작업을 수행하기 전에 응답을 기다려야한다 :

if (account != null) { 
    authidCoDe = account.getKey(); 
    ... 
} 

onCreate가 수행해야합니다 onResponse에서

@Override 
protected void onCreate(Bundle savedInstanceState) { 
    super.onCreate(savedInstanceState); 
    setContentView(R.layout.activity_dashboard); 
    uName = getIntent().getStringExtra("username"); 
    // reset session 
    authidCoDe = 0; 

    // invoke session 
    fetchAccD(uName); 
} 

당신이 할 수 있습니다

public void onResponse(JSONObject response) { 

    try { 
     JSONArray jsonArray = response.getJSONArray("Account"); 
     JSONObject jsonObject = jsonArray.getJSONObject(0); 
     account.setUname(jsonObject.optString("uname")); 
    // account.setPword(jsonObject.optString("pword")); 
     account.setKey(jsonObject.optInt("key")); 
     account.setName(jsonObject.optString("name")); 
     account.setRemarks(jsonObject.optString("remarks")); 
     useAccount(account); 
     requestQueue.stop(); 
    } 
    catch (JSONException e) { 
     Toast.makeText(getApplicationContext(), "Fetch failed!", Toast.LENGTH_SHORT).show(); 
     requestQueue.stop(); 
    } 
} 

private void useAccount(Account account) { 
    if (account != null) { 
     authidCoDe = account.getKey(); 
     ... 
    } 
} 

그리고 fetchAccD 당신은 void 수, 값을 반환 할 필요가 없습니다 : 방법 useAccount을 정의합니다.

+0

감사! 그것은 작동하지만 그 뜻은, 내'onCreate' 메소드는'fetchAccD (uName);까지만 작동 할 수 있다는 뜻입니까? 아니면 안돼? :) –

+0

'fetchAccD' 이후에 더 많은 것들을 추가 할 수 있습니다. 귀하의 활동이 응답을 기다려야한다고 말하면 그 동안 다른 일을 할 수 없다는 것을 의미하지는 않습니다. 고마워요. 답변을 수락했음을 표시해주세요. 감사합니다. 감사합니다. –

+0

고마워요! 정말 당신의 도움을 인정, 여기 내 승인 :) –

관련 문제