classcastexception:Fragment_main无法强制转换为片段活动android

时间:2014-11-01 00:43:32

标签: java android eclipse android-layout android-fragments

我有一个fragment_weather.xml和一个WeatherFragment.java。这是我第一次使用碎片,我不确定我犯了什么错误。我将提供三组代码。第一个是主要活动,其中真正的错误是。

    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;
        }
    }
}

接下来是我的天气碎片,这就是错误所提到的。

    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);
    }
}

接下来是错误也提到的activity_weather.xml。

<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"
    />        

完整错误是:

  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)

有人知道发生了什么吗?提前致谢。

2 个答案:

答案 0 :(得分:1)

这不是正确的答案!!!!

我认为getSupportFragmentMananger()返回一个FragmentManager()对象,但FragmentActivity是一个视图,它们不一样。

您可以查看有关此内容的官方链接:[http://developer.android.com/guide/components/fragments.html

答案 1 :(得分:0)

您似乎正在从http://code.tutsplus.com/tutorials/create-a-weather-app-on-android--cms-21587

进行教程

我遇到了同样的问题。事实证明,我忘了更新WeatherActivity类的onCreate方法。