-2

i m completely beginner in android developing and following the tutorial for sunshine app, while running the app it was supposed to display the detail on detailactivity but gives error. help me figure it out

mainactivity

package com.example.android.sunshine.app;


import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.view.Menu;
import android.view.MenuItem;



public class MainActivity extends AppCompatActivity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
     /**  if (savedInstanceState == null){
         getSupportFragmentManager().beginTransaction()
         .add(R.id.container, new ForecastFragment())
         .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.main, menu);
        return true;
    }

    @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();

        //noinspection SimplifiableIfStatement
        if (id == R.id.action_settings) {
            return true;
        }
        return super.onOptionsItemSelected(item);
    }
}

forecastFragment

package com.example.android.sunshine.app;

import android.content.Intent;
import android.net.*;
import android.os.*;
import android.support.v4.app.*;
import android.text.format.*;
import android.util.*;
import android.view.*;
import android.widget.*;

import org.json.*;
import java.io.*;
import java.net.*;
import java.text.*;
import java.util.*;


/**
 * Created by Nabahat on 7/8/2015.
 */
public class ForecastFragment extends Fragment {

    List<String> mWeekForecast;
    ArrayAdapter<String> mForecastAdapter = null;

    public ForecastFragment() {
    }

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

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

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        int id = item.getItemId();
        if (id == R.id.action_refresh) {
            FetchWeatherTask weatherTask = new FetchWeatherTask();
            weatherTask.execute("94043");
            return true;
        }
        return super.onOptionsItemSelected(item);
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        View rootView = inflater.inflate(R.layout.fragment_main, container, false);
        String[] forecastArray = {
                "Today - Sunny - 88/63",
                "Tomorrow - Foggy - 70/40",
                "Weds - Cloudy - 72/63",
                "Thurs - Asteroids - 75/65",
                "Fri - Heavy Rain - 65/56",
                "Sat - HELP TRAPPED IN WEATHERSTATION - 60/51",
                "Sun - Sunny - 80/68"
        };

        List<String> weekForecast = new ArrayList<String>(
                Arrays.asList(forecastArray));

        mForecastAdapter = new ArrayAdapter<String>(
                getActivity(),
                R.layout.list_item_forecast,
                R.id.list_item_forecast_textview,
                weekForecast);
        ListView listView = (ListView) rootView.findViewById(R.id.listview_forecast);
        listView.setAdapter(mForecastAdapter);

        listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> adapterView, View view, int position, long l) {
                String forecast = mForecastAdapter.getItem(position);
                Intent intent = new Intent(getActivity(), DetailActivity.class )
                        .putExtra(Intent.EXTRA_TEXT, forecast);
                startActivity(intent);
            }
        });
        return rootView;
    }

    public class FetchWeatherTask extends AsyncTask<String, Void, String[]> {

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

        /* The date/time conversion code is going to be moved outside the asynctask later,
  * so for convenience we're breaking it out into its own method now.
  */
        private String getReadableDateString(long time) {
            // Because the API returns a unix timestamp (measured in seconds),
            // it must be converted to milliseconds in order to be converted to valid date.
            SimpleDateFormat shortenedDateFormat = new SimpleDateFormat("EEE MMM dd");
            return shortenedDateFormat.format(time);
        }

        /**
         * Prepare the weather high/lows for presentation.
         */
        private String formatHighLows(double high, double low) {
            // For presentation, assume the user doesn't care about tenths of a degree.
            long roundedHigh = Math.round(high);
            long roundedLow = Math.round(low);

            String highLowStr = roundedHigh + "/" + roundedLow;
            return highLowStr;
        }

        /**
         * Take the String representing the complete forecast in JSON Format and
         * pull out the data we need to construct the Strings needed for the wireframes.
         * <p/>
         * Fortunately parsing is easy:  constructor takes the JSON string and converts it
         * into an Object hierarchy for us.
         */
        private String[] getWeatherDataFromJson(String forecastJsonStr, int numDays)
                throws JSONException {

            // These are the names of the JSON objects that need to be extracted.
            final String OWM_LIST = "list";
            final String OWM_WEATHER = "weather";
            final String OWM_TEMPERATURE = "temp";
            final String OWM_MAX = "max";
            final String OWM_MIN = "min";
            final String OWM_DESCRIPTION = "main";

            JSONObject forecastJson = new JSONObject(forecastJsonStr);
            JSONArray weatherArray = forecastJson.getJSONArray(OWM_LIST);

            // OWM returns daily forecasts based upon the local time of the city that is being
            // asked for, which means that we need to know the GMT offset to translate this data
            // properly.

            // Since this data is also sent in-order and the first day is always the
            // current day, we're going to take advantage of that to get a nice
            // normalized UTC date for all of our weather.

            Time dayTime = new Time();
            dayTime.setToNow();

            // we start at the day returned by local time. Otherwise this is a mess.
            int julianStartDay = Time.getJulianDay(System.currentTimeMillis(), dayTime.gmtoff);

            // now we work exclusively in UTC
            dayTime = new Time();

            String[] resultStrs = new String[numDays];
            for (int i = 0; i < weatherArray.length(); i++) {
                // For now, using the format "Day, description, hi/low"
                String day;
                String description;
                String highAndLow;

                // Get the JSON object representing the day
                JSONObject dayForecast = weatherArray.getJSONObject(i);

                // The date/time is returned as a long.  We need to convert that
                // into something human-readable, since most people won't read "1400356800" as
                // "this saturday".
                long dateTime;
                // Cheating to convert this to UTC time, which is what we want anyhow
                dateTime = dayTime.setJulianDay(julianStartDay + i);
                day = getReadableDateString(dateTime);

                // description is in a child array called "weather", which is 1 element long.
                JSONObject weatherObject = dayForecast.getJSONArray(OWM_WEATHER).getJSONObject(0);
                description = weatherObject.getString(OWM_DESCRIPTION);

                // Temperatures are in a child object called "temp".  Try not to name variables
                // "temp" when working with temperature.  It confuses everybody.
                JSONObject temperatureObject = dayForecast.getJSONObject(OWM_TEMPERATURE);
                double high = temperatureObject.getDouble(OWM_MAX);
                double low = temperatureObject.getDouble(OWM_MIN);

                highAndLow = formatHighLows(high, low);
                resultStrs[i] = day + " - " + description + " - " + highAndLow;
            }
            for (String s : resultStrs) {
                Log.v(LOG_TAG, "Forecast entry: " + s);
            }
            return resultStrs;
        }

        @Override
        protected String[] doInBackground(String... params) {

            if (params.length == 0) {
                return null;
            }

            HttpURLConnection urlConnection = null;
            BufferedReader reader = null;
            String forecastJsonStr = null;

            String format = "json";
            String units = "metric";
            int numDays = 7;

            try {

                final String FORECAST_BASE_URL =
                        "http://api.openweathermap.org/data/2.5/forecast/daily?";
                final String QUERY_PARAM = "q";
                final String FORMAT_PARAM = "mode";
                final String UNITS_PARAM = "units";
                final String DAYS_PARAM = "cnt";

                Uri builtUri = Uri.parse(FORECAST_BASE_URL).buildUpon()
                        .appendQueryParameter(QUERY_PARAM, params[0])
                        .appendQueryParameter(FORMAT_PARAM, format)
                        .appendQueryParameter(UNITS_PARAM, units)
                        .appendQueryParameter(DAYS_PARAM, Integer.toString(numDays))
                        .build();

                URL url = new URL(builtUri.toString());

                Log.v(LOG_TAG, "Built URI " + builtUri.toString());

                urlConnection = (HttpURLConnection) url.openConnection();
                urlConnection.setRequestMethod("GET");
                //urlConnection.setRequestProperty("API_KEY", "c84aeef73dfe54e9ec696154cfb89a5a");
                urlConnection.setDoInput(true);
                urlConnection.setRequestProperty("User-Agent", "Mozilla/5.0 ( compatible ) ");
                urlConnection.setRequestProperty("Accept", "*/*");
                urlConnection.setDoOutput(false);
                urlConnection.connect();

                InputStream inputStream = urlConnection.getInputStream();
                StringBuffer buffer = new StringBuffer();
                if (inputStream == null) {
                    return null;
                }
                reader = new BufferedReader(new InputStreamReader(inputStream));

                String line;
                while ((line = reader.readLine()) != null) {
                    buffer.append(line + "\n");
                }

                if (buffer.length() == 0) {
                    return null;
                }
                forecastJsonStr = buffer.toString();
                Log.v(LOG_TAG, "Forecast JSON String: " + forecastJsonStr);
            } catch (IOException e) {
                Log.e(LOG_TAG, "Error ", e);
                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);
                    }
                }
            }
            try {
                return getWeatherDataFromJson(forecastJsonStr, numDays);
            } catch (JSONException e) {
                Log.e(LOG_TAG, e.getMessage(), e);
                e.printStackTrace();
            }
            return null;
        }

        @Override
        protected void onPostExecute(String[] result) {
            if (result != null) {
                mForecastAdapter.clear();
                for (String dayForecastStr : result) {
                    mForecastAdapter.add(dayForecastStr);
                }
            }
        }
    }
}

detail activity

package com.example.android.sunshine.app;

import android.content.Intent;
import android.support.v4.app.Fragment;
import android.support.v7.app.ActionBarActivity;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;


public class DetailActivity extends AppCompatActivity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_detail);
        if (savedInstanceState == null) {
            getSupportFragmentManager().beginTransaction()
                    .add(R.id.container, new DetailFragment()).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.menu_detail, menu);
        return true;
    }

    @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();

        //noinspection SimplifiableIfStatement
        if (id == R.id.action_settings) {
            return true;
        }

        return super.onOptionsItemSelected(item);
    }

    public static class DetailFragment extends Fragment {

        public DetailFragment() {
        }

        @Override
        public View onCreateView(LayoutInflater inflater, ViewGroup container,
                                 Bundle savedInstanceState) {
            Intent intent = getActivity().getIntent();
            View rootView = inflater.inflate(R.layout.fragment_detail, container, false);
            if (intent != null && intent.hasExtra(Intent.EXTRA_TEXT)){
                String forecastStr = intent.getStringExtra(Intent.EXTRA_TEXT);
                ((TextView) rootView.findViewById(R.id.detail_text))
                        .setText(forecastStr);
            }

            return rootView;
        }
    }
}

activitydetail.xml

<fragment xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools" android:id="@+id/fragment"
    android:name="com.example.android.sunshine.app.DetailActivity$DetailFragment"
    tools:layout="@layout/fragment_detail" android:layout_width="match_parent"
    android:layout_height="match_parent" />

activitymain.xml

<fragment xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:id="@+id/fragment"
    android:name="com.example.android.sunshine.app.ForecastFragment"
    tools:layout="@layout/fragment_main"
    android:layout_width="match_parent"
    android:layout_height="match_parent" />

fragmentdetail.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:paddingLeft="64dp"
    android:paddingRight="64dp"
    android:paddingTop="16dp"
    android:paddingBottom="16dp"
    tools:context="com.example.android.sunshine.app.DetailFragment">

    <TextView
        android:id="@+id/detail_text"
        android:text="@string/hello_world"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content" />

</RelativeLayout>

fragmentmain.xml

<FrameLayout
    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:paddingLeft="64dp"
    android:paddingRight="64dp"
    android:paddingTop="@dimen/activity_vertical_margin"
    android:paddingBottom="@dimen/activity_vertical_margin"
    tools:context="com.example.sunshine.app.MainActivityFragment$PlaceholderFragment"
    android:id="@+id/container">

    <ListView
        android:id="@+id/listview_forecast"
        android:layout_width="match_parent"
        android:layout_height="match_parent" />

</FrameLayout>

logcat

 android.support.v7.internal.widget.ActionBarOverlayLayout{bd47b46 V.E..... ... 0,0-0,0 #7f0c003e app:id/decor_content_parent}
    07-09 22:24:29.820  12200-12200/com.example.android.sunshine.app D/FragmentManager﹕ android.support.v7.internal.widget.ContentFrameLayout{252c0107 V.E..... ... 0,0-0,0 #1020002 android:id/content}
    07-09 22:24:29.820  12200-12200/com.example.android.sunshine.app D/FragmentManager﹕ android.widget.RelativeLayout{39c34c6e V.E..... ... 0,0-0,0 #7f0c004f app:id/fragment}
    07-09 22:24:29.820  12200-12200/com.example.android.sunshine.app D/FragmentManager﹕ android.support.v7.widget.AppCompatTextView{e76c234 V.ED.... ... 0,0-0,0 #7f0c0050 app:id/detail_text}
    07-09 22:24:29.820  12200-12200/com.example.android.sunshine.app D/FragmentManager﹕ android.support.v7.internal.widget.ActionBarContainer{3ff4b85d V.ED.... ... 0,0-0,0 #7f0c003f app:id/action_bar_container}
    07-09 22:24:29.826  12200-12200/com.example.android.sunshine.app D/FragmentManager﹕ android.support.v7.widget.Toolbar{4d05d2 V.E..... ... 0,0-0,0 #7f0c0040 app:id/action_bar}
    07-09 22:24:29.828  12200-12200/com.example.android.sunshine.app D/FragmentManager﹕ android.widget.TextView{2afda6a3 V.ED.... ... 0,0-0,0}
    07-09 22:24:29.828  12200-12200/com.example.android.sunshine.app D/FragmentManager﹕ android.support.v7.internal.widget.ActionBarContextView{1bd7cda0 G.E..... ... 0,0-0,0 #7f0c0041 app:id/action_context_bar}
    07-09 22:24:29.829  12200-12200/com.example.android.sunshine.app D/AndroidRuntime﹕ Shutting down VM
    07-09 22:24:29.830  12200-12200/com.example.android.sunshine.app E/AndroidRuntime﹕ FATAL EXCEPTION: main
        Process: com.example.android.sunshine.app, PID: 12200
        java.lang.RuntimeException: Unable to start activity ComponentInfo{com.example.android.sunshine.app/com.example.android.sunshine.app.DetailActivity}: java.lang.IllegalArgumentException: No view found for id 0x7f0c0051 (com.example.android.sunshine.app:id/container) for fragment DetailFragment{2a0c5022 #1 id=0x7f0c0051}
                at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2325)
                at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2390)
                at android.app.ActivityThread.access$800(ActivityThread.java:151)
                at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1303)
                at android.os.Handler.dispatchMessage(Handler.java:102)
                at android.os.Looper.loop(Looper.java:135)
                at android.app.ActivityThread.main(ActivityThread.java:5257)
                at java.lang.reflect.Method.invoke(Native Method)
                at java.lang.reflect.Method.invoke(Method.java:372)
                at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:903)
                at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:698)
         Caused by: java.lang.IllegalArgumentException: No view found for id 0x7f0c0051 (com.example.android.sunshine.app:id/container) for fragment DetailFragment{2a0c5022 #1 id=0x7f0c0051}
                at android.support.v4.app.FragmentManagerImpl.moveToState(FragmentManager.java:947)
                at android.support.v4.app.FragmentManagerImpl.moveToState(FragmentManager.java:1138)
                at android.support.v4.app.BackStackRecord.run(BackStackRecord.java:740)
                at android.support.v4.app.FragmentManagerImpl.execPendingActions(FragmentManager.java:1501)
                at android.support.v4.app.FragmentActivity.onStart(FragmentActivity.java:551)
                at android.app.Instrumentation.callActivityOnStart(Instrumentation.java:1236)
                at android.app.Activity.performStart(Activity.java:6006)
                at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2288)
                at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2390)
                at android.app.ActivityThread.access$800(ActivityThread.java:151)
                at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1303)
                at android.os.Handler.dispatchMessage(Handler.java:102)
                at android.os.Looper.loop(Looper.java:135)
                at android.app.ActivityThread.main(ActivityThread.java:5257)
                at java.lang.reflect.Method.invoke(Native Method)
                at java.lang.reflect.Method.invoke(Method.java:372)
                at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:903)
                at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:698)
    07-09 22:24:32.288  12200-12209/com.example.android.sunshine.app W/art﹕ Suspending all threads took: 70.244ms
    07-09 22:24:40.045  12200-12209/com.example.android.sunshine.app W/art﹕ Suspending all threads took: 5.676ms
user102303
  • 27
  • 3

2 Answers2

0

Your DetailActivity has the lines:

if (savedInstanceState == null) {
    getSupportFragmentManager().beginTransaction()
            .add(R.id.container, new DetailFragment()).commit();
}

But your activity_detail.xml as you've posted doesn't have any id named container - in fact, it already has a Fragment directly in the layout. You should remove the lines from your DetailActivity's onCreate().

ianhanniballake
  • 191,609
  • 30
  • 470
  • 443
  • not it showed another error, it doesnot even display live data 07-09 23:01:13.206 25914-26116/com.example.android.sunshine.app E/FetchWeatherTask﹕ Error – user102303 Jul 09 '15 at 18:14
  • You'll need to update your question with a new logcat message or open a new question if you have an entirely new problem. – ianhanniballake Jul 09 '15 at 18:17
  • i think there is in error in xml file. cant get that, rest of the code is fine i think – user102303 Jul 09 '15 at 18:36
0

In activitydetail.xml change android:id="@+id/fragment" to android:"@+id/container"

Marco Ferrari
  • 4,914
  • 5
  • 33
  • 53