0

私はviewpagerを使用してフラグメントを作成していますが、arraylistに渡したいと思います。だから私は、以下の事を試してみました:カスタムオブジェクトarraylistをアクティビティからフラグメントに渡す方法

MainActivity:

private ArrayList<customers> mArrayList = null; 

    ViewPagerAdapter adapter = new ViewPagerAdapter(MainActivity.this.getSupportFragmentManager()); 

    adapter.addFrag(NewCustomer.newInstance(mArrayList), "NewCustomer"); 

今フラグメントのクラスに私が作成していインスタンス:

public static final ArrayList<customers> data = new ArrayList<customers>(); 

public static final NewCustomer newInstance(ArrayList<customers> mArrayList) { 

     NewCustomer f = new NewCustomer(); 
     Bundle bdl = new Bundle(1); 
     bdl.putParcelableArrayList(data, mArrayList); 
     f.setArguments(bdl); 
     return f; 
    } 

しかし、これは動作しません。 bdl.putParcelableArrayListにエラーが表示されています。私はarraylistを取得し、そのクラスのローカルarraylistに格納したいと思います。

私のカスタムオブジェクトでarraylistを取得するにはどうすればよいですか?

答えて

1

お試しいただけますか?

public static final NewCustomer newInstance(ArrayList<customers> mArrayList) { 

     NewCustomer f = new NewCustomer(); 
     Bundle bdl = new Bundle(1); 
     this.data = mArrayList; // assign its Value 
     bdl.putParcelableArrayList(data, mArrayList); 
     f.setArguments(bdl); 
     return f; 
    } 

this.data = mArrayList断片の現在のメンバ変数に値を代入します。これで現在の断片でアクセスできます。

+0

あなたはすべきですあなたが提供するコードがなぜ機能しているのか、そして何をしているのかを説明してください。単純にコードを提供しても、OPと同様の質問に終わる可能性のある次のユーザーには役立ちません。 – AxelH

+0

@AxelHはい、あなたは正しいです、私はそれをお詫び申し上げます。 –

+0

謝罪しないでください;)しかし、静的コンテキストで 'this'の使い方をどのように説明していますか?私は実際にその部分を取得しません。または、メソッドの間違った使い方; – AxelH

1

モデルクラス "NewCustomer"がParcelableを実装していることを確認してください。

4

渡す最初のパラメータが間違っています。 は、定義を確認してください:

putParcelableArrayList(String key, ArrayList<? extends Parcelable> value) 

はあなたのフラグメントに、次のように、キーを定義します。

public static final String KEY; 

を次のコードあなたの断片の使用にローカル変数として配列リストを取得するには:

@Override 
public void onStart() { 
    super.onStart(); 
    Bundle arguments = getArguments(); 
    ArrayList<customers> customer_list = arguments.getParcelable(KEY); 
} 
+0

を参照してください。 [source](https://developer.android.com/reference/android/os/Bundle.html)を追加し、putParcelableをKEY(これは定数であるため初期化する必要があります)で呼び出す方法を示します。 – AxelH

関連する問題