片段与语境

Fragmente and Context

我将此代码整合到一个 Fragment 但在 Fragment 中请求 Context 时它不起作用:

SimpleCursorAdapter ad1 = new SimpleCursorAdapter(**What i put here**, R.layout.spinner, cursor, from, to); 

如果此代码进入 Activity 它将是:

SimpleCursorAdapter(**This**, R.layout.spinner, cursor, from, to); 

请帮帮我。

您应该使用 getActivity() 访问片段的 activity 上下文:

SimpleCursorAdapter ad1 = new SimpleCursorAdapter(getActivity(), R.layout.spinner, cursor, from, to);

希望对您有所帮助。

   SQLiteDatabase db =  getActivity().openOrCreateDatabase("IbsPEC.db", Context.MODE_PRIVATE, null); 
          Spinner  ddlPrdutor1 = (Spinner)getActivity().findViewById(R.id.ddlProdutor1);
          Cursor cursor =  db.rawQuery("SELECT rowid _id,_grupo, id, nome FROM PRODUTOR ORDER BY NOME", null);

          String[] from = { "nome", "_id", "_grupo" }; 
          int[] to = { R.id.lblNome, R.id.lblId, R.id.lbl_id_FK };            

        SimpleCursorAdapter ad1 = new SimpleCursorAdapter(getActivity(), R.layout.spinner, cursor, from, to); 
        ad1.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);


          ddlPrdutor1.setAdapter(ad1);
          db.close();

在调试模式下,错误发生在:ddProdutor1.setAdapter(ad1); Return Exception NullPointer 仅此而已;这个 class 是一个片段。