-1

I have been messing around with this code:

package com.example.doblevxv5.sunny;

import android.os.AsyncTask;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.ListView;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

/**
 * Encapsulates fetching the forecast and displaying it as a {@link ListView} layout.
 */
public class ForecastFragment extends Fragment {

    public ForecastFragment() {
    }

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        // Add this line in order for this fragment to handle menu events.
        setHasOptionsMenu(true);
    }

    @Override
    public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {
        inflater.inflate(R.menu.forecastfragment, menu);
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        // Handle action bar item clicks here. The action bar will
        // automatically handle clicks on the Home/Up button, so long
        // as you specify a parent activity in AndroidManifest.xml.
        int id = item.getItemId();
        if (id == R.id.action_refresh) {
            FetchWeatherTask weatherTask = new FetchWeatherTask();
            weatherTask.execute();
            return true;
        }
        return super.onOptionsItemSelected(item);
    }

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

        // Create some dummy data for the ListView.  Here's a sample weekly forecast
        String[] data = {
                "Mon 6/23 - Sunny - 31/17",
                "Tue 6/24 - Foggy - 21/8",
                "Wed 6/25 - Cloudy - 22/17",
                "Thurs 6/26 - Rainy - 18/11",
                "Fri 6/27 - Foggy - 21/10",
                "Sat 6/28 - TRAPPED IN WEATHERSTATION - 23/18",
                "Sun 6/29 - Sunny - 20/7"
        };
        List<String> weekForecast = new ArrayList<String>(Arrays.asList(data));

        // Now that we have some dummy forecast data, create an ArrayAdapter.
        // The ArrayAdapter will take data from a source (like our dummy forecast) and
        // use it to populate the ListView it's attached to.
        ArrayAdapter<String> forecastAdapter =
                new ArrayAdapter<String>(
                        getActivity(), // The current context (this activity)
                        R.layout.list_item_forecast, // The name of the layout ID.
                        R.id.list_item_forecast_textview, // The ID of the textview to populate.
                        weekForecast);

        View rootView = inflater.inflate(R.layout.fragment_main, container, false);

        // Get a reference to the ListView, and attach this adapter to it.
        ListView listView = (ListView) rootView.findViewById(R.id.listview_forecast);
        listView.setAdapter(forecastAdapter);

        return rootView;
    }

    public class FetchWeatherTask extends AsyncTask<Void, Void, Void> {

        private final String LOG_TAG = FetchWeatherTask.class.getSimpleName();

        @Override
        protected Void doInBackground(Void... params) {
            // These two need to be declared outside the try/catch
            // so that they can be closed in the finally block.
            HttpURLConnection urlConnection = null;
            BufferedReader reader = null;

            // Will contain the raw JSON response as a string.
            String forecastJsonStr = null;

            try {
                // Construct the URL for the OpenWeatherMap query
                // Possible parameters are avaiable at OWM's forecast API page, at
                // http://openweathermap.org/API#forecast
                URL url = new URL("http://api.openweathermap.org/data/2.5/forecast/daily?q=94043&mode=json&units=metric&cnt=7");

                // Create the request to OpenWeatherMap, and open the connection
                urlConnection = (HttpURLConnection) url.openConnection();
                urlConnection.setRequestMethod("GET");
                urlConnection.connect();

                // Read the input stream into a String
                InputStream inputStream = urlConnection.getInputStream();
                StringBuffer buffer = new StringBuffer();
                if (inputStream == null) {
                    // Nothing to do.
                    return null;
                }
                reader = new BufferedReader(new InputStreamReader(inputStream));

                String line;
                while ((line = reader.readLine()) != null) {
                    // Since it's JSON, adding a newline isn't necessary (it won't affect parsing)
                    // But it does make debugging a *lot* easier if you print out the completed
                    // buffer for debugging.
                    buffer.append(line + "\n");
                }

                if (buffer.length() == 0) {
                    // Stream was empty.  No point in parsing.
                    return null;
                }
                forecastJsonStr = buffer.toString();
            } catch (IOException e) {
                Log.e(LOG_TAG, "Error ", e);
                // If the code didn't successfully get the weather data, there's no point in attemping
                // to parse it.
                return null;
            } finally {
                if (urlConnection != null) {
                    urlConnection.disconnect();
                }
                if (reader != null) {
                    try {
                        reader.close();
                    } catch (final IOException e) {
                        Log.e(LOG_TAG, "Error closing stream", e);
                    }
                }
            }
            return null;
        }
    }
}

This code is taken from the following GIS Hub from an oline Android course: https://github.com/udacity/Sunshine/blob/2.05-trigger-refresh/app/src/main/java/com/example/android/sunshine/app/ForecastFragment.java

Here's what the Logcat shows:

11-10 00:03:41.479  13081-13081/com.example.doblevxv5.sunny E/AndroidRuntime﹕ FATAL EXCEPTION: main
    java.lang.RuntimeException: Unable to instantiate activity ComponentInfo{com.example.doblevxv5.sunny/com.example.doblevxv5.sunny.ForecastFragment}: java.lang.ClassCastException: com.example.doblevxv5.sunny.ForecastFragment cannot be cast to android.app.Activity
            at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2016)
            at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2117)
            at android.app.ActivityThread.access$700(ActivityThread.java:134)
            at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1218)
            at android.os.Handler.dispatchMessage(Handler.java:99)
            at android.os.Looper.loop(Looper.java:137)
            at android.app.ActivityThread.main(ActivityThread.java:4867)
            at java.lang.reflect.Method.invokeNative(Native Method)
            at java.lang.reflect.Method.invoke(Method.java:511)
            at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1007)
            at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:774)
            at dalvik.system.NativeStart.main(Native Method)
     Caused by: java.lang.ClassCastException: com.example.doblevxv5.sunny.ForecastFragment cannot be cast to android.app.Activity
            at android.app.Instrumentation.newActivity(Instrumentation.java:1068)
            at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2007)
            at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2117)
            at android.app.ActivityThread.access$700(ActivityThread.java:134)
            at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1218)
            at android.os.Handler.dispatchMessage(Handler.java:99)
            at android.os.Looper.loop(Looper.java:137)
            at android.app.ActivityThread.main(ActivityThread.java:4867)
            at java.lang.reflect.Method.invokeNative(Native Method)
            at java.lang.reflect.Method.invoke(Method.java:511)
            at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1007)
            at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:774)
            at dalvik.system.NativeStart.main(Native Method)

Here is the AndroidManifest.xml file:

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.example.doblevxv5.sunny" >

    <uses-permission android:name="android.permission.INTERNET" />


    <application
        android:allowBackup="true"
        android:icon="@drawable/ic_launcher"
        android:label="@string/app_name"
        android:theme="@style/AppTheme"
        android:debuggable="true">
        <activity
            android:name=".ForecastFragment"
            android:label="@string/app_name" >
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />
                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
    </application>

</manifest>

When I run the app in my phone, it just stops. I cannot even keep the app open.

Thanks for your help!

Mich Vellve
  • 75
  • 2
  • 8
  • 1
    show your manifest.xml – M D Nov 10 '14 at 06:23
  • Caused by: java.lang.ClassCastException: com.example.doblevxv5.sunny.ForecastFragment cannot be cast to android.app.Activity -- main Problem, show your manifest. – Mohammed Ali Nov 10 '14 at 06:29
  • this line here `com.example.doblevxv5.sunny.ForecastFragment cannot be cast to android.app.Activity` suggests a similar problem may of been solved [here](http://stackoverflow.com/questions/20576747/fragment-cannot-be-cast-to-android-app-activity) – Abbath Nov 10 '14 at 06:29

6 Answers6

1

Your log clearly said

  java.lang.RuntimeException: Unable to instantiate activity ComponentInfo{com.example.doblevxv5.sunny/com.example.doblevxv5.sunny.ForecastFragment}: java.lang.ClassCastException: com.example.doblevxv5.sunny.ForecastFragment cannot be cast to android.app.Activity

ForcastFragment is not an Activity it's an Fragment and you cant register it on manifest.xml

So, better to create one Activity and take one FrameLayout and load your ForcastFragment on your Activity at Run time and register your Activity in your manifest.xml.

M D
  • 47,665
  • 9
  • 93
  • 114
1

You cannot declare Fragment in the manifest. In manifest remove android:name=".ForecastFragment" and in place of ForecaseFragment specify your Activity name.

1

Replace this :

android:name=".ForecastFragment"

With this :

android:name=".MainActivity"

Note : Only register Activities in AndroidManifest.xml no need to register Fragment,Fragment is part of activity so which directly call from activity without register in AndroidManifext.xml

Haresh Chhelana
  • 24,720
  • 5
  • 57
  • 67
0

What is happening here is that you are trying to instantiate a fragment as an activity.

Your class ForecastFragment is an extension of a fragment as the code states. A fragment forms part of an activities layout, as such it must be part of an activity so that it can be instantiated as a view.

Check out the main activity they provide in the course - https://github.com/udacity/Sunshine/blob/2.05-trigger-refresh/app/src/main/java/com/example/android/sunshine/app/MainActivity.java

Tim Botha
  • 51
  • 3
0

Refer the following link it shows How to create and execute the fragment and mention the activity in the manifest

http://www.tutorialspoint.com/android/android_fragments.htm

hareesh J
  • 520
  • 1
  • 6
  • 21
0

You should focus on this line of your error:

Caused by: java.lang.ClassCastException: com.example.doblevxv5.sunny.ForecastFragment cannot be cast to android.app.Activity
            at android.app.Instrumentation.newActivity(Instrumentation.java:1068)

Your class is a Fragment, not an Activity. Try using:

public class ForecastFragment extends FragmentActivity{
...
}

On the link you provided, there are multiple activities, you only picked one .java file, there is also a second .java file called MainActivity. https://github.com/udacity/Sunshine/blob/2.05-trigger-refresh/app/src/main/java/com/example/android/sunshine/app/MainActivity.java You should read how Android works: http://developer.android.com/training/basics/activity-lifecycle/index.html Your application is based on activities, think of an Activity as the pages of the book, think of a Main Activity as the first page of the book and think of a fragment as the content of that book.

MrSilent
  • 564
  • 10
  • 28