olá,
Está aparecendo o seguinte erro ao utilizar fragment na minha listaAlunos
E/AndroidRuntime: FATAL EXCEPTION: main
Process: br.com.cadastroDeAluno, PID: 5780
java.lang.RuntimeException: Unable to start activity ComponentInfo{br.com.cadastroDeAluno/br.com.cadastroDeAluno.MainListaAlunosActivity}: java.lang.IllegalStateException: The specified child already has a parent. You must call removeView() on the child's parent first.
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2585)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2667)
at android.app.ActivityThread.handleRelaunchActivity(ActivityThread.java:4337)
at android.app.ActivityThread.-wrap15(ActivityThread.java)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1500)
at android.os.Handler.dispatchMessage(Handler.java:111)
at android.os.Looper.loop(Looper.java:207)
at android.app.ActivityThread.main(ActivityThread.java:5776)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:789)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:679)
Caused by: java.lang.IllegalStateException: The specified child already has a parent. You must call removeView() on the child's parent first.
at android.view.ViewGroup.addViewInner(ViewGroup.java:4438)
at android.view.ViewGroup.addView(ViewGroup.java:4274)
at android.support.v4.view.ViewPager.addView(ViewPager.java:1477)
at android.view.ViewGroup.addView(ViewGroup.java:4215)
at android.view.ViewGroup.addView(ViewGroup.java:4188)
at android.support.v4.app.FragmentManagerImpl.moveToState(FragmentManager.java:1124)
at android.support.v4.app.FragmentManagerImpl.moveToState(FragmentManager.java:1290)
at android.support.v4.app.FragmentManagerImpl.moveToState(FragmentManager.java:1272)
at android.support.v4.app.FragmentManagerImpl.dispatchActivityCreated(FragmentManager.java:2149)
at android.support.v4.app.FragmentController.dispatchActivityCreated(FragmentController.java:201)
at android.support.v4.app.FragmentActivity.onStart(FragmentActivity.java:600)
at android.support.v7.app.AppCompatActivity.onStart(AppCompatActivity.java:178)
at android.app.Instrumentation.callActivityOnStart(Instrumentation.java:1245)
at android.app.Activity.performStart(Activity.java:6620)
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2542)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2667)
at android.app.ActivityThread.handleRelaunchActivity(ActivityThread.java:4337)
at android.app.ActivityThread.-wrap15(ActivityThread.java)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1500)
at android.os.Handler.dispatchMessage(Handler.java:111)
at android.os.Looper.loop(Looper.java:207)
at android.app.ActivityThread.main(ActivityThread.java:5776)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:789)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:679)
I/System: FinalizerDaemon: finalize objects = 143
D/OpenGLRenderer: ~CanvasContext() 0x7f8399a000
D/OpenGLRenderer: ~CanvasContext() 0x7f8399d800
classe main:
public class MainListaAlunosActivity extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_lista_alunos);
//ViewPager - controla a variação dos fragments
ViewPager viewPager = (ViewPager) findViewById(R.id.viewpager);
viewPager.setAdapter(new MyAdapter(getSupportFragmentManager()));
//TabLayout
TabLayout tabLayout = (TabLayout) findViewById(R.id.tab_layout_main);
tabLayout.setupWithViewPager(viewPager);
}
private class MyAdapter extends FragmentPagerAdapter{
private final ArrayList<Fragment> fragments;
private final ArrayList<String> titles;
public MyAdapter(FragmentManager fm) {
super(fm);
fragments = new ArrayList<Fragment>(2);
fragments.add(new ListarAlunosFragment());
fragments.add(new ListarMediasFragment());
titles = new ArrayList<String>(fragments.size());//deixar sicronizado no tamanho
titles.add(getString(R.string.tab_alunos));
titles.add(getString(R.string.tab_media));
}
@Override
public Fragment getItem(int position) {
return fragments.get(position);
}
@Override
public int getCount() {
return fragments.size();
}
//deixar a tabs com titulo dinâmico
@Override
public CharSequence getPageTitle(int position){
return titles.get(position);
}
}
}
fragment listaAluno
public class ListarAlunosFragment extends Fragment {
//private static final int PERMISSION_RECEIVER_SMS = 123;
private ListView listaAlunos;
private View meuFragment;
/**
* public ListarAlunosFragment() {
* // Required empty public constructor
* }
*/
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
//setRetainInstance(true);
setHasOptionsMenu(true); //mostra o menu no fragment
// Inflate the layout for this fragment
meuFragment = inflater.inflate(R.layout.fragment_listar_alunos, container, false);
listaAlunos = (ListView) meuFragment.findViewById(R.id.lista_alunos);
listaAlunos.setEmptyView(meuFragment.findViewById(R.id.list_vazia));//caso a lista esteja sem nenhum aluno cadastrado
//mostrar a logo na tela do App
//getSupportActionBar().setDisplayShowHomeEnabled(true);
//getSupportActionBar().setIcon(R.mipmap.ic_students);
// ---- selecionando um aluno da lista p/ editar/atualizar no formulario ----
listaAlunos.setOnItemClickListener(new AdapterView.OnItemClickListener() {
@Override
public void onItemClick(AdapterView<?> lista, View item, int position, long id) {
Aluno aluno = (Aluno) lista.getItemAtPosition(position);
Intent intentAlunoParaFormulario = new Intent(getActivity(), FormularioActivity.class);
intentAlunoParaFormulario.putExtra("Aluno", aluno);
startActivity(intentAlunoParaFormulario);
}
});
//---------------------------------------------------------------------------
// ----- botao novoAluno ----
final Button novoAluno = (Button) meuFragment.findViewById(R.id.novo_aluno);
novoAluno.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
Intent intentVaiParaFormulario = new Intent(getActivity(), FormularioActivity.class);
startActivity(intentVaiParaFormulario);
}
});
//-------------------------------------------------------------------------
// ---- menu no contexto na lista ----
registerForContextMenu(listaAlunos);
return meuFragment;
}
public void carregaLista() {
AlunoDAO dao = new AlunoDAO(getActivity());
List<Aluno> alunos = dao.buscaAlunos();
dao.close();
//criando um AlunosAdapter
AlunosAdapter adapter = new AlunosAdapter(getActivity(), alunos);//alem de passar um aluno tem q ser passado um contexto (this) para o adapter.
listaAlunos.setAdapter(adapter);
}
@Override
public void onResume() {
super.onResume();
carregaLista();
}
@Override
public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {
inflater.inflate(R.menu.menu_lista_alunos, menu);
super.onCreateOptionsMenu(menu, inflater);
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case R.id.menu_baixar_provas:
Intent vaiParaProvas = new Intent(getActivity(), ProvasActivity.class);
startActivity(vaiParaProvas);
break;
case R.id.menu_mapa:
Intent vaiParaMapa = new Intent(getActivity(), MapaActivity.class);
startActivity(vaiParaMapa);
break;
}
return super.onOptionsItemSelected(item);
}
// ----- codigo do menu no contexto na lista de alunos ------
@Override
public void onCreateContextMenu(ContextMenu menu, View v, final ContextMenu.ContextMenuInfo menuInfo) {
//-- recuperando o aluno clicado --------------
AdapterView.AdapterContextMenuInfo info = (AdapterView.AdapterContextMenuInfo) menuInfo;
final Aluno aluno = (Aluno) listaAlunos.getItemAtPosition(info.position);
// --------------------------------------------
//-- menu no contexto - ligar --------
MenuItem ItemLigar = menu.add("Fazer ligação");
Intent intentLigar = new Intent(Intent.ACTION_VIEW);
intentLigar.setData(Uri.parse("tel:" + aluno.getTelefone()));
ItemLigar.setIntent(intentLigar);
//--------------------------------------------------
//-- menu no contexto - enviar sms --------
MenuItem ItemSMS = menu.add("Enviar SMS");
Intent intentSMS = new Intent(Intent.ACTION_VIEW);
intentSMS.setData(Uri.parse("sms:" + aluno.getTelefone()));
ItemSMS.setIntent(intentSMS);
//--------------------------------------------------
//-- menu item deletar no contexto -----------
MenuItem deletar = menu.add("Deletar");
deletar.setOnMenuItemClickListener(new MenuItem.OnMenuItemClickListener() {
@Override
public boolean onMenuItemClick(MenuItem menuItem) {
//deletando do aluno
AlunoDAO dao = new AlunoDAO(getActivity());
dao.deleta(aluno);
dao.close();
//mostrando mensagem e atualizando a lista
Toast.makeText(getActivity(), "Aluno " + aluno.getNome() + " deletado com sucesso!", Toast.LENGTH_SHORT).show();
carregaLista();
return false;
}
});
//-----------------------------------------------------
//@Override
//public void onRequestPermissionResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantTesults) {
//super.onRequestPermissionResult(requestCode, permissions, grantResults);
// if (requestCode == 123) {
// faz a ligacao
// }
//}
}
}
fragmentmedia
public class ListarMediasFragment extends Fragment {
private ListView listaDasMediaAlunos;
private View viewMedia;
/**
* public ListarMediasFragment() {
// Required empty public constructor
}
*/
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
//return inflater.inflate(R.layout.fragment_listar_medias, container, false);
//setRetainInstance(true);//retendo a instancia ao girar o aparelho
setHasOptionsMenu(true); //mostra o menu no fragment
viewMedia = inflater.inflate(R.layout.fragment_listar_alunos, container, false);
listaDasMediaAlunos = (ListView) viewMedia.findViewById(R.id.lista_alunos);
listaDasMediaAlunos.setEmptyView(viewMedia.findViewById(R.id.list_vazia));//caso a lista de media esteja fazia
return listaDasMediaAlunos;
}
@Override
public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {
inflater.inflate(R.menu.menu_lista_media, menu);
super.onCreateOptionsMenu(menu, inflater);
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case R.id.menu_enviar_notas:
new EnviaAlunosTask(getActivity()).execute(); //essa linha mostra a resposta do json
break;
case R.id.menu_baixar_provas:
Intent vaiParaProvas = new Intent(getActivity(), ProvasActivity.class);
startActivity(vaiParaProvas);
break;
case R.id.menu_mapa:
Intent vaiParaMapa = new Intent(getActivity(), MapaActivity.class);
startActivity(vaiParaMapa);
break;
}
return super.onOptionsItemSelected(item);
}
public void carregaMediaAlunos() {
AlunoDAO daoMedia = new AlunoDAO(getActivity());
List<MediaDasNotas> media = daoMedia.buscaMediaAlunos();
daoMedia.close();
//criando um MediaDasNotasAdapter
MediaDasNotasAdapter adapterMedia = new MediaDasNotasAdapter(getActivity(), media);
listaDasMediaAlunos.setAdapter(adapterMedia);
}
@Override
public void onResume() {
super.onResume();
carregaMediaAlunos();
}
}
esse está ocorrendo quando giro a orientação do aparelho
qual a solução?