Android Open Source - RiceCourses Main Activity






From Project

Back to project page RiceCourses.

License

The source code is released under:

MIT License

If you think the Android project RiceCourses listed in this page is inappropriate, such as containing malicious code/tools or violating the copyright, please email info at java2s dot com, thanks.

Java Source Code

package info.kevinlin.ricecourses;
/*from  w  w  w .j av a  2 s .c o m*/
import java.io.IOException;
import java.util.ArrayList;
import java.util.Calendar;

import org.json.JSONException;
import org.json.JSONObject;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;

import android.app.ActionBar;
import android.app.AlertDialog;
import android.app.PendingIntent;
import android.app.ProgressDialog;
import android.content.ComponentName;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.IntentSender;
import android.content.ServiceConnection;
import android.graphics.Color;
import android.graphics.drawable.ColorDrawable;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.IBinder;
import android.os.RemoteException;
import android.os.StrictMode;
import android.support.v7.app.ActionBarActivity;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.Spinner;
import android.widget.Toast;

import com.android.vending.billing.IInAppBillingService;


public class MainActivity extends ActionBarActivity implements AdapterView.OnItemSelectedListener {

    ProgressDialog mProgressDialog;

    IInAppBillingService mservice;
    ServiceConnection connection;
    String inappid = "donation"; //replace this with your in-app product id
    String donationResult = "Thanks for the donation!";

    public final static String URL = "info.kevinlin.ricecourses.URLSTRING";
    public final static String SESSION_CODE = "info.kevinlin.ricecourses.sessionCode";
    String termCodeSession = "";
    String termCodeYear = "";
    String subject = "";
    String titleText = "";

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

        //Get current year to populate a String[] year array.
        ArrayList<String> years = new ArrayList<String>();
        int currentYear = Calendar.getInstance().get(Calendar.YEAR);
        int year = 2004;
        while (year <= currentYear + 1)
        {
            years.add("" + year);
            year++;
        }

        //Initialize spinners.
        Spinner sessionSpinner = (Spinner) findViewById(R.id.sessionSpinner);
        ArrayAdapter<CharSequence> sessionAdapter = ArrayAdapter.createFromResource(this, R.array.sessionArray, android.R.layout.simple_spinner_item);
        sessionAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
        sessionSpinner.setAdapter(sessionAdapter);
        Spinner yearSpinner = (Spinner) findViewById(R.id.yearSpinner);
        ArrayAdapter<String> yearAdapter = new ArrayAdapter<String>(this, android.R.layout.simple_spinner_item, years);
        yearAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
        yearSpinner.setAdapter(yearAdapter);
        yearSpinner.setSelection(years.size() - 2);
        Spinner subjectSpinner = (Spinner) findViewById(R.id.subjectSpinner);
        ArrayAdapter<CharSequence> subjectAdapter = ArrayAdapter.createFromResource(this, R.array.subjectArray, android.R.layout.simple_spinner_item);
        subjectAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
        subjectSpinner.setAdapter(subjectAdapter);

        sessionSpinner.setOnItemSelectedListener(this);
        yearSpinner.setOnItemSelectedListener(this);
        subjectSpinner.setOnItemSelectedListener(this);

        StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitAll().build();
        StrictMode.setThreadPolicy(policy);

        ActionBar actionBar = getActionBar();
        actionBar.setBackgroundDrawable(new ColorDrawable(Color.rgb(11, 35, 69)));

        connection = new ServiceConnection() {

            @Override
            public void onServiceDisconnected(ComponentName name) {
                mservice = null;

            }

            @Override
            public void onServiceConnected(ComponentName name, IBinder service) {
                mservice = IInAppBillingService.Stub.asInterface(service);
            }
        };

        bindService(new Intent("com.android.vending.billing.InAppBillingService.BIND"), connection, Context.BIND_AUTO_CREATE);
    }


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

    public void onItemSelected(AdapterView<?> parent, View view, int pos, long id) {
        switch (parent.getId()) {
            case R.id.sessionSpinner:
                if (parent.getItemAtPosition(pos).toString().equals("Fall"))
                    termCodeSession = "10";
                if (parent.getItemAtPosition(pos).toString().equals("Spring"))
                    termCodeSession = "20";
                if (parent.getItemAtPosition(pos).toString().equals("Summer"))
                    termCodeSession = "30";
                break;
            case R.id.subjectSpinner:
                if (parent.getItemAtPosition(pos).toString().length() > 6 && !parent.getItemAtPosition(pos).toString().equals("Select a subject"))
                    subject = parent.getItemAtPosition(pos).toString().substring(0, 4);
                if (parent.getItemAtPosition(pos).toString().equals("Select a subject"))
                    subject = "";
                break;
        }
        int termCodeYearInt = Integer.parseInt(((Spinner)(findViewById(R.id.yearSpinner))).getSelectedItem().toString());
        if (termCodeSession.equals("10"))
            termCodeYearInt++;
        termCodeYear = "" + termCodeYearInt;
    }

    public void onNothingSelected(AdapterView<?> parent) {
        // Another interface callback
    }

    public void searchCourses(View view) {
        EditText title = (EditText)findViewById(R.id.titleEditText);
        Spinner subjectSpinner = (Spinner)findViewById(R.id.subjectSpinner);
        if (title.getText().toString().equals("") && subjectSpinner.getSelectedItem().toString().equals("Select a subject"))
            errorDialog();
        else {
            titleText = title.getText().toString();
            Intent intent = new Intent(this, CourseList.class);
            String urlstring = "http://courses.rice.edu/admweb/!SWKSCAT.cat?p_action=QUERY&p_term=" + termCodeYear + termCodeSession + "&p_name=&p_title=" + titleText + "&p_instr=&p_subj=" + subject + "&p_spon_coll=&p_df=&p_ptrm=&p_mode=AND";
            intent.putExtra(URL, urlstring);
            intent.putExtra(SESSION_CODE, termCodeYear + termCodeSession);
            startActivity(intent);
        }
    }

    public boolean onOptionsItemSelected(MenuItem item) {
        switch (item.getItemId()) {
            case R.id.action_about:
                aboutDialog();
                return true;
            case R.id.action_donate:
                donateDialog();
                return true;
            default:
                return super.onOptionsItemSelected(item);
        }
    }

    private void aboutDialog() {
        AlertDialog.Builder builder = new AlertDialog.Builder(this);
        builder.setMessage(R.string.about_message)
                .setTitle("About");
        builder.setPositiveButton("OK", new DialogInterface.OnClickListener() {
            public void onClick(DialogInterface dialog, int id) {
                // User clicked OK button
            }
        });
        builder.create().show();
    }

    private void donateDialog() {
        AlertDialog.Builder builder = new AlertDialog.Builder(this);
        builder.setMessage(R.string.donate_message).setTitle("About");
        builder.setPositiveButton("OK", new DialogInterface.OnClickListener() {
            public void onClick(DialogInterface dialog, int id) {
                new Donate().execute();
            }
        });
        builder.setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
            public void onClick(DialogInterface dialog, int id) {
                // User cancelled the dialog
            }
        });

        builder.create().show();
    }

    private void errorDialog() {
        AlertDialog.Builder builder = new AlertDialog.Builder(this);
        builder.setMessage(R.string.error_message)
                .setTitle("Error");
        builder.setPositiveButton("OK", new DialogInterface.OnClickListener() {
            public void onClick(DialogInterface dialog, int id) {
                // User clicked OK button
            }
        });
        builder.create().show();
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        if (requestCode == 1001) {
            String purchaseData = data.getStringExtra("INAPP_PURCHASE_DATA");

            if (resultCode == RESULT_OK) {
                try {
                    JSONObject jo = new JSONObject(purchaseData);
                    Toast toast = Toast.makeText(getApplicationContext(), donationResult, Toast.LENGTH_LONG);
                    toast.show();

                } catch (JSONException e) {
                    System.out.println("Failed to parse purchase data.");
                    e.printStackTrace();
                }
            }
        }
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        if (connection != null) {
            unbindService(connection);
        }
    }

    private class Donate extends AsyncTask<Void, Void, Void> {

        Bundle skuDetails;

        @Override
        protected void onPreExecute() {
            super.onPreExecute();
            mProgressDialog = new ProgressDialog(MainActivity.this);
            mProgressDialog.setTitle("Processing...");
            mProgressDialog.setMessage("Loading Google Play billing service...");
            mProgressDialog.setIndeterminate(false);
            mProgressDialog.setCancelable(false);
            mProgressDialog.setCanceledOnTouchOutside(false);
            mProgressDialog.show();
        }

        @Override
        protected Void doInBackground(Void... params) {
            ArrayList<String> skuList = new ArrayList<String>();
            skuList.add(inappid);
            Bundle querySkus = new Bundle();
            querySkus.putStringArrayList("ITEM_ID_LIST", skuList);
            try {
                skuDetails = mservice.getSkuDetails(3, getPackageName(), "inapp", querySkus);

            } catch (Exception e) {
                //do nothing because i am a lazy programmer
            }
            return null;
        }

        @Override
        protected void onPostExecute(Void result) {
            mProgressDialog.dismiss();
            try {
                int response = skuDetails.getInt("RESPONSE_CODE");
                if (response == 0) {

                    ArrayList<String> responseList = skuDetails.getStringArrayList("DETAILS_LIST");

                    for (String thisResponse : responseList) {
                        JSONObject object = new JSONObject(thisResponse);
                        String sku = object.getString("productId");
                        String price = object.getString("price");
                        if (sku.equals(inappid)) {
                            System.out.println("price " + price);
                            String randomString = "bGoa+V7g/yqDXvKRqq+JTFn4uQZbPiQJo4pf9RzJ";
                            Bundle buyIntentBundle = mservice.getBuyIntent(3, getPackageName(), sku, "inapp", randomString);
                            PendingIntent pendingIntent = buyIntentBundle.getParcelable("BUY_INTENT");
                            if (pendingIntent != null)
                                startIntentSenderForResult(pendingIntent.getIntentSender(), 1001, new Intent(), Integer.valueOf(0), Integer.valueOf(0), Integer.valueOf(0));
                            else
                                donationResult = "There was an error processing your donation. Perhaps you've already donated?";
                        }
                    }
                }
            }
            catch (JSONException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            } catch (IntentSender.SendIntentException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            } catch (RemoteException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
        }
    }

    private void showToast(String s, int i) {
        if (i == 0) {
            Toast toast = Toast.makeText(getApplicationContext(), s, Toast.LENGTH_SHORT);
            toast.show();
        }
        else {
            Toast toast = Toast.makeText(getApplicationContext(), s, Toast.LENGTH_LONG);
            toast.show();
        }
    }

}




Java Source Code List

info.kevinlin.ricecourses.ApplicationTest.java
info.kevinlin.ricecourses.CourseDetails.java
info.kevinlin.ricecourses.CourseList.java
info.kevinlin.ricecourses.Course.java
info.kevinlin.ricecourses.MainActivity.java
info.kevinlin.ricecourses.TabsPagerAdapter.java
info.kevinlin.ricecourses.detailsTab.java
info.kevinlin.ricecourses.webpageTab.java