ViewPager의 각 인스턴스에 사용자 지정 개체를 저장하기 위해 SparseArray를 얼마나 올바르게 구현합니까? Android 개발-Java

Leon92

먼저 시간과 도움을 주신 모든 분들께 미리 감사드립니다. 내 질문은 아마도 기본적이고 어리석은 질문 일 것입니다. 그러나 나는 초보자이고 이것이 배우기에 좋은 곳이라고 생각합니다!

그래서 저는 Question이라는 사용자 지정 개체가 있으며 Question.java에 설명되어 있습니다. 다음과 같이 보입니다.

import android.os.Parcel;
import android.os.Parcelable;





public class Question implements Parcelable{
    String mark;
    String total;
    String worth;

public Question(String amark, String atotal, String aworth ) {
    mark = amark;
    total = atotal;
    worth = aworth;

}

public Question(Parcel in) {

        mark = in .readString();
        total = in .readString();
        worth = in .readString();


}

@Override
public int describeContents() {
    // TODO Auto-generated method stub
    return 0;
}
private void readFromParcel(Parcel in ) {

    mark = in .readString();
    total = in .readString();
    worth = in .readString();

}

@Override
public void writeToParcel(Parcel dest, int flags) {
    // TODO Auto-generated method stub
    dest.writeString(mark);
    dest.writeString(total);
    dest.writeString(worth);

}

public static final Parcelable.Creator<Question> CREATOR = new Parcelable.Creator<Question>() {
    public Question createFromParcel(Parcel in) {
        return new Question(in);
    }

    public Question[] newArray(int size) {
        return new Question[size];
    }
};
}

이제 사용자로부터 정보를 수집하기 위해 사용자 정의 된 수의 양식을 작성하고 있습니다. 따라서 각 항목에 Question 개체가 포함 된 SparseArray를 만들려고합니다 (이 모든 정보를 구현을 위해 다른 활동에 전달할 수 있음). 이제 나는 모든 통과가 작동합니다. 그러나 내 UserFragment.java가 열릴 때마다 (각 'form'은보기 페이지를 생성하는 활동 인 FirstFragment.java에 의해 제어되는 UserFragment의 인스턴스이기 때문에) 기본적으로 UserFragment.java 때문에 질문의 새 SparseList를 생성합니다. 다음과 같이 보입니다.

import android.content.Intent;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v4.view.ViewPager;
import android.util.SparseArray;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;

public class UserFragment extends Fragment {


    public View onCreateView(LayoutInflater inflater, ViewGroup container,
            Bundle savedInstanceState) {
        final View rootView = inflater.inflate(R.layout.layout_avgcalcform,
                container, false);

        final int pagetotal = getArguments().getInt("size");


           TextView tv = (TextView) rootView.findViewById(R.id.avg_testtv);
           tv.setText(String.valueOf(getArguments().getInt("page_position")));
         String Text;
         if(pagetotal==getArguments().getInt("page_position")){
             Text = "Submit";
         } else
         Text = "next";  

        Button b = (Button) rootView.findViewById(R.id.button1);
        b.setText(Text);
        b.setOnClickListener( new View.OnClickListener(){

               public void onClick(View v){
                   //Extracting the information from the user input forms! NOTE:NEED TO ADD ERROR CHECKING
                final EditText markc = (EditText)rootView.findViewById(R.id.editTextASSMARK);
                final EditText marktotc = (EditText)rootView.findViewById(R.id.editTextASSTOT);
                final EditText assvalc = (EditText)rootView.findViewById(R.id.editTextASSWORTH);
                   //Converting from INFO string to int
                   double currentassmark = Double.parseDouble(markc.getText().toString());
                   double currentassworth = Double.parseDouble(marktotc.getText().toString());
                   double currentassval = Double.parseDouble(assvalc.getText().toString());
                   // Determining the current viewnumber (or form number) the user is currently on.
                   int currentviewnum =  ((FirstFragment) getActivity()).getPager().getCurrentItem();

                   saveData(new Question(markc.getText().toString(),marktotc.getText().toString(),assvalc.getText().toString()),currentviewnum);
                   ((FirstFragment) getActivity()).getPager().setCurrentItem(currentviewnum+1);
                   double totalpercentage =(double)((currentassmark/currentassworth)*currentassval);
                   Bundle bundle = new Bundle();
                   int currentpagenumber =  getArguments().getInt("page_position");
                   String currentpage = String.valueOf(currentpagenumber);
                   //bundle.putDouble(currentpage, totalpercentage);


                   if(pagetotal==currentpagenumber){
                       bundle.putString("TEST", currentpage);
                       Intent intent = new Intent(UserFragment.this.getActivity(), DisplayAverageActivity.class);                  
                       bundle.putInt("numberofforms", getArguments().getInt("page_position")); 
                       bundle.putSparseParcelableArray("Questions",questions);
                       intent.putExtras(bundle);
                       startActivity(intent);

                   }


               }
    });
        return rootView;

    }
//this is an error, on every creation of UserFragment, it basically creates a new questions array.
    // This results in only the the existance of (questions.get(lastpage).hello).
       SparseArray<Question> questions = new SparseArray<Question>();
    public void saveData(Question quest, int pagenumber){
           questions.put(pagenumber, quest);

    }



}

매번 질문이라는 새로운 SparseArray를 정의하지 않고는 (올바르게) 이것을 수행하는 방법을 생각할 수 없습니다. 그래서 기본적으로 내가 이것에 접근하려고 할 때, 물론 나에게 널 포인터를주지 않는 유일한 반복이 마지막이다. 예를 들어 다음과 같이 액세스하면 String markk = questions.get (totalasses-1) .mark; totalasses-1 만 작동합니다. 그래서 누군가가 내 문제에 대한 해결책을 도울 수 있다면 배열을 어떻게 정의합니까? FirstFragment.java (또는 UserFragment 외부 어딘가)에서 SparseArray를 한 번만 생성 한 다음 각 항목을 해당 뷰 페이저 양식의 질문 양식으로 채 웁니다.

가능하다면 코딩 된 예제와 설명을 포함 해주세요. 저는 초보자이므로 배우고 싶고 해결책을 찾고 싶습니다!

대단히 감사합니다.

스티븐

이에 접근 할 수있는 세 가지 방법이 있습니다.

게으른 방법으로 할 수 있으며 static 키워드 (즉 static SparseArray<Question> questions = new SparseArray<Question>();)를 추가하여 SparseArray를 정적 변수로 만들 수 있습니다.

또는 Bundle을 사용 하고 savedInstanceState매개 변수에 희소 배열을 저장할 수 있습니다.

배열을 가져 오려면

SparseArray<Question> questions = savedInstanceState.getSparseParcelableArray("questions");

그것을 저장하기 위해

savedInstanceState.putSparseParcelableArray("questions", questions);

그러나 , 당신의 Question클래스는 Parcelable 을 구현해야 할 것 입니다 (편집 : 신경 쓰지 마십시오.

세 번째 방법은 단일 인스턴스 만있는 클래스에 대한 참조를 만들고 questions해당 클래스 내부 변수를 저장하는 것 입니다.하지만 게시물에 다른 클래스를 제공하지 않기 때문에이 위치를 찾을 수 없습니다.

이 기사는 인터넷에서 수집됩니다. 재 인쇄 할 때 출처를 알려주십시오.

침해가 발생한 경우 연락 주시기 바랍니다[email protected] 삭제

에서 수정
0

몇 마디 만하겠습니다

0리뷰
로그인참여 후 검토

관련 기사

Related 관련 기사

뜨겁다태그

보관