edu.csh.coursebrowser.SchoolActivity.java Source code

Java tutorial

Introduction

Here is the source code for edu.csh.coursebrowser.SchoolActivity.java

Source

/*******************************************************************************
 * Copyright (c) 2012 Andrew Hanes
 *
 * Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
 *
 * The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
 *
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
 ******************************************************************************/
package edu.csh.coursebrowser;

import android.app.Activity;
import android.app.ProgressDialog;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.AsyncTask;
import android.os.Bundle;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ArrayAdapter;
import android.widget.ListView;
import android.widget.TextView;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import shared.AlertError;
import shared.Department;
import shared.School;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLConnection;
import java.util.ArrayList;
import java.util.HashMap;

public class SchoolActivity extends Activity {
    HashMap<String, School> map_items = null;
    ArrayList<String> map = null;
    public static SharedPreferences sp;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_course_browser);
        ListView lv = (ListView) this.findViewById(R.id.schools);
        this.setTitle("Course Browser");

        map_items = new HashMap<String, School>();
        map = new ArrayList<String>();
        this.sp = getPreferences(MODE_WORLD_READABLE);
        ArrayAdapter<String> adapter = new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1, map);
        this.setTitle("Course Browser");

        if (!sp.contains("firstRun")) {
            SharedPreferences.Editor e = sp.edit();
            e.putBoolean("firstRun", false);
            e.commit();
            Intent intent = new Intent(SchoolActivity.this, AboutActivity.class);
            startActivity(intent);
        }

        addItem(new School("01", "Saunder's College of Business"));
        addItem(new School("03", "College of Engineering"));
        addItem(new School("05", "College of Liberal Arts"));
        addItem(new School("06", "Applied Science & Technology"));
        addItem(new School("08", "NTID"));
        addItem(new School("10", "College of Science"));
        addItem(new School("11", "Wellness"));
        addItem(new School("17", "Academic Services"));
        addItem(new School("20", "Imaging Arts and Sciences"));
        addItem(new School("30", "Interdisciplinary Studies"));
        addItem(new School("40", "GCCIS"));
        addItem(new School("50", "Institute for Sustainability"));

        lv.setAdapter(adapter);

        lv.setOnItemClickListener(new OnItemClickListener() {

            @Override
            public void onItemClick(AdapterView<?> arg0, View arg1, int arg2, long arg3) {
                String s = ((TextView) arg1).getText().toString();
                final School school = map_items.get(s);
                new AsyncTask<String, String, String>() {
                    ProgressDialog p;

                    protected void onPreExecute() {
                        p = new ProgressDialog(SchoolActivity.this);
                        p.setTitle("Fetching Info");
                        p.setMessage("Contacting Server...");
                        p.setCancelable(false);
                        p.show();
                    }

                    protected String doInBackground(String... school) {
                        String params = "action=getDepartments&school=" + school[0] + "&quarter=20123";
                        Log.v("Params", params);
                        URL url;
                        String back = "";
                        try {
                            url = new URL("http://iota.csh.rit" + ".edu/schedule/js/browseAjax.php");

                            URLConnection conn = url.openConnection();
                            conn.setDoOutput(true);
                            OutputStreamWriter writer = new OutputStreamWriter(conn.getOutputStream());
                            writer.write(params);
                            writer.flush();
                            String line;
                            BufferedReader reader = new BufferedReader(
                                    new InputStreamReader(conn.getInputStream()));

                            while ((line = reader.readLine()) != null) {
                                Log.v("Back:", line);
                                back += line;
                            }
                            writer.close();
                            reader.close();
                        } catch (MalformedURLException e) {
                            // TODO Auto-generated catch block
                            e.printStackTrace();
                            return null;
                        } catch (IOException e) {
                            // TODO Auto-generated catch block
                            e.printStackTrace();
                            return null;
                        }
                        return back;
                    }

                    protected void onPostExecute(String s) {
                        if (s == null || s == "") {
                            new AlertError(SchoolActivity.this, "IO Error!").show();
                            return;
                        }

                        try {
                            JSONObject jso = new JSONObject(s);
                            JSONArray jsa = new JSONArray(jso.getString("departments"));
                            ArrayList<Department> depts = new ArrayList<Department>();
                            for (int i = 0; i < jsa.length(); ++i) {
                                JSONObject obj = new JSONObject(jsa.get(i).toString());
                                depts.add(new Department(obj.getString("title"), obj.getString("id"),
                                        obj.getString("code")));
                            }

                        } catch (JSONException e) {
                            e.printStackTrace();
                            new AlertError(SchoolActivity.this, "Invalid JSON From Server").show();
                            p.dismiss();
                            return;
                        }

                        Intent intent = new Intent(SchoolActivity.this, DepartmentActivity.class);
                        intent.putExtra("from", school.deptName);
                        intent.putExtra("args", s);
                        intent.putExtra("qCode", sp.getString("quarter", "20122"));
                        startActivity(intent);
                        p.dismiss();
                    }
                }.execute(school.deptNum);
            }

        });

    }

    public void addItem(School s) {
        assert (map != null && map_items != null);
        this.map_items.put(s.deptName, s);
        this.map.add(s.deptName);
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(R.menu.activity_course_browser, menu);
        return true;
    }

    public boolean onOptionsItemSelected(MenuItem item) {
        switch (item.getItemId()) {
        case R.id.menu_settings:
            Intent intent = new Intent(this, SettingsActivity.class);
            startActivity(intent);
            return true;
        case R.id.menu_about:
            Intent i = new Intent(this, AboutActivity.class);
            startActivity(i);
            return true;
        default:
            return false;
        }
    }
}