Skip to main content

[Date Prev][Date Next][Thread Prev][Thread Next][Date Index][Thread Index] [List Home]
Re: [cdt-dev] get artifact name and getProjet return null

> Using the following function to get the active project will always return
> null, is this a bug or do I use it incorrect?
> IProject project = ResourcesPlugin.getWorkspace().getRoot().getProject();
> For now I use this method, but it is far from perfect since I need to close
> all the other projects.
> IProject[] myproject =
> ResourcesPlugin.getWorkspace().getRoot().getProjects();
>   IProject project = null;
>   for(int i = 0; i < myproject.length; i++) {
>     if( myproject[i].isOpen()) {
>       project = myproject[i];
>       continue;
>     }
> }

You are using getProject incorrectly, 'getProject()' is a method
defined on all IResource elements, including the root workspace, and
returns the project to which the given resource belongs, but as the
workspace root does not belong to any project it will by definition
return null.

It is important to state in what context you need this info, in
general an action or view keeps track of the current selection,
and from that you can distill the 'active' project, e.g. if you have
an action, you could use something like the following in its delegate:

 * @see IActionDelegate#selectionChanged(IAction, ISelection)
public void selectionChanged(IAction action, ISelection selection) 
	if ( selection instanceof StructuredSelection )
		Object obj = ((StructuredSelection)selection).getFirstElement();
		if ( obj instanceof IAdaptable )
			obj = ((IAdaptable)obj).getAdapter(IResource.class);
		if ( obj instanceof IResource )
			m_project = ((IResource)obj).getProject();

Back to the top