Erro ao usar Fragment

15 respostas
H

Olá, pessoal.

Estou iniciando a aprendizagem em desenvolvimento para Android. Estou seguindo o Trainning do site oficial ( http://developer.android.com/training/index.html ).
Tudo estava seguindo como esperado até eu inicial o conteúdo a respeito de Fragments.

Seguindo a linha de aprendizagem ( http://developer.android.com/training/basics/fragments/index.html ) me deparei com um erro que ainda não achei solução.

Toda vez que tento executar algum projeto que faça uso de Fragments, o IDE (Eclipse) acusa uma série de erros, como:
" [2013-04-28 14:46:41 - MainActivity] Unable to resolve target ‘android-15’ “
” Call requires API level 11 (current min is 4): new android.app.Fragment "

no meu AndroidManifest.xml o mínimo e o maximo sdk está definido como:

Acredito que seja algum problema com a versão da API, tentei várias dicas que encontrei na web e não funcionou.

estou usando o pacote ADT que contém o eclipse e o SDK ( http://developer.android.com/sdk/index.html )

Usando um exemplo do site de trainning também recebo os erros:

/*
* Copyright (C) 2012 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.example.android.fragments;

import android.support.v4.*;
import android.support.v4.app.FragmentActivity;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.Fragment;

public class MainActivity extends FragmentActivity 
implements HeadlinesFragment.OnHeadlineSelectedListener {

/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.news_articles);

// Check whether the activity is using the layout version with
// the fragment_container FrameLayout. If so, we must add the first fragment
if (findViewById(R.id.fragment_container) != null) {

// However, if we're being restored from a previous state,
// then we don't need to do anything and should return or else
// we could end up with overlapping fragments.
if (savedInstanceState != null) {
return;
}

// Create an instance of ExampleFragment
HeadlinesFragment firstFragment = new HeadlinesFragment();

// In case this activity was started with special instructions from an Intent,
// pass the Intent's extras to the fragment as arguments
firstFragment.setArguments(getIntent().getExtras() );

// Add the fragment to the 'fragment_container' FrameLayout
getSupportFragmentManager().beginTransaction()
.add(R.id.fragment_container, firstFragment).commit();
}
}

public void onArticleSelected(int position) {
// The user selected the headline of an article from the HeadlinesFragment

// Capture the article fragment from the activity layout
ArticleFragment articleFrag = (ArticleFragment)
getSupportFragmentManager().findFragmentById(R.id. article_fragment);

if (articleFrag != null) {
// If article frag is available, we're in two-pane layout...

// Call a method in the ArticleFragment to update its content
articleFrag.updateArticleView(position);

} else {
// If the frag is not available, we're in the one-pane layout and must swap frags...

// Create fragment and give it an argument for the selected article
ArticleFragment newFragment = new ArticleFragment();
Bundle args = new Bundle();
args.putInt(ArticleFragment.ARG_POSITION, position);
newFragment.setArguments(args);
FragmentTransaction transaction = getSupportFragmentManager().beginTransaction();

// Replace whatever is in the fragment_container view with this fragment,
// and add the transaction to the back stack so the user can navigate back
transaction.replace(R.id.fragment_container, newFragment);
transaction.addToBackStack(null);

// Commit the transaction
transaction.commit();
}
}
}

Será que alguém já passou por esse problema no inicio do desenvolvimento?

Se falta alguma informação, me avisem.

Desde já, muito obrigado.

15 Respostas

A

Olá
Está usando a Android Support Library (android-support-v4.jar) ?

H

Estou sim.

Meu diretório do projeto ficou assim:

http://imageshack.us/photo/my-images/46/workspacek.png/

M

Este erro acontece só quando vai executar?

H

Não, ele simplesmente não compila.

na linha 23 aparece este erro:

The type java.lang.Object cannot be resolved. It is indirectly referenced from required .class files

outro erro bastante estranho é este:

The project was not built since its build path is incomplete. Cannot find the class file for java.lang.Object. Fix the build path then try building this project

A

Já criou um novo projeto só para testar o ambiente?

H

sim, eu criei um projeto simples antes e executou sem erro.

O erro ocorre apenas quando faço uso de Fragments.

Será que tem algum problema com o pacote ADT?

A

A MainActivity do seu projeto está idêntico ao do primeiro post?

H

Não sei se entendi bem sua pergunta, A H Gusukuma.

Mas sim, postei exatamente a classe MainActivity do meu projeto.

A

Tentou dar um clean no projeto?

H

Tentei sim, mas não notei nenhuma mudança.

M

Vai na Preferences>Build Path e veja se tem algum recurso quebrado (tem um indicador vermelho)

A

Quais APIs você tem instalado? Nesse projeto pede a API 15
Você está tentando rodar o projeto original ou com alterações?

H

Marky.Vasconcelos, não tem nenhum link com indicador vermelho.

A H Gusukuma, instalei a API 15 pelo Android SDK Manager, mas não funcionou.

Consegui resolver em parte o problema. Como estava usando o pacote ADT Bundle, resolvi tentar instalar o Eclipse e o plugin ADT e ver se funcionava.
E pra minha surpresa, funfo.

Agora, a dúvida. Será que tem algum Bug no pacote ADT Bundle? ou será alguma besteira que estou fazendo com a configuração dele?
Qual alternativa vocês usam para o desenvolvimento?

Muito obrigado por ajudarem.

A

Eu disse que o projeto original exigia o API 15, mas no seu Manifest estava setado o API 17
O erro que estava sendo indicado em vermelho (x) estava na estrutura do projeto, no MainActivity.java

Eu uso o Eclipse + ADT plugin

H

Valeu A H Gusukuma e Marky.Vasconcelos pelo suporte.

Por enquanto to conseguindo avançar nos meus estudos.

Valeu…

Criado 28 de abril de 2013
Ultima resposta 4 de mai. de 2013
Respostas 15
Participantes 3