选择列表项时出现java.lang.NullPointerException错误

时间:2013-02-12 13:12:10

标签: android

当我尝试将活动连接到片段类时,我收到空指针错误。 活动类是一个列表活动,当点击特定列表时,片段类应该打开..任何正文都有示例代码或解决方案可以提供给我..我的片段类名是Termfragment ..

我在listactivity类中使用了这段代码:

           public class HelpActivity extends ListActivity {


Context myContext=this;
@Override
protected void onCreate(Bundle savedInstanceState) {
    // TODO Auto-generated method stub
    super.onCreate(savedInstanceState);
    String[] helplist = getResources().getStringArray(R.array.helplist);
    this.setListAdapter(new ArrayAdapter<String>(this, R.layout.list_view, R.id.label, helplist));
    ListView lv = getListView();
    lv.setOnItemClickListener(new OnItemClickListener() {
          public void onItemClick(AdapterView<?> parent, View view,
              int position, long id) {
              TermFragment mytermfragment = new TermFragment(myContext);
               getSupportFragmentManager().beginTransaction().add(R.id.mytermfragment_container, mytermfragment).commit();
              mytermfragment.show(getSupportFragmentManager(),"mytermfragment");


          }
        });

}
}

TermFragment类:

          public class TermFragment extends DialogFragment implements DialogInterface.OnClickListener {
private Context termContext;
private AlertDialogListener mListener;


public TermFragment(Context context) {
    termContext=context;
}


public interface AlertDialogListener
{
    public void onDialogPositiveClick(DialogFragment dialogFragment);
        }

@Override
public Dialog onCreateDialog(Bundle savedInstanceState) {

    Log.i("help","onCreateDialog");
    AlertDialog.Builder builder = new AlertDialog.Builder(termContext);

    LayoutInflater inflater = getActivity().getLayoutInflater();

    builder.setTitle("Terms");

    builder.setView(inflater.inflate(R.layout.terms_view, null));

    builder.setPositiveButton("I AGREE", new DialogInterface.OnClickListener() {
        @Override
        public void onClick(DialogInterface dialog, int which) {
            mListener.onDialogPositiveClick(TermFragment.this);
        }
    });



    AlertDialog alertDialog = builder.create();
    Log.i("alert","alertDialog Created");
    return alertDialog;
}
@Override
public void onClick(DialogInterface dialog, int which) {
    // TODO Auto-generated method stub

}

}

1 个答案:

答案 0 :(得分:3)

你无法启动像启动Activity这样的片段,你可以在视图中显示/添加它或将其显示为dialogFragment, 在布局中的视图中添加片段

        ExampleFragment mFragment = new ExampleFragment();  // ExampleFragment is your fragment
        FragmentTransaction ft = getFragmentManager().beginTransaction();
        ft.add(R.id.fragmentContainer, mFragment).commit(); // fragmentContainer is id of your view in your layout

在onitemClickListener

中执行上述任务

要使用DialogFragments,请检查此http://android-developers.blogspot.com/2012/05/using-dialogfragments.html

    TermFragment frag= new TermFragment ();  
    frag.show(fm, "fragment_tag");