2017-09-22 19 views
-4

我想在recyclerView的onBindViewHolder中使用DatabaseHelper。正常活動可以聲明openHelper像我可以在recyclerView中使用SQLiteOpenHelper嗎?

DatabaseHelper myDb; 
myDb = new DatabaseHelper(this); 

但是如何聲明onBindViewHolder?這是我的代碼。

@Override 
    public void onBindViewHolder(homeAdapter.ViewHolder holder, int position) { 
     holder.homeAuth.setText(authList.get(position)); 
     holder.homeName.setText(nameList.get(position)); 
     holder.homeIntro.setText(introList.get(position)); 
     holder.homePk.setText(pkList.get(position)); 

     holder.itemView.setOnClickListener(new View.OnClickListener() { 
      @Override 
      public void onClick(View v) { 

       final Context context = v.getContext(); 
       final String serverURL = "http://youngh.cafe24app.com/qrock/views/qrock_pk/user_email"; 

       myDb = new DatabaseHelper(this); //is it Possible? 
       final String token = myDb.getToken(); 
       final String email = myDb.getEmail(); 

       Intent myIntent = new Intent(context, mainActivity.class); 
       context.startActivity(myIntent); 
       ((Activity) context).finish(); 

       ((Activity) context).overridePendingTransition(R.xml.madefadein, R.xml.splashfadeout); 
      } 
     }); 
    } 

我一般聲明myDb。但如何使myDb?像new DatabaseHelper(this)這樣的myDb是不可能的?如何改變它?對不起,我不會說英語。

+1

你缺乏一些基本的編程和麪向對象編程概念的人... – Vucko

+0

而不是在'onBindViewHolder'創建新對象創建'myDb = new DatabaseHelper(context);'裏面RecyclerView的Adapter構造函數 – akhilesh0707

+0

@Vucko對不起。我開始android studio和OOP不長...我知道constructer的參數。但我不知道如何轉換爲constructer的參數需要。 –

回答

1

在RecyclerView的適配器構造做到這一點

DatabaseHelper myDb; 
myDb = new DatabaseHelper(context); 

,您可以在onBindViewHolder

+0

但它返回上下文無法應用於適配器。 –

+0

將上下文傳遞給構造函數,並用'new DatabaseHelper(context)'替換'new DatabaseHelper(this)'' – Omer

0

檢查什麼DatabaseHelper需要作爲構造函數的參數一起使用。我想這是Context,所以new DatabaseHelper(context);應該工作

1

如果調用thissetOnClickListener裏面會把有關onclickListener對象不context。您可以在onClickListener中使用myDb = new DatabaseHelper(context);

但是,實現的最佳方式是在適配器構造函數中初始化DatabaseHelper。

在您的適配器構造函數中獲取Context作爲參數並在那裏初始化您的DatabaseHelper。

你的實現應該是這樣的:

class YourAdapter extends RecyclerView.Adapter<YourViewHolder>{ 
    private DatabaseHelper myDb; 

    public YourAdapter(Context context){ 
     myDb = new DatabaseHelper(context) 
    } 
} 

希望它能幫助:)

相關問題