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

2.01 add the Network Code  #325

@edjata

Description

@edjata

Well, I am very, very new to android development. So please don't laugh. I want to learn at my old age. Went through the Udacity Java class now I'm here. Got through all of part 1 with minimal issues. I even created a second string array in my app just to make sure I got it. yup it worked!! However, now I am stuck!!! After adding the networking code my app won't work. Everything looks right to me, but what do I know, lol. Hopefully someone out there can help me. This is day 3 trying to find out what I'm doing wrong.

MainActivity.java

package com.example.android.sunshine.app;

import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
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 MainActivityFragment.PlaceholderFragment())
                .commit();
    }

    Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
    setSupportActionBar(toolbar);
}

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

}

MainActivityFragment.java

package com.example.android.sunshine.app;

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;

/**

  • A placeholder fragment containing a simple view.
    */
    public class MainActivityFragment extends Fragment {

    public static class PlaceholderFragment extends Fragment{

    // Declaring Adapter

    ArrayAdapter mForcecastAdapter;

    public PlaceholderFragment() {
    }

    @OverRide

    //this is the onCreateView method for the placeholder fragment

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

     //Creates the String[] Array named dateForecastArray
    
     String[] dateForecastArray = {
             "Today - Sunny - 88/63",
             "Tomorrow - Foggy - 70/46",
             "Weds - Cloudy - 72/63",
             "Thurs - Rainy - 64/51",
             "Fri - Foggy - 70/46",
             "Sat - Sunny - 76/68",
             "Sun - Trapped in Heat - 105/99"
     };
    
     //Creates the String[] Array named oldDateForecastArray "My test"
    
     String[] oldDateForecastArray ={
             "Mon - Jan 1, 2017 - Cold/Snow - 15/3",
             "Tues - Jan 2, 2017 - Rain/Snow - 15/3",
             "Wed - Jan 3, 2017 - Cold - 15/3",
             "Thus - Jan 4, 2017 - Rain - 15/3",
             "Fri - Jan 5, 2017 - Icy Rain - 15/3",
             "Sat - Jan 6, 2017 - Cold - 15/3",
             "Sun - Jan 7, 2017 - Sunny/Cold - 15/3"
     };
    
     //calling the String Array
    
     List<String> weekForecast = new ArrayList<String>(
             Arrays.asList(oldDateForecastArray)
     );
    
     /**
      * initializing Adapter:
      * create ArrayAdapter<String>:
     * mForcecastAdapter = new ArrayAdapter<String>
     *
     *Parameters:
     *    context: getActivity()
     *
     *    --**NOTE: "context" contains global information about the app environment
     *    -*       It allows us to access system services and resources
     *    -*       As well as the application specific resources we define
     *
     *    ID of list item layout: R.layout.list_item_forecast
     *    --**Note: "R.layout" refers to a layout file
     *
     *    ID of text view: R.id.list_item_forecast_textview
     *    --**Note: "R.id" refers to a specific XML element with the matching id attribute
     *
     *    list of data: weekForecast
     *    --**Note: The array list of forecast defined
      */
    
     mForcecastAdapter =
             new ArrayAdapter<String> (
                     //The current context (the fragment's parent activity)
                     getActivity(),
                     //ID of list item layout
                     R.layout.list_item_forecast,
                     //ID of textview to populate
                     R.id.list_item_forecast_textview,
                     //forecast data
                     weekForecast);
     //inflated rootView
     View rootView = inflater.inflate(R.layout.fragment_main, container, false);
    
     //Create reference to listview find by ID
     /**
      * View hierarchy: example
      * tier 1:                [Relative Layout] id:root
      *                                   /    \
      * tier 2: [Linear Layout] id:container,  [Button] id:btn
      *             /           \
      * t3: [image] no id,  [TextView] id:txt
      *
      * java code:
      *      Button b = (Button)this.findViewById(R.id.btn);
      *      LinearLayout container = (LinearLayout)this.findViewById(R.id.container)
      *      TextView t = (TextView)container.findViewById(R.id.txt);
      */
    
     //Get a reference to the ListView. rootView here refers to rootView of the fragment inflated above
     ListView listView = (ListView) rootView.findViewById(R.id.listview_forecast);
    
     //binding adapter to listView
     listView.setAdapter(mForcecastAdapter);
    
    
    
     // 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=30034&mode=json&units=metric&cnt=7&APPID=c67f4ffaa108e5944910a9d3795aad9e");
    
         // 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("PlaceholderFragment", "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("PlaceholderFragment", "Error closing stream", e);
             }
         }
     }
    
     return rootView;
    

    }

    }

}

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions