Last Updated
Viewed 12 Times
     

So I've just downloaded project from udacity course. Unfortunately I've received some kinds of error, that I can't fix.. I've already added Internet permision, what else could I do?

Here's the code from github https://github.com/udacity/ud843_Soonami

And here's the error

Problem parsing the earthquake JSON results
    org.json.JSONException: End of input at character 0

MainActivity

 /**
 * Displays information about a single earthquake.
 */
public class MainActivity extends AppCompatActivity {

    /** Tag for the log messages */
    public static final String LOG_TAG = MainActivity.class.getSimpleName();

    /** URL to query the USGS dataset for earthquake information */
    private static final String USGS_REQUEST_URL =
            "http://earthquake.usgs.gov/fdsnws/event/1/query?format=geojson&starttime=2012-01-01&endtime=2012-12-01&minmagnitude=6";

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        // Kick off an {@link AsyncTask} to perform the network request
        TsunamiAsyncTask task = new TsunamiAsyncTask();
        task.execute();
    }

    /**
     * Update the screen to display information from the given {@link Event}.
     */
    private void updateUi(Event earthquake) {
        // Display the earthquake title in the UI
        TextView titleTextView = (TextView) findViewById(R.id.title);
        titleTextView.setText(earthquake.title);

        // Display the earthquake date in the UI
        TextView dateTextView = (TextView) findViewById(R.id.date);
        dateTextView.setText(getDateString(earthquake.time));

        // Display whether or not there was a tsunami alert in the UI
        TextView tsunamiTextView = (TextView) findViewById(R.id.tsunami_alert);
        tsunamiTextView.setText(getTsunamiAlertString(earthquake.tsunamiAlert));
    }

    /**
     * Returns a formatted date and time string for when the earthquake happened.
     */
    private String getDateString(long timeInMilliseconds) {
        SimpleDateFormat formatter = new SimpleDateFormat("EEE, d MMM yyyy 'at' HH:mm:ss z");
        return formatter.format(timeInMilliseconds);
    }

    /**
     * Return the display string for whether or not there was a tsunami alert for an earthquake.
     */
    private String getTsunamiAlertString(int tsunamiAlert) {
        switch (tsunamiAlert) {
            case 0:
                return getString(R.string.alert_no);
            case 1:
                return getString(R.string.alert_yes);
            default:
                return getString(R.string.alert_not_available);
        }
    }

    /**
     * {@link AsyncTask} to perform the network request on a background thread, and then
     * update the UI with the first earthquake in the response.
     */
    private class TsunamiAsyncTask extends AsyncTask<URL, Void, Event> {

        @Override
        protected Event doInBackground(URL... urls) {
            // Create URL object
            URL url = createUrl(USGS_REQUEST_URL);

            // Perform HTTP request to the URL and receive a JSON response back
            String jsonResponse = "";
            try {
                jsonResponse = makeHttpRequest(url);
            } catch (IOException e) {
                // TODO Handle the IOException
            }

            // Extract relevant fields from the JSON response and create an {@link Event} object
            Event earthquake = extractFeatureFromJson(jsonResponse);

            // Return the {@link Event} object as the result fo the {@link TsunamiAsyncTask}
            return earthquake;
        }

        /**
         * Update the screen with the given earthquake (which was the result of the
         * {@link TsunamiAsyncTask}).
         */
        @Override
        protected void onPostExecute(Event earthquake) {
            if (earthquake == null) {
                return;
            }

            updateUi(earthquake);
        }

        /**
         * Returns new URL object from the given string URL.
         */
        private URL createUrl(String stringUrl) {
            URL url = null;
            try {
                url = new URL(stringUrl);
            } catch (MalformedURLException exception) {
                Log.e(LOG_TAG, "Error with creating URL", exception);
                return null;
            }
            return url;
        }

        /**
         * Make an HTTP request to the given URL and return a String as the response.
         */
        private String makeHttpRequest(URL url) throws IOException {
            String jsonResponse = "";
            HttpURLConnection urlConnection = null;
            InputStream inputStream = null;
            try {
                urlConnection = (HttpURLConnection) url.openConnection();
                urlConnection.setRequestMethod("GET");
                urlConnection.setReadTimeout(10000 /* milliseconds */);
                urlConnection.setConnectTimeout(15000 /* milliseconds */);
                urlConnection.connect();
                inputStream = urlConnection.getInputStream();
                jsonResponse = readFromStream(inputStream);
            } catch (IOException e) {
                // TODO: Handle the exception
            } finally {
                if (urlConnection != null) {
                    urlConnection.disconnect();
                }
                if (inputStream != null) {
                    // function must handle java.io.IOException here
                    inputStream.close();
                }
            }
            return jsonResponse;
        }

        /**
         * Convert the {@link InputStream} into a String which contains the
         * whole JSON response from the server.
         */
        private String readFromStream(InputStream inputStream) throws IOException {
            StringBuilder output = new StringBuilder();
            if (inputStream != null) {
                InputStreamReader inputStreamReader = new InputStreamReader(inputStream, Charset.forName("UTF-8"));
                BufferedReader reader = new BufferedReader(inputStreamReader);
                String line = reader.readLine();
                while (line != null) {
                    output.append(line);
                    line = reader.readLine();
                }
            }
            return output.toString();
        }

        /**
         * Return an {@link Event} object by parsing out information
         * about the first earthquake from the input earthquakeJSON string.
         */
        private Event extractFeatureFromJson(String earthquakeJSON) {
            try {
                JSONObject baseJsonResponse = new JSONObject(earthquakeJSON);
                JSONArray featureArray = baseJsonResponse.getJSONArray("features");

                // If there are results in the features array
                if (featureArray.length() > 0) {
                    // Extract out the first feature (which is an earthquake)
                    JSONObject firstFeature = featureArray.getJSONObject(0);
                    JSONObject properties = firstFeature.getJSONObject("properties");

                    // Extract out the title, time, and tsunami values
                    String title = properties.getString("title");
                    long time = properties.getLong("time");
                    int tsunamiAlert = properties.getInt("tsunami");

                    // Create a new {@link Event} object
                    return new Event(title, time, tsunamiAlert);
                }
            } catch (JSONException e) {
                Log.e(LOG_TAG, "Problem parsing the earthquake JSON results", e);
            }
            return null;
        }
    }
}

Event (pojo)

    public class Event {

    /** Title of the earthquake event */
    public final String title;

    /** Time that the earthquake happened (in milliseconds) */
    public final long time;

    /** Whether or not a tsunami alert was issued (1 if it was issued, 0 if no alert was issued) */
    public final int tsunamiAlert;

    /**
     * Constructs a new {@link Event}.
     *
     * @param eventTitle is the title of the earthquake event
     * @param eventTime is the time the earhtquake happened
     * @param eventTsunamiAlert is whether or not a tsunami alert was issued
     */
    public Event(String eventTitle, long eventTime, int eventTsunamiAlert) {
        title = eventTitle;
        time = eventTime;
        tsunamiAlert = eventTsunamiAlert;
    }
}

JSON response

    {
  "type": "FeatureCollection",
  "metadata": {
    "generated": 1575220865000,
    "url": "https://earthquake.usgs.gov/fdsnws/event/1/query?format=geojson&starttime=2012-01-01&endtime=2012-12-01&minmagnitude=6",
    "title": "USGS Earthquakes",
    "status": 200,
    "api": "1.8.1",
    "count": 122
  },
  "features": [
    {
      "type": "Feature",
      "properties": {
        "mag": 6.7999999999999998,
        "place": "Izu Islands, Japan region",
        "time": 1325395675980,
        "updated": 1435683543922,
        "tz": null,
        "url": "https://earthquake.usgs.gov/earthquakes/eventpage/usp000jcws",
        "detail": "https://earthquake.usgs.gov/fdsnws/event/1/query?eventid=usp000jcws&format=geojson",
        "felt": 300,
        "cdi": 5.0999999999999996,
        "mmi": null,
        "alert": null,
        "status": "reviewed",
        "tsunami": 0,
        "sig": 864,
        "net": "us",
        "code": "p000jcws",
        "ids": ",usp000jcws,usc0007fbh,choy20120101052756,duputel201201010527a,",
        "sources": ",us,us,choy,duputel,",
        "types": ",associate,dyfi,focal-mechanism,impact-text,moment-tensor,origin,phase-data,",
        "nst": 628,
        "dmin": null,
        "rms": 0.83999999999999997,
        "gap": 10.800000000000001,
        "magType": "mww",
        "type": "earthquake",
        "title": "M 6.8 - Izu Islands, Japan region"
      },
      "geometry": {
        "type": "Point",
        "coordinates": [
          138.072,
          31.456,
          365.30000000000001
        ]
      },
      "id": "usp000jcws"
    }
  ],
  "bbox": [
    -178.295,
    -60.948,
    6.3,
    178.52,
    72.96,
    586.9
  ]
}

I was trying to run this code but it's not working.

You should create a calculator with its basic functions.

Create a calculator class which has sum, subtract, division, and multiply methods, all of them take two int parameters and return the resulted int.

Example: When the sum method is called as sum(5,6), it should return 11 which is the sum of 5 and 6

How can I fix it ?

class MyCalculator {
    int input1 = 15;
    int input2 = 5; 
    public float sum() {

        int sum = input1 + input2;
         return sum;
    }

    public float divid() {
        // TODO: write java code to calculate the average for all input variables
       int divid = (input1 / input2);
         return divid;
    }
    public float subtract() {
        // TODO: write java code to calculate the average for all input variables
        int subtract = (input1 - input2);
         return subtract;
    }
    public float multiply() {
        // TODO: write java code to calculate the average for all input variables
        int multiply = (input1 * input2);
         return multiply;
    }

}

It gives me this error

method sum in class MyCalculator cannot be applied to given types;
required: no arguments
found: int,int
reason: actual and formal argument lists differ in length
method divid in class MyCalculator cannot be applied to given types;
required: no arguments
found: int,int
reason: actual and formal argument lists differ in length
method subtract in class MyCalculator cannot be applied to given types;
required: no arguments
found: int,int
reason: actual and formal argument lists differ in length
method multiply in class MyCalculator cannot be applied to given types;
required: no arguments
found: int,int
reason: actual and formal argument lists differ in length

I am new to android and following the Udacity Android developer course to learn. I am on chapter 3 where they teach about the adding the settings in your app. I have added the SettingActivity from android studio. When I click on settings menu, my app crashes. This is my pref_general.xml file

<PreferenceScreen xmlns:android="http://schemas.android.com/apk/res/android">

<!-- NOTE: EditTextPreference accepts EditText attributes. -->
<!-- NOTE: EditTextPreference's summary should be set to its value by the activity code. -->
<EditTextPreference
    android:key="@string/pref_location_key"
    android:defaultValue="@string/pref_location_default"
    android:maxLines="1"
    android:inputType="text"
    android:selectAllOnFocus="true"
    android:singleLine="true"
    android:title="@string/pref_location_label" />

I have made these changes in SettingActivity

protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setupActionBar();
addPreferencesFromResource(R.xml.pref_general);
bindPreferenceSummaryToValue(findPreference(getString(R.string.pref_location_key)));}

I am getting following exception when I click the Setting menu

Process: com.example.android.sunshine.app, PID: 10131
java.lang.RuntimeException: Unable to start activity ComponentInfo{com.example.android.sunshine.app/com.example.android.sunshine.app.SettingsActivity}: java.lang.RuntimeException: Modern two-pane PreferenceActivity requires use of a PreferenceFragment
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2339)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2413)
at android.app.ActivityThread.access$800(ActivityThread.java:155)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1317)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:135)
at android.app.ActivityThread.main(ActivityThread.java:5343)
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:905)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:700)

Caused by: java.lang.RuntimeException: Modern two-pane PreferenceActivity requires use of a PreferenceFragment
 at android.preference.PreferenceActivity.requirePreferenceManager(PreferenceActivity.java:1441)
 at android.preference.PreferenceActivity.addPreferencesFromResource(PreferenceActivity.java:1511)
 at com.example.android.sunshine.app.SettingsActivity.onCreate(SettingsActivity.java:124)
 at android.app.Activity.performCreate(Activity.java:6010)
 at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1129)
 at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2292)
 at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2413) 
 at android.app.ActivityThread.access$800(ActivityThread.java:155) 
 at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1317) 
 at android.os.Handler.dispatchMessage(Handler.java:102) 
 at android.os.Looper.loop(Looper.java:135) 
 at android.app.ActivityThread.main(ActivityThread.java:5343) 
 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:905) 
 at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:700)

Any help? Sorry if its very naive thing

i have recently changed back to Ubuntu from windows and i am trying to start android programming on it again. i have installed oracle Jdk and downloaded the bundle but when I open it it gives me the error:

[2014-03-07 13:45:03 - adb] Unexpected exception 'Cannot run program "/home/abdollah/Documents/adt-bundle-linux-x86_64-20131030/sdk/platform-tools/adb": error=2, No such file or directory' while attempting to get adb version from '/home/abdollah/Documents/adt-bundle-linux-x86_64-20131030/sdk/platform-tools/adb'

could it be because i had CDT before separately with a different version of eclipse before? with the same work-space? would appreciate any help!

Similar Question 4 (1 solutions) : JSON parser can't run

Similar Question 5 (3 solutions) : Can't run the ActionBarCompat sample

Similar Question 6 (5 solutions) : Can't resolve symbol “context” on simple program

Similar Question 7 (3 solutions) : Can not run program, permission denied erro13 Jenkins

Similar Question 8 (1 solutions) : Can't use program to close an android app

Similar Question 9 (4 solutions) : Can't find Java folder in Program Files

cc