2017-04-23 4 views
2

저는 Volley를 사용하는 방법을 배우고 있습니다. 나는 응답을 System.out.printIn에 성공적으로 기록하고 배열의 단일 항목에 대해 logcat에서 확인합니다. 여러 항목을 가지고있을 때 FOR LOOP로 어려움을 겪고 있습니다. 데이터를 반복하는 방법을 알아낼 수 없습니다. 누군가가 나를 어떻게하는지 보여주는 것을 도와 주실 수 있습니까?Android 용 Volley 응답 루프

내 MainActivity

package hfad.com.volley_listview_array; 

import android.app.Activity; 
import android.os.Bundle; 
import android.widget.ArrayAdapter; 
import android.widget.TextView; 

import com.android.volley.Request; 
import com.android.volley.Response; 
import com.android.volley.VolleyError; 
import com.android.volley.toolbox.JsonObjectRequest; 
import com.android.volley.toolbox.Volley; 

import org.json.JSONArray; 
import org.json.JSONException; 
import org.json.JSONObject; 

import java.util.ArrayList; 
public class MainActivity extends Activity { 
    ArrayAdapter<String> adapter; 
    ArrayList<String> items; 
    protected void onCreate(Bundle savedInstanceState) { 
     super.onCreate(savedInstanceState); 
     setContentView(R.layout.activity_main); 


     final TextView mTextView = (TextView) findViewById(R.id.textView); 

     String url = "https://reqres.in/api/users?page=2"; 

     JsonObjectRequest jsonRequest = new JsonObjectRequest 
       (Request.Method.GET, url, new Response.Listener<JSONObject>() { 
        @Override 
        public void onResponse(JSONObject response) { 
         // the response is already constructed as a JSONObject! 
         try { 
          response = response.getJSONObject("data"); 

          //for loop goes here? How? I get i already defined in scope 
          for (int i = 0, i < response.length(), i++); 
          //String site = response.getString("first_name"), 
           //  network = response.getString("last_name"); 
          //System.out.println("firstname: "+site+"\nLastname: "+network); 
         } catch (JSONException e) { 
          e.printStackTrace(); 
         } 
        } 
       }, new Response.ErrorListener() { 

        @Override 
        public void onErrorResponse(VolleyError error) { 
         error.printStackTrace(); 
        } 
       }); 

     Volley.newRequestQueue(this).add(jsonRequest); 


    }} 

그리고 내 activity_main.xml 내가 목록에서 결과를 표시 할 필요가 없습니다. 모든 데이터가 차례로 쌓이기 만하면됩니다.

<?xml version="1.0" encoding="utf-8"?> 
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:tools="http://schemas.android.com/tools" 
    android:layout_width="match_parent" 
    android:layout_height="match_parent" 
    android:orientation="vertical" 
    android:padding="10dp" 
    tools:context=".MainActivity"> 


    <TextView 
     android:id="@+id/textView" 
     android:layout_width="match_parent" 
     android:layout_height="wrap_content" 
     android:text="TextView" /> 
    <!-- 
    <ListView 
     android:id="@+id/listv" 
     android:layout_width="match_parent" 
     android:layout_height="89dp"></ListView> 
    --> 

</LinearLayout> 

내 데이터가 내 로그 캣에 표시 할 데이터를 가지고 https://reqres.in/api/users?page=2

{"page":"2","per_page":3,"total":12,"total_pages":4,"data":[{"id":4,"first_name":"eve","last_name":"holt","avatar":"https://s3.amazonaws.com/uifaces/faces/twitter/marcoramires/128.jpg"},{"id":5,"first_name":"gob","last_name":"bluth","avatar":"https://s3.amazonaws.com/uifaces/faces/twitter/stephenmoon/128.jpg"},{"id":6,"first_name":"tracey","last_name":"bluth","avatar":"https://s3.amazonaws.com/uifaces/faces/twitter/bigmancho/128.jpg"}]} 

이 테스트 API에서이지만 첫 번째 항목을 표시합니다. 모든 레코드를 반복하는 방법. 어떤 도움을 주셔서 감사합니다.

+0

시도의 JSONArray를 포함/deserializators –

답변

1
String url = "https://reqres.in/api/users?page=2"; 

     JsonObjectRequest jsonRequest = new JsonObjectRequest 
       (Request.Method.GET, url, new Response.Listener<JSONObject>() { 
        @Override 
        public void onResponse(JSONObject response) { 
         try { 
          JSONArray jsonArray = response.getJSONArray("data"); 
          JSONObject jsonInnerObject; 

          for (int k = 0; k< jsonArray.length(); k++){ 

           jsonInnerObject=new JSONObject(jsonArray.get(k).toString()); 

           String site = jsonInnerObject.getString("first_name"), 
            network = jsonInnerObject.getString("last_name"); 
           System.out.println("firstname: "+site+"\nLastname: "+network); 
          } 

         } catch (JSONException e) { 
          e.printStackTrace(); 
         } 
        } 
       }, new Response.ErrorListener() { 

        @Override 
        public void onErrorResponse(VolleyError error) { 
         error.printStackTrace(); 
        } 
       }); 

     Volley.newRequestQueue(this).add(jsonRequest);` 

참고 : 데이터가 GSON 포 잭슨 무척를 사용 된 JSONObject

+0

이 명확한 답변을 주셔서 너무 감사드립니다. 감사합니다. 내가 왜 저에게 오류를주고 있었습니까? "i"이외의 다른 문자를 사용해야합니까? – Marco

+0

@Marco for 루프에서 "i"를 사용할 수 있습니다. 내 안드로이드 스튜디오에서 테스트 중이었고 "i"는 이미 내 수업에서 사용 중이므로 k를 사용했습니다 –

+0

. 당신의 도움을 주셔서 감사합니다. – Marco