Skip to content
This repository has been archived by the owner on Jun 23, 2022. It is now read-only.

The layout is not the same as one from the end of lesson 1? #109

Open
thaibt opened this issue Dec 26, 2015 · 30 comments
Open

The layout is not the same as one from the end of lesson 1? #109

thaibt opened this issue Dec 26, 2015 · 30 comments

Comments

@thaibt
Copy link

thaibt commented Dec 26, 2015

Hi, I am not sure what I did wrong, I basically copied and paste the code from the lesson when I was doing my project. The turn out of my code does not look like what the class has so far? Is it the version of my simulation? I am currently doing this in Jelly Bean, while the lesson is using Gingerbread. My simulation does not have settings implemented when I already have done what the code should be?

untitled

This is my MainActivity.java

package com.dev.xxxxx.sunshine;

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

/**
 * A placeholder fragment containing a simple view.
 */

}

untitled2

@Kasijjuf
Copy link

Does the onCreate method of your ForecastFragment contain the statement setHasOptionsMenu(true); ?

@thaibt
Copy link
Author

thaibt commented Dec 26, 2015

It looks like I do not. Where should I add this?

package com.dev.bao.sunshine;

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

public class ForecastFragment extends Fragment {

ArrayAdapter<String> mForecastAdapter;

public ForecastFragment() {
}

@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",
            "Mon 6/30 - Sunny - 45/40",
            "Tue 7/1 - Rainy - 30/18"
    };
    List<String> weekForecast = new ArrayList<String>(Arrays.asList(data));


    mForecastAdapter = new ArrayAdapter<String>(
            getActivity(),
            R.layout.list_item_forecast,
            R.id.list_item_forecast_textview,
            weekForecast);
    View rootView = inflater.inflate(R.layout.activity_main, container, false);

    ListView listView = (ListView) rootView.findViewById(R.id.listview_forecast);
    listView.setAdapter(mForecastAdapter);
    return rootView;

}
public class FetchWeatherTask extends AsyncTask<Void, Void, Void> {
    private final String LOG_TAG = FetchWeatherTask.class.getSimpleName();

    HttpURLConnection urlConnection = null;
    BufferedReader reader = null;

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


        @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
                String baseUrl = "http://api.openweathermap.org/data/2.5/forecast/city?id=524901";
                String apiKey = "&APPID=" + BuildConfig.OPEN_WEATHER_MAP_API_KEY;
                URL url = new URL(baseUrl.concat(apiKey));

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

}

@Kasijjuf
Copy link

You are trying to have the the fragment add an item to the overflow menu, yes?

In the ForecastFragment class override the onCreate method and write the statement setHasOptionsMenu(true); .

@thaibt
Copy link
Author

thaibt commented Dec 26, 2015

Hi, sorry I am honestly not sure. I am completely new to android
development. I am currently on Lesson 2, adding a refresh button in
ForecastFragment.java

This is the section
2.02_refactor_forecast_fragment...2.03_add_refresh_xml

I tried the above and debugged, I still did not see the menu option.

Thank You,
Bao Thai

On Sat, Dec 26, 2015 at 2:50 PM, Kasijjuf notifications@github.com wrote:

You are trying to have the the fragment add an item to the overflow menu,
yes?

In the ForecastFragment class override the onCreate method and write the
statement setHasOptionsMenu(true); .


Reply to this email directly or view it on GitHub
#109 (comment)
.

@Kasijjuf
Copy link

What's in your forecastfragment.xml file? If you upload your code to a public repository in your GitHub account, I can give you better help.

@thaibt
Copy link
Author

thaibt commented Dec 26, 2015

Sorry, I am not home right now. Will you be free in 3 or 4 hours?

On Dec 26, 2015, at 4:11 PM, Kasijjuf notifications@github.com wrote:

What's in your forecastfragment.xml file? If you upload your code to a public repository in your GitHub account, I can give you better help.


Reply to this email directly or view it on GitHub.

@Kasijjuf
Copy link

I should be.

@thaibt
Copy link
Author

thaibt commented Dec 27, 2015

I am still messing around with GitHub trying to figure out how to upload
codes and etc... However I'll just paste my forecastfragment.xml code below

On Sat, Dec 26, 2015 at 4:20 PM, Kasijjuf notifications@github.com wrote:

I should be.


Reply to this email directly or view it on GitHub
#109 (comment)
.

@Kasijjuf
Copy link

OK, I think I figured out why the menu isn't displaying. You've added the XML that defines the menu, but the code that actually reads and implements that definition hasn't been added yet. That's the job of the next step:

2.03_add_refresh_xml...2.04_inflate_menu

@thaibt
Copy link
Author

thaibt commented Dec 27, 2015

Hmmm, I did that, and I still do not see it.

package com.dev.bao.sunshine;

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;

public class ForecastFragment extends Fragment {

ArrayAdapter<String> mForecastAdapter;

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) {
        return true;
    }
    return super.onOptionsItemSelected(item);
}

@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
                         Bundle savedInstanceState) {
    setHasOptionsMenu(true);
    // 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",
            "Mon 6/30 - Sunny - 45/40",
            "Tue 7/1 - Rainy - 30/18"
    };
    List<String> weekForecast = new ArrayList<String>(Arrays.asList(data));


    mForecastAdapter = new ArrayAdapter<String>(
            getActivity(),
            R.layout.list_item_forecast,
            R.id.list_item_forecast_textview,
            weekForecast);
    View rootView = inflater.inflate(R.layout.activity_main, container, false);

    ListView listView = (ListView) rootView.findViewById(R.id.listview_forecast);
    listView.setAdapter(mForecastAdapter);
    return rootView;

}
public class FetchWeatherTask extends AsyncTask<Void, Void, Void> {
    private final String LOG_TAG = FetchWeatherTask.class.getSimpleName();

    HttpURLConnection urlConnection = null;
    BufferedReader reader = null;

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


        @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
                String baseUrl = "http://api.openweathermap.org/data/2.5/forecast/city?id=524901";
                String apiKey = "&APPID=" + BuildConfig.OPEN_WEATHER_MAP_API_KEY;
                URL url = new URL(baseUrl.concat(apiKey));

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

}

On Sat, Dec 26, 2015 at 7:29 PM, Kasijjuf notifications@github.com wrote:

OK, I think I figured out why the menu isn't displaying. You've added the
XML that defines the menu, but the code that actually reads and implements
that definition hasn't been added yet. That's the job of the next step:

2.03_add_refresh_xml...2.04_inflate_menu
2.03_add_refresh_xml...2.04_inflate_menu


Reply to this email directly or view it on GitHub
#109 (comment)
.

@Kasijjuf
Copy link

Both your onCreate method and your onCreateView method contain the
setHasOptionsMenu(true);
statement. It should only be in onCreate.

@thaibt
Copy link
Author

thaibt commented Dec 27, 2015

I did that and it's still the same.
untitled

Is it because of the way my activity_main.xml is set up? I feel like it is.

@Kasijjuf
Copy link

You are running this on an actual device or on the emulator and not just looking at what appears in the Design view, right?

@thaibt
Copy link
Author

thaibt commented Dec 28, 2015

Yes, I am running it on an emulator. I attempted to delete the toolbar from main_activity.xml, it's gone, but the option settings bar is still nowhere. I'm just honestly messing around and see what is the problem.

On Dec 28, 2015, at 1:27 PM, Kasijjuf notifications@github.com wrote:

You are running this on an actual device or on the emulator and not just looking at what appears in the Design view, right?


Reply to this email directly or view it on GitHub.

@thaibt
Copy link
Author

thaibt commented Dec 28, 2015

I am using SDK 16 in case you wondered.

@Kasijjuf
Copy link

As your minSdkVersion?

@thaibt
Copy link
Author

thaibt commented Dec 28, 2015

Yes

On Dec 28, 2015, at 2:34 PM, Kasijjuf notifications@github.com wrote:

As your minSdkVersion?


Reply to this email directly or view it on GitHub.

@Kasijjuf
Copy link

If you upload your code to a public repository in your GitHub account, I can give you better help. Until then I'm stumped.

@thaibt
Copy link
Author

thaibt commented Dec 29, 2015

May you guide me with this? I am trying to use the desktop version.

On Mon, Dec 28, 2015 at 11:20 PM, Kasijjuf notifications@github.com wrote:

If you upload your code to a public repository in your GitHub account, I
can give you better help. Until then I'm stumped.


Reply to this email directly or view it on GitHub
#109 (comment)
.

@thaibt
Copy link
Author

thaibt commented Dec 29, 2015

Oooooh, I think I got it now, which files do you need from my android
studio?

See if you can check this git hub https://github.com/exocore123/sunshine

On Mon, Dec 28, 2015 at 11:24 PM, Bao Thai baothaijunk@gmail.com wrote:

May you guide me with this? I am trying to use the desktop version.

On Mon, Dec 28, 2015 at 11:20 PM, Kasijjuf notifications@github.com
wrote:

If you upload your code to a public repository in your GitHub account, I
can give you better help. Until then I'm stumped.


Reply to this email directly or view it on GitHub
#109 (comment)
.

@Kasijjuf
Copy link

Sorry for the delayed response,

In Android Studio open your project, then in the menu bar select VCS -> Import into Version Control -> Share Project on GitHub.

@thaibt
Copy link
Author

thaibt commented Dec 31, 2015

@Kasijjuf
Copy link

Kasijjuf commented Jan 1, 2016

Ok I think I figured it out for real this time.

First, compiling and running the code as you have it in your initial commit on your GitHub repository produces an app with no action bar. To add the action bar back simply remove the attribute android:theme="@style/AppTheme.NoActionBar" from line 14 of your AndroidManifest.xml file (link).

Now I am hypothesizing that when you created your Android Virtual Device, you selected either the Nexus One or the Nexus S as the base template. Both of these devices are pre-Honeycomb and thus have the pre-Honeycomb-style navigation buttons, i.e. Back, Menu, Home, and Search. By default when an app is run on such a device, the menu options are accessed via the Menu button rather than via an overflow button in the action bar. I'm fairly certain there is a way to override this behaviour, but I am unaware of what that way is.

When I ran your app in an Android Virtual Device using the Galaxy Nexus as the base template, the overflow button appeared in the action bar as expected (after performing the operation described in paragraph two, of course).

Did I get it right this time?

@thaibt
Copy link
Author

thaibt commented Jan 1, 2016

Wow, you got it! So selecting an android device emulator does matter? Do
you have any recommendation when I set up as a beginner android app
development? That was a rather bugging issue when it was so minor. Thank
you so much!

On Thu, Dec 31, 2015 at 10:55 PM, Kasijjuf notifications@github.com wrote:

Ok I think I figured it out for real this time.

First, compiling and running the code as you have it in your initial
commit on your GitHub repository produces an app with no action bar. To add
the action bar back simply remove the attribute
android:theme="@style/AppTheme.NoActionBar" from line 14 of your
AndroidManifest.xml file (link
https://github.com/exocore123/Sunshine2/blob/master/app/src/main/AndroidManifest.xml#L14
).

Now I am hypothesizing that when you created your Android Virtual Device,
you selected either the Nexus One or the Nexus S as the base template. Both
of these devices are pre-Honeycomb and thus have the pre-Honeycomb-style
navigation buttons, i.e. Back, Menu, Home, and Search. By default when an
app is run on such a device, the menu options are accessed via the Back
button rather than via an overflow button in the action bar. I'm fairly
certain there is a way to override this behaviour, but I am unaware of what
that way is.

When I ran your app in an Android Virtual Device using the Galaxy Nexus as
the base template, the overflow button appeared in the action bar as
expected (after performing the operation described in paragraph two, of
course).

Did I get it right this time?


Reply to this email directly or view it on GitHub
#109 (comment)
.

@Kasijjuf
Copy link

Kasijjuf commented Jan 1, 2016

Thanks for the challenge and glad I could help. Keep in touch.

@Laksh05
Copy link

Laksh05 commented Jul 23, 2016

@Kasijjuf This helped me too. Thank u brother

@Kasijjuf
Copy link

@Laksh05 Glad to hear it

@pri10
Copy link

pri10 commented Sep 20, 2016

my app is crashing

what does container mean in this code? I am getting error in R.id.container

public class MainActivity extends ActionBarActivity {

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

@rhexgomez
Copy link

@pri10 The specific view that will hold the ForecastFragment() after attaching. Similar relationship to Picture Frame and the Picture.

@pri10
Copy link

pri10 commented Sep 21, 2016

Okay thanks :) @elmargomez

Sign up for free to subscribe to this conversation on GitHub. Already have an account? Sign in.
Labels
None yet
Projects
None yet
Development

No branches or pull requests

5 participants