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

Commit

Permalink
2.02 Refactor logging string into constant
Browse files Browse the repository at this point in the history
  • Loading branch information
sdspikes authored and Lyla committed Mar 4, 2015
1 parent 27e83bd commit 1e4314f
Showing 1 changed file with 65 additions and 55 deletions.
Expand Up @@ -15,6 +15,7 @@
*/
package com.example.android.sunshine.app;

import android.os.AsyncTask;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.util.Log;
Expand Down Expand Up @@ -76,65 +77,74 @@ public View onCreateView(LayoutInflater inflater, ViewGroup container,
ListView listView = (ListView) rootView.findViewById(R.id.listview_forecast);
listView.setAdapter(mForecastAdapter);

// 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");
}
return rootView;
}

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

This comment has been minimized.

Copy link
@mayank-kgp

mayank-kgp Jun 19, 2015

I am getting error in this line - Class 'FetchWeatherTask' is public, should be declared in a file named 'FetchWeatherTask.java'

This comment has been minimized.

Copy link
@schwannden

schwannden Jul 11, 2015

Yes you need to rename the file containing this class to 'FetchWeatherTask.java'

This comment has been minimized.

Copy link
@edwardsun007

edwardsun007 Jul 19, 2016

On this line , Android studio is complaining that " class ' FetchWeatherTask' must be declared abstract or implement abstract method 'doInBackground(params...)'
And at line "@OverRide " , I have " Method does not override method from its superclass." Anyone can help me out here ?

I already changed my class and method signature as:
`
public class FetchWeatherTask extends AsyncTask<void, void, void> {

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

    @Override
    protected  Void doInBackground(Void... params) {`

This comment has been minimized.

Copy link
@DaniyalArshad

DaniyalArshad Jul 20, 2016

@edwardsun007

It happens to be a matter of "Package Visibility", for more details check out the following thread (http://stackoverflow.com/questions/7641876/java-the-difference-between-class-classname-and-public-class-classname).

What you need to do is to edit the following statement:

class FetchWeatherTask extends AsyncTask<Void, Void, Void>

P.S There are 3 Voids to be used after the AsyncTask as Parameters (Y).


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

This comment has been minimized.

Copy link
@schwannden

schwannden Jul 11, 2015

Better this way perhaps?
this.getClass().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.
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;
}
forecastJsonStr = buffer.toString();
} catch (IOException e) {
Log.e("ForecastFragment", "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("ForecastFragment", "Error closing stream", e);
} 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;
}

return rootView;
}
}

9 comments on commit 1e4314f

@senderic
Copy link

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

The name of the commit threw me off! :)
"Introducing AsyncTask" would have been easier. Oh well, had me click around and find interesting stuff.

@Daveguido
Copy link

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

My app keeps crashing and I continue to get the:
"Caused by: android.os.NetworkOnMainThreadException" error after moving the networking code outside the main thread using "AsyncTask". (Just showing the snip-it where its broke up)

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

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

@senderic
Copy link

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

@Daveguido, are you sure all your networking code is off the main thread? Could you provide a link to your forked github code that contains our project (assuming you have that up)

@Daveguido
Copy link

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

@esend7881 I was working on getting it up, but I actually figured out the problem. Thanks a million though!

@basu901
Copy link

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Both my MainActivity.java and ForecastFragment.java are identical to the one present here,but i'm getting a warning saying the FetchWeatherTask is never used.There are no errors when i run the code,and it is getting launched on my device,but the problem is,it is still crashing.Help me out please!!!! I am using Android Studio 1.2.2

@theaichampion
Copy link

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I am getting the same error using Android Studio 2.1

@theaichampion
Copy link

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I am getting the same error using Android Studio 2.1

@CoolestCatMona
Copy link

@CoolestCatMona CoolestCatMona commented on 1e4314f Jul 6, 2016

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Having trouble with this step in the tutorial, MainActivity.java and ForecastFragment.java match perfectly, as do the XML files, so the sunshine app should continue to work now that we have a background thread, however the app still crashes, looking at the logcat I am getting the following

07-06 03:26:45.782 2085-2085/? E/AndroidRuntime: FATAL EXCEPTION: main 07-06 03:26:45.782 2085-2085/? E/AndroidRuntime: Process: app.com.example.---.sunshine, PID: 2085 07-06 03:26:45.782 2085-2085/? E/AndroidRuntime: java.lang.RuntimeException: Unable to start activity ComponentInfo{app.com.example.sean.sunshine/app.com.example.sean.sunshine.MainActivity}: android.view.InflateException: Binary XML file line #18: Binary XML file line #1: Error inflating class fragment 07-06 03:26:45.782 2085-2085/? E/AndroidRuntime: at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2416) 07-06 03:26:45.782 2085-2085/? E/AndroidRuntime: at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2476) 07-06 03:26:45.782 2085-2085/? E/AndroidRuntime: at android.app.ActivityThread.-wrap11(ActivityThread.java) 07-06 03:26:45.782 2085-2085/? E/AndroidRuntime: at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1344) 07-06 03:26:45.782 2085-2085/? E/AndroidRuntime: at android.os.Handler.dispatchMessage(Handler.java:102) 07-06 03:26:45.782 2085-2085/? E/AndroidRuntime: at android.os.Looper.loop(Looper.java:148) 07-06 03:26:45.782 2085-2085/? E/AndroidRuntime: at android.app.ActivityThread.main(ActivityThread.java:5417) 07-06 03:26:45.782 2085-2085/? E/AndroidRuntime: at java.lang.reflect.Method.invoke(Native Method) 07-06 03:26:45.782 2085-2085/? E/AndroidRuntime: at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:726) 07-06 03:26:45.782 2085-2085/? E/AndroidRuntime: at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:616) 07-06 03:26:45.782 2085-2085/? E/AndroidRuntime: Caused by: android.view.InflateException: Binary XML file line #18: Binary XML file line #1: Error inflating class fragment 07-06 03:26:45.782 2085-2085/? E/AndroidRuntime: at android.view.LayoutInflater.inflate(LayoutInflater.java:539) 07-06 03:26:45.782 2085-2085/? E/AndroidRuntime: at android.view.LayoutInflater.inflate(LayoutInflater.java:423) 07-06 03:26:45.782 2085-2085/? E/AndroidRuntime: at android.view.LayoutInflater.inflate(LayoutInflater.java:374) 07-06 03:26:45.782 2085-2085/? E/AndroidRuntime: at android.support.v7.app.AppCompatDelegateImplV7.setContentView(AppCompatDelegateImplV7.java:256) 07-06 03:26:45.782 2085-2085/? E/AndroidRuntime: at android.support.v7.app.AppCompatActivity.setContentView(AppCompatActivity.java:109) 07-06 03:26:45.782 2085-2085/? E/AndroidRuntime: at app.com.example.---.sunshine.MainActivity.onCreate(MainActivity.java:17) 07-06 03:26:45.782 2085-2085/? E/AndroidRuntime: at android.app.Activity.performCreate(Activity.java:6237) 07-06 03:26:45.782 2085-2085/? E/AndroidRuntime: at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1107) 07-06 03:26:45.782 2085-2085/? E/AndroidRuntime: at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2369) 07-06 03:26:45.782 2085-2085/? E/AndroidRuntime: at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2476)  07-06 03:26:45.782 2085-2085/? E/AndroidRuntime: at android.app.ActivityThread.-wrap11(ActivityThread.java)  07-06 03:26:45.782 2085-2085/? E/AndroidRuntime: at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1344)  07-06 03:26:45.782 2085-2085/? E/AndroidRuntime: at android.os.Handler.dispatchMessage(Handler.java:102)  07-06 03:26:45.782 2085-2085/? E/AndroidRuntime: at android.os.Looper.loop(Looper.java:148)  07-06 03:26:45.782 2085-2085/? E/AndroidRuntime: at android.app.ActivityThread.main(ActivityThread.java:5417)  07-06 03:26:45.782 2085-2085/? E/AndroidRuntime: at java.lang.reflect.Method.invoke(Native Method)  07-06 03:26:45.782 2085-2085/? E/AndroidRuntime: at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:726)  07-06 03:26:45.782 2085-2085/? E/AndroidRuntime: at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:616)  07-06 03:26:45.782 2085-2085/? E/AndroidRuntime: Caused by: android.view.InflateException: Binary XML file line #1: Error inflating class fragment 07-06 03:26:45.782 2085-2085/? E/AndroidRuntime: at android.view.LayoutInflater.createViewFromTag(LayoutInflater.java:782) 07-06 03:26:45.782 2085-2085/? E/AndroidRuntime: at android.view.LayoutInflater.parseInclude(LayoutInflater.java:941) 07-06 03:26:45.782 2085-2085/? E/AndroidRuntime: at android.view.LayoutInflater.rInflate(LayoutInflater.java:831) 07-06 03:26:45.782 2085-2085/? E/AndroidRuntime: at android.view.LayoutInflater.rInflateChildren(LayoutInflater.java:798) 07-06 03:26:45.782 2085-2085/? E/AndroidRuntime: at android.view.LayoutInflater.inflate(LayoutInflater.java:515) 07-06 03:26:45.782 2085-2085/? E/AndroidRuntime: at android.view.LayoutInflater.inflate(LayoutInflater.java:423)  07-06 03:26:45.782 2085-2085/? E/AndroidRuntime: at android.view.LayoutInflater.inflate(LayoutInflater.java:374)  07-06 03:26:45.782 2085-2085/? E/AndroidRuntime: at android.support.v7.app.AppCompatDelegateImplV7.setContentView(AppCompatDelegateImplV7.java:256)  07-06 03:26:45.782 2085-2085/? E/AndroidRuntime: at android.support.v7.app.AppCompatActivity.setContentView(AppCompatActivity.java:109)  07-06 03:26:45.782 2085-2085/? E/AndroidRuntime: at app.com.example.---.sunshine.MainActivity.onCreate(MainActivity.java:17)  07-06 03:26:45.782 2085-2085/? E/AndroidRuntime: at android.app.Activity.performCreate(Activity.java:6237)  07-06 03:26:45.782 2085-2085/? E/AndroidRuntime: at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1107)  07-06 03:26:45.782 2085-2085/? E/AndroidRuntime: at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2369)  07-06 03:26:45.782 2085-2085/? E/AndroidRuntime: at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2476)  07-06 03:26:45.782 2085-2085/? E/AndroidRuntime: at android.app.ActivityThread.-wrap11(ActivityThread.java)  07-06 03:26:45.782 2085-2085/? E/AndroidRuntime: at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1344)  07-06 03:26:45.782 2085-2085/? E/AndroidRuntime: at android.os.Handler.dispatchMessage(Handler.java:102)  07-06 03:26:45.782 2085-2085/? E/AndroidRuntime: at android.os.Looper.loop(Looper.java:148)  07-06 03:26:45.782 2085-2085/? E/AndroidRuntime: at android.app.ActivityThread.main(ActivityThread.java:5417)  07-06 03:26:45.782 2085-2085/? E/AndroidRuntime: at java.lang.reflect.Method.invoke(Native Method)  07-06 03:26:45.782 2085-2085/? E/AndroidRuntime: at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:726)  07-06 03:26:45.782 2085-2085/? E/AndroidRuntime: at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:616)  07-06 03:26:45.782 2085-2085/? E/AndroidRuntime: Caused by: android.os.NetworkOnMainThreadException 07-06 03:26:45.782 2085-2085/? E/AndroidRuntime: at android.os.StrictMode$AndroidBlockGuardPolicy.onNetwork(StrictMode.java:1273) 07-06 03:26:45.782 2085-2085/? E/AndroidRuntime: at java.net.InetAddress.lookupHostByName(InetAddress.java:431) 07-06 03:26:45.782 2085-2085/? E/AndroidRuntime: at java.net.InetAddress.getAllByNameImpl(InetAddress.java:252) 07-06 03:26:45.782 2085-2085/? E/AndroidRuntime: at java.net.InetAddress.getAllByName(InetAddress.java:215) 07-06 03:26:45.782 2085-2085/? E/AndroidRuntime: at com.android.okhttp.internal.Network$1.resolveInetAddresses(Network.java:29) 07-06 03:26:45.782 2085-2085/? E/AndroidRuntime: at com.android.okhttp.internal.http.RouteSelector.resetNextInetSocketAddress(RouteSelector.java:188) 07-06 03:26:45.782 2085-2085/? E/AndroidRuntime: at com.android.okhttp.internal.http.RouteSelector.nextProxy(RouteSelector.java:157) 07-06 03:26:45.782 2085-2085/? E/AndroidRuntime: at com.android.okhttp.internal.http.RouteSelector.next(RouteSelector.java:100) 07-06 03:26:45.782 2085-2085/? E/AndroidRuntime: at com.android.okhttp.internal.http.HttpEngine.createNextConnection(HttpEngine.java:357) 07-06 03:26:45.782 2085-2085/? E/AndroidRuntime: at com.android.okhttp.internal.http.HttpEngine.nextConnection(HttpEngine.java:340) 07-06 03:26:45.782 2085-2085/? E/AndroidRuntime: at com.android.okhttp.internal.http.HttpEngine.connect(HttpEngine.java:330) 07-06 03:26:45.782 2085-2085/? E/AndroidRuntime: at com.android.okhttp.internal.http.HttpEngine.sendRequest(HttpEngine.java:248) 07-06 03:26:45.782 2085-2085/? E/AndroidRuntime: at com.android.okhttp.internal.huc.HttpURLConnectionImpl.execute(HttpURLConnectionImpl.java:433) 07-06 03:26:45.782 2085-2085/? E/AndroidRuntime: at com.android.okhttp.internal.huc.HttpURLConnectionImpl.connect(HttpURLConnectionImpl.java:114) 07-06 03:26:45.782 2085-2085/? E/AndroidRuntime: at app.com.example.sean.sunshine.MainActivityFragment.onCreateView(MainActivityFragment.java:83) 07-06 03:26:45.782 2085-2085/? E/AndroidRuntime: at android.support.v4.app.Fragment.performCreateView(Fragment.java:1962) 07-06 03:26:45.782 2085-2085/? E/AndroidRuntime: at android.support.v4.app.FragmentManagerImpl.moveToState(FragmentManager.java:1036) 07-06 03:26:45.782 2085-2085/? E/AndroidRuntime: at android.support.v4.app.FragmentManagerImpl.moveToState(FragmentManager.java:1226) 07-06 03:26:45.782 2085-2085/? E/AndroidRuntime: at android.support.v4.app.FragmentManagerImpl.addFragment(FragmentManager.java:1328) 07-06 03:26:45.782 2085-2085/? E/AndroidRuntime: at android.support.v4.app.FragmentManagerImpl.onCreateView(FragmentManager.java:2284) 07-06 03:26:45.782 2085-2085/? E/AndroidRuntime: at android.support.v4.app.FragmentController.onCreateView(FragmentController.java:111) 07-06 03:26:45.782 2085-2085/? E/AndroidRuntime: a

So it points back to the 17th line in my MainActivity.java, which is super.onCreate(savedInstanceState);

Tried my best googling for a few hours, saw that there could be something wrong with the XML files, so I made sure they matched up perfectly.

Any help is appreciated, thanks, and apologies for formatting.

@RockUncleBratt
Copy link

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

If I may. there might be errors in your ForcastFragment.java file. What Branch are you on? There are several code fixes we have to find as part of the lesion with branch 3 and 4. Also after I completed Branch 3 my app crashed as there were things I was asking of my app that were not completed and until I reached The end of Branch 3 and found the errors that were intentional was I only then able to get it so my app did not crash.. Do you look through the errors in the event window?

Please sign in to comment.