嗨,我有一个扩展SQLiteOpenHelper的类,名为“ KnowledgeBaseHelper”。
我在用于扩展Activity的类中使用了一段时间,但是后来我决定从使用ListActivity转到ListFragment,问题是,当我尝试实例化名为KnowledgeBaseHelper的类时,例如“ KnowledgeBaseHelper helper = new KnowledgeBaseHelper( ListActivity.this);“它给我一个错误“构造函数KnowledgeBaseHelper(ListActivity)未定义”

当我扩展ListActivity时,这通常有效,但是现在我有此错误。实例化是否不同于ListActivity和FragmentActivity?

谢谢

以下是我的代码

public class ListActivity extends ListFragment {
    ArrayList<String> symptomList;
    String name;

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
        Bundle savedInstanceState) {
        // TODO Auto-generated method stub
        return inflater.inflate(R.layout.fragment_generalsymptoms, container,
            false);
    }

    @Override
    public void onActivityCreated(Bundle savedInstanceState) {
        // TODO Auto-generated method stub
        super.onActivityCreated(savedInstanceState);

        new LoadSymptoms().execute();
    }

    class LoadSymptoms extends AsyncTask<String, String, String> {

    @Override
    protected String doInBackground(String... params) {
        // TODO Auto-generated method stub
            KnowledgeBaseHelper helper = new KnowledgeBaseHelper(
                ListActivity.this);

            return null;
    }
}


对于SQLiteOpenHelper,我有很长的代码和方法,因此我决定只包括一些。

public class KnowledgeBaseHelper extends SQLiteOpenHelper {

    private static final int DATABASE_VERSION = 1;

    private static final String DATABASE_NAME = "docdroid";

    //... I deleted the following lines

    public KnowledgeBaseHelper(Context context) {
        super(context, DATABASE_NAME, null, DATABASE_VERSION);
    }

    @Override
    public void onCreate(SQLiteDatabase db) {

        StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder()
            .permitAll().build();
        StrictMode.setThreadPolicy(policy);

        // Create Clinic Table
        createTable(db, TABLE_CLINIC, CLINIC_COLUMN);
        //... I deleted the following lines
    }

    @Override
    public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
        // Drop older table if existed
    db.execSQL("DROP TABLE IF EXISTS " + TABLE_CLINIC);
        onCreate(db);
        //... I deleted the following lines
    }
}


还有其他方法可以实例化在Fragments中扩展SQLiteOpenHelper的类吗?

最佳答案

您需要传递给KnowledgeBaseHelper构造函数的参数是Context

Activity是-a Context,因此您可以在活动中使用this

Fragment不是Context,因此不能在片段中使用this

您可以在片段中使用getActivity()来获取对托管活动的引用(即-a Context)。

08-18 16:26