2017-12-12 6 views
0

커서 내에서 ArrayList 항목에 하나의 변수를 지정하려고하지만 항상 마지막 값을 반환합니다. 아래 코드는 다음과 같습니다.커서 반복자 안의 arraylist 항목에 값을 할당하는 방법

DB

public ArrayList<Bean> getPendingData(String s) { 
    SQLiteDatabase db = getWritableDatabase(); 
    String[] columns = {name}; 
    String[] selectionArgs = {s}; 
    Cursor cursor = db.query(TABLE_NAME, columns, " pending= ? ", selectionArgs, null, null, null, null); 
    cursor.moveToFirst();  
    ArrayList<Bean> pending = new ArrayList<>(); 
    String index0 = null; 
    Bean bean; 
    bean = new Bean(); 
    while(!cursor.isAfterLast()) { 
     index0 = cursor.getString(cursor.getColumnIndex(name)); 
     bean.setQuestion(index0); 
     pending.add(bean); 
     cursor.moveToNext(); 
    } 

    cursor.close(); 
    return pending; 
} 

Bean.java에서 값을 얻기

public class Bean { 
public static int id; // ans 
public static String score; 
public static String logo; 
public static String image; 

public static String getQuestion() { 
    return question; 
} 

public static void setQuestion(String question) { 
    Bean.question = question; 
} 

public static String question; 
public static String description; 
public static String option_three; 
public static String OptionFour; 

}

당신은 동안 블록 내부에 빈을 초기화 할 필요가

답변

0

:

while(!cursor.isAfterLast()) { 
    Bean bean = new Bean(); 
    index0 = cursor.getString(cursor.getColumnIndex(name)); 
    bean.setQuestion(index0); 
    pending.add(bean); 
    cursor.moveToNext(); 
} 

이유는 Java가 참조로 객체를 사용하기 때문에 동일한 객체를 항상 "보류 중"배열에 추가하지만이 반복에서이 객체의 값을 변경하기 때문에 결국 값 마지막 반복의

+0

아무 것도 변경하지 않고 마지막 값만 반환합니다. –

+0

이 코드를 사용해도 될까요? while 블록 대신에 : do { Bean bean = new Bean(); String index0 = cursor.getString (cursor.getColumnIndex (name)); bean.setQuestion (index0); pending.add (bean); } while (cursor.moveToNext());' 각 반복에서 주어진 값을 디버깅 할 수있는 중단 점을 추가 할 수 있습니다. –

+0

이미 igor하지만 같은 결과를 시도했습니다. –

0

cursor.isAfterLast() 커서가 마지막 행 위치에있는 경우 true을 반환합니다. ! (not)을 추가하면 커서가 끝날 때까지 수행됩니다.

그래서 while(!cursor.isAfterLast()){}은 while 루프가 커서의 마지막 레코드까지 이동하는 것을 의미합니다.

커서에서 반환하는 모든 행을 가져 오는 데이 메서드를 사용합니다.

if (cursor != null) { 
     if (cursor.getCount() > 0) { 
      if (cursor.moveToFirst()) { 
       homeClassesArrayList = new ArrayList<>(); 
       do { 
        // fetching data 
       } while (cursor.moveToNext()); 
      } 
     } 
} 
+0

Dharmistha를 변경하지 않고 마지막 값만 반환합니다. –

관련 문제