2016-05-04 6 views
1

ボタンをクリックすると、ユーザー入力データのバンドルがSQLiteデータベースに保存され、CardViewがRecyclerViewリストに挿入されます。私はゼロのデフォルト値で始まり、 "Save"ボタンがクリックされるたびに(新しいCardViewが作成される)カウンタを作成し、そのカウンタをRecyclerViewリストのCardViewに出力したいと思います。Android:SharedPreferencesカウンタをRecyclerView TextViewに設定するにはどうすればよいですか?

OnBindViewHolderメソッドのアダプタファイルにAndroidスタジオエラーが表示され、最後の行で "holder ..."が始まります。アクティビティからアダプタファイルにコンテキストを取得するにはどうすればよいですか?私はgetSharedPreferences()がグローバルコンテキストを許可したとは思っていましたが、getPreferences()は動作しませんでした。

私は、ボタンのクリックで活動ファイルでSharedPreferencesを使用してカウンタを設定します。

public class Activity extends AppCompatActivity { 
... 
    public void onClickSave(View v) { 
    ... 
    int totalcount = 0; 
    SharedPreferences sp = getSharedPreferences("Share_Prefs",Context.MODE_PRIVATE); 
    SharedPreferences.Editor editor = sp.edit(); 
    editor.putInt("int_key", ++totalcount); 
    editor.apply(); 

RecyclerViewアダプタファイル次のコードがあります:Contextで、以来、

public class Adapter extends RecyclerView.Adapter<Adapter.ListViewHolder> { 
    .... 
    Context context; 
    .... 
    public Adapter(Context context, List<UserData> dbList) { 
    this.context = context; 

    public class ListViewHolder extends RecyclerView.ViewHolder { 

     TextView cardBlankTextNums; 

     public ListViewHolder(View itemView) { 
     super(itemView); 

     cardBlankTextNums = (TextView)itemView.findViewById(R.id.cardBlankTextNums); 

     @Override 
     public int getItemCount() { 
      return dbList.size(); 
     } 

    @Override 
    public void onBindViewHolder(final ListViewHolder holder, final int position) { 

    int totalcount = 0; 

    holder.cardBlankTextNums.setText(dbList.get(position).getSharedPreferences.edit.getInt("int_key",totalcount));  
+0

dbList.get(位置).getSharedPreferences ...構文正しいですか? – Pooya

+0

正しい構文について考えてみてください。 – AJW

+0

私は – Pooya

答えて

0

getSharedPreferences作品あなたのアダプタには名前がないので、あなたのアダプタクラスにコンテキストを渡す必要があります。

public class Adapter extends RecyclerView.Adapter<Adapter.ListViewHolder> { 

    private Context mContext; 

    public Adapter (Context context) 
    { 
     mContext = context; 
    } 

    ... 

public void onBindViewHolder(final ListViewHolder holder, final int position) { 

    holder.cardBlankTextNums.setText(mContext.getSharedPreferences("Share_Prefs",Context.MODE_PRIVATE).getInt("int_key",totalcount)); 

そして、新しいアダプタをインスタンス化する場合は、コンテキストを渡す必要があります。たとえば、あなたが活動中である場合、あなたがする必要があります。

Adapter newAdapter = new Adapter(this); 

あなたはあなたがする必要があるフラグメントである場合:

Adapter newAdapter = new Adapter(getActivity()); 
+0

の下に答えを投稿します。setTextは "dbList.get(position)..."を使ってCardViewの位置を必要としませんか? – AJW

+0

@AJW個人的に私はどのロジックを使用しているのか分かりませんが、getSharedPreferencesはビューの位置に関係なく固定数を返します – Pooya

+0

私はコンテキストを渡しましたが、含めるのを忘れました。上記のコードを編集して表示します。 – AJW

関連する問題