2017-02-26 4 views
0

私はバレーボールを使ってnewRequestQueueを行い、SharedPreferencesを取得しようとしている:onClick() - newRequestQueue(this)とgetApplicationContext()エラー?

public class CardAdapter extends RecyclerView.Adapter<CardAdapter.ViewHolder> { 
... 
class ViewHolder extends RecyclerView.ViewHolder implements View.OnClickListener{ 
... 

@Override 
     public void onClick(View v) { 

... 
      -> SharedPreferences pref = getApplicationContext().getSharedPreferences("pref01", MODE_PRIVATE); 
      String username = pref.getString("username", "No name defined"); 

LRequest lRequest = new lRequest(pid, username); 
      -> RequestQueue queue = Volley.newRequestQueue(this); 
      queue.add(lRequest); 

... 

} 

    } 
} 

問題は、それがonClick()イベント内であり、それが私にこのエラーを与えることである。

cannot resolve method getApplicationContext() 

Volley cannot be apply to com.st.mf.CardAdapter.ViewHolder 

どのように解決できますか?

答えて

1

単純に、getApplicationContext()は、どのアダプタクラスのメソッドでもありません。はい、SharedPreferencesを取得するにはコンテキストが必要です。

Volley.newRequestQueue(this)の場合も同様です。 thisの使用方法は、アダプタではなくContextである必要があります。


現実的には、アクティビティからVolleyに電話をかけ、そこでアダプタからデータを入力します。

Contextが本当に必要だった場合は、あなたのコンストラクタが必要です。

public class CardAdapter extends ... 
    private Context context; 

    public CardAdapter(Context context, ...) { 
     this.context = context; 
     ... 
    } 

    ... 

    context.getSharedPreferences("pref01", MODE_PRIVATE); 

    ... 

    RequestQueue queue = Volley.newRequestQueue(context); 

そして、あなたはアダプタを作成...

CardAdapter adapter = new CardAdapter(getApplicationContext(), ...); 
+0

私はあなたに感謝し、それをしようとします! –

関連する問題