简体   繁体   中英

classcastexception: Fragment_main cannot be cast to fragment activity android

I have a fragment_weather.xml and a WeatherFragment.java. This is my first time using fragments and I am not sure what mistake I have made. I will give three sets of code. The first one is the mainactivity, where the real error is.

    package ah.hathi.simpleweather;

import android.support.v7.app.ActionBarActivity;
import android.support.v4.app.Fragment;
import android.text.InputType;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.EditText;



public class WeatherActivity extends ActionBarActivity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_weather);
        if (savedInstanceState == null) {
            getSupportFragmentManager().beginTransaction()
                    .add(R.id.container, new PlaceholderFragment())
                    .commit();
        }
    }


    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(R.menu.weather, menu);
        return true;
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        if(item.getItemId() == R.id.change_city){
            showInputDialog();
        }
        return false;
    }

    private void showInputDialog(){
        AlertDialog.Builder builder = new AlertDialog.Builder(this);
        builder.setTitle("Change city");
        final EditText input = new EditText(this);
        input.setInputType(InputType.TYPE_CLASS_TEXT);
        builder.setView(input);
        builder.setPositiveButton("Go", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                changeCity(input.getText().toString());
            }
        });
        builder.show();
    }

    public void changeCity(String city){
        WeatherFragment wf = (WeatherFragment)getSupportFragmentManager()
                                .findFragmentById(R.id.container);
        wf.changeCity(city);
        new CityPreference(this).setCity(city);
    }
    /**
     * A placeholder fragment containing a simple view.
     */
    public static class PlaceholderFragment extends Fragment {

        public PlaceholderFragment() {
        }


        @Override
        public View onCreateView(LayoutInflater inflater, ViewGroup container,
                Bundle savedInstanceState) {
            View rootView = inflater.inflate(R.layout.fragment_weather, container, false);
            return rootView;
        }
    }
}

next is my weatherfragment which is what the error is mentioning.

    package ah.hathi.simpleweather;

import java.text.DateFormat;
import java.util.Date;
import java.util.Locale;
import ah.hathi.simpleweather.WeatherActivity.PlaceholderFragment;
import org.json.JSONObject;

import android.graphics.Typeface;
import android.os.Bundle;
import android.os.Handler;
import android.support.v4.app.Fragment;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;
import android.widget.Toast;

public class WeatherFragment extends Fragment {
    Typeface weatherFont;

    TextView cityField;
    TextView updatedField;
    TextView detailsField;
    TextView currentTemperatureField;
    TextView weatherIcon;

    Handler handler;

    public WeatherFragment(){   
        handler = new Handler();
    }
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);  
        weatherFont = Typeface.createFromAsset(getActivity().getAssets(), "fonts/weather.ttf");     
        updateWeatherData(new CityPreference(getActivity()).getCity());
    }
    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
            Bundle savedInstanceState) {
        View rootView = inflater.inflate(R.layout.fragment_weather, container, false);
        cityField = (TextView)rootView.findViewById(R.id.city_field);
        updatedField = (TextView)rootView.findViewById(R.id.updated_field);
        detailsField = (TextView)rootView.findViewById(R.id.details_field);
        currentTemperatureField = (TextView)rootView.findViewById(R.id.current_temperature_field);
        weatherIcon = (TextView)rootView.findViewById(R.id.weather_icon);

        weatherIcon.setTypeface(weatherFont);
        return rootView; 
    }

    private void updateWeatherData(final String city){
        new Thread(){
            public void run(){
                final JSONObject json = RemoteFetch.getJSON(getActivity(), city);
                if(json == null){
                    handler.post(new Runnable(){
                        public void run(){
                            Toast.makeText(getActivity(), 
                                    getActivity().getString(R.string.place_not_found), 
                                    Toast.LENGTH_LONG).show(); 
                        }
                    });
                } else {
                    handler.post(new Runnable(){
                        public void run(){
                            renderWeather(json);
                        }
                    });
                }               
            }
        }.start();
    }

    private void renderWeather(JSONObject json){
        try {
            cityField.setText(json.getString("name").toUpperCase(Locale.US) + 
                    ", " + 
                    json.getJSONObject("sys").getString("country"));

            JSONObject details = json.getJSONArray("weather").getJSONObject(0);
            JSONObject main = json.getJSONObject("main");
            detailsField.setText(
                    details.getString("description").toUpperCase(Locale.US) +
                    "\n" + "Humidity: " + main.getString("humidity") + "%" +
                    "\n" + "Pressure: " + main.getString("pressure") + " hPa");

            currentTemperatureField.setText(
                        String.format("%.2f", main.getDouble("temp"))+ " ℃");

            DateFormat df = DateFormat.getDateTimeInstance();
            String updatedOn = df.format(new Date(json.getLong("dt")*1000));
            updatedField.setText("Last update: " + updatedOn);

            setWeatherIcon(details.getInt("id"),
                    json.getJSONObject("sys").getLong("sunrise") * 1000,
                    json.getJSONObject("sys").getLong("sunset") * 1000);

        }catch(Exception e){
            Log.e("SimpleWeather", "One or more fields not found in the JSON data");
        }
    }

    private void setWeatherIcon(int actualId, long sunrise, long sunset){
        int id = actualId / 100;
        String icon = "";
        if(actualId == 800){
            long currentTime = new Date().getTime();
            if(currentTime>=sunrise && currentTime<sunset) {
                icon = getActivity().getString(R.string.weather_sunny);
            } else {
                icon = getActivity().getString(R.string.weather_clear_night);
            }
        } else {
            switch(id) {
            case 2 : icon = getActivity().getString(R.string.weather_thunder);
                     break;         
            case 3 : icon = getActivity().getString(R.string.weather_drizzle);
                     break;     
            case 7 : icon = getActivity().getString(R.string.weather_foggy);
                     break;
            case 8 : icon = getActivity().getString(R.string.weather_cloudy);
                     break;
            case 6 : icon = getActivity().getString(R.string.weather_snowy);
                     break;
            case 5 : icon = getActivity().getString(R.string.weather_rainy);
                     break;
            }
        }
        weatherIcon.setText(icon);
    }

    public void changeCity(String city){
        updateWeatherData(city);
    }
}

Next is the activity_weather.xml which the error also mentions.

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:paddingBottom="@dimen/activity_vertical_margin"
android:paddingLeft="@dimen/activity_horizontal_margin"
android:paddingRight="@dimen/activity_horizontal_margin"
android:paddingTop="@dimen/activity_vertical_margin"
tools:context="ah.hathi.simpleweather.WeatherActivity$PlaceholderFragment" >

<TextView
    android:id="@+id/city_field"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_alignParentTop="true"
    android:layout_centerHorizontal="true"
    android:textAppearance="?android:attr/textAppearanceLarge" />

<TextView
    android:id="@+id/updated_field"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_below="@+id/city_field"
    android:layout_centerHorizontal="true"
    android:textAppearance="?android:attr/textAppearanceMedium"
    android:textSize="13sp" />

<TextView
    android:id="@+id/weather_icon"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"       
    android:layout_centerVertical="true"
    android:layout_centerHorizontal="true"
    android:textAppearance="?android:attr/textAppearanceLarge"
    android:textSize="70sp"
    />

<TextView
    android:id="@+id/current_temperature_field"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_alignParentBottom="true"
    android:layout_centerHorizontal="true"
    android:textAppearance="?android:attr/textAppearanceLarge"
    android:textSize="40sp" />

<TextView
    android:id="@+id/details_field"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_below="@+id/weather_icon"
    android:layout_centerHorizontal="true"
    android:textAppearance="?android:attr/textAppearanceMedium"
    />        

The full error is:

  10-31 17:25:21.913: E/AndroidRuntime(4105): java.lang.ClassCastException: ah.hathi.simpleweather.WeatherActivity$PlaceholderFragment cannot be cast to ah.hathi.simpleweather.WeatherFragment
10-31 17:25:21.913: E/AndroidRuntime(4105):     at ah.hathi.simpleweather.WeatherActivity.changeCity(WeatherActivity.java:65)
10-31 17:25:21.913: E/AndroidRuntime(4105):     at ah.hathi.simpleweather.WeatherActivity$1.onClick(WeatherActivity.java:58)
10-31 17:25:21.913: E/AndroidRuntime(4105):     at com.android.internal.app.AlertController$ButtonHandler.handleMessage(AlertController.java:166)
10-31 17:25:21.913: E/AndroidRuntime(4105):     at android.os.Handler.dispatchMessage(Handler.java:102)
10-31 17:25:21.913: E/AndroidRuntime(4105):     at android.os.Looper.loop(Looper.java:136)
10-31 17:25:21.913: E/AndroidRuntime(4105):     at android.app.ActivityThread.main(ActivityThread.java:5001)
10-31 17:25:21.913: E/AndroidRuntime(4105):     at java.lang.reflect.Method.invokeNative(Native Method)
10-31 17:25:21.913: E/AndroidRuntime(4105):     at java.lang.reflect.Method.invoke(Method.java:515)
10-31 17:25:21.913: E/AndroidRuntime(4105):     at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:785)
10-31 17:25:21.913: E/AndroidRuntime(4105):     at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:601)
10-31 17:25:21.913: E/AndroidRuntime(4105):     at dalvik.system.NativeStart.main(Native Method)

Does anybody know what is going on? Thanks in advanced.

IT'S NOT THE RIGHT ANSWER !!!!

I think getSupportFragmentMananger() return a FragmentManager() object, but FragmentActivity is an view, they are not the same.

You can check the official link about this: [ http://developer.android.com/guide/components/fragments.html

It seems you're doing the tutorial from http://code.tutsplus.com/tutorials/create-a-weather-app-on-android--cms-21587

I encountered the same issue. As it turned out, I forgot to update the onCreate method of class WeatherActivity.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM