Felipe Quirós
Felipe Quirós

Reputation: 440

java.lang.ClassCastException: casting an object, to his parent

I'm a IOS coder, but I'm trying to learn a little bit of android, but I'm getting problems.

I have the following class:

package com.example.fragmenttabhostdemo;

import android.app.Fragment;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;

public class Tab1 extends Fragment {

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
            Bundle savedInstanceState) {

        return inflater.inflate(R.layout.tab1, container, false);
    }
}

When I try to run it, the console says:

java.lang.ClassCastException: com.example.fragmenttabhostdemo.Tab1 cannot be cast to android.support.v4.app.Fragment

Any ideas of what I'm doing wrong ? The problem I think, is occurring when I try to make the fragment activity for my android app layout, and add some tabs to the host:

protected void onCreate(Bundle savedInstanceState) {
     super.onCreate(savedInstanceState);
     setContentView(R.layout.activity_main);

     tabHost = (FragmentTabHost) findViewById(R.id.tabhost);

     tabHost.setup(this, getSupportFragmentManager(), R.id.tabcontent);

     tabHost.addTab(tabHost.newTabSpec("Tab1").setIndicator("Lengueta 1"), Tab1.class, null);
     tabHost.addTab(tabHost.newTabSpec("Tab2").setIndicator("Lengueta 2"),
                           Tab2.class, null);
     tabHost.addTab(tabHost.newTabSpec("Tab3").setIndicator("Lengueta 3"),
                           Tab3.class, null);
   }

So, I don't know what I'm doing wrong. Any other ideas to get a tab layout easily, I just can't do it.

P.D. I'm trying to follow this tutorial: http://www.androidcurso.com/index.php/tutoriales-android-basico/32-unidad-2-diseno-de-la-interfaz-de-usuario-vistas-y-layouts/452-fragmenttabhost

Upvotes: 1

Views: 419

Answers (2)

user489041
user489041

Reputation: 28304

It says it can not be cast to a android.support.v4.app.Fragment. In you Fragment file, you have an import of android.app.Fragment. My guess is that your imports are off.

Upvotes: 2

Andrew Schuster
Andrew Schuster

Reputation: 3229

Your hint is this part right here:

android.support.v4.app.Fragment

You're casting a regular Fragment to a support Fragment. It's confusing because they are two classes with the same name, but located in different packages. Essentially, if you're working with the support libraries, you should stick to all support types. With that in mind, in your Tab1 class, make the following change in your import statements.

//import android.app.Fragment;
import android.support.v4.app.Fragment;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;

Upvotes: 5

Related Questions