com.joda.tentatime.FindExamActivity.java Source code

Java tutorial

Introduction

Here is the source code for com.joda.tentatime.FindExamActivity.java

Source

package com.joda.tentatime;

import android.app.Activity;
import android.app.ProgressDialog;
import android.os.AsyncTask;
import android.os.Bundle;
import android.text.method.ScrollingMovementMethod;
import android.view.View;
import android.view.View.OnClickListener;

import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.LinearLayout;
import android.widget.ListAdapter;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.EditText;
import android.widget.Toast;

import android.content.Intent;

import com.google.gson.Gson;

import org.apache.http.HttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;

import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.Serializable;
import java.util.ArrayList;
import java.util.List;

/**
 * Created by daniel on 8/6/13.
 * <p/>
 * Copyright (c) Joseph Hejderup & Daniel Kristoffersson, All rights reserved.
 * See License.txt in the project root for license information.
 */
public class FindExamActivity extends Activity {

    ListView examsView;
    EditText mGetExam;
    List<ExamResult> results;

    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_find_exam);
        setupWidgets();
    }

    private void setupWidgets() {
        Button btn = (Button) findViewById(R.id.searchB);
        btn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                DownloadJsonTask task = new DownloadJsonTask();
                task.execute(userChoice(mGetExam.getText().toString()));
            }
        });

        mGetExam = (EditText) findViewById(R.id.getExam);
        examsView = (ListView) findViewById(R.id.examsLV);
        examsView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                Intent intent = new Intent(FindExamActivity.this, Result.class);
                Bundle b = new Bundle();
                b.putSerializable("key", (Serializable) results.get(position));
                intent.putExtras(b); //deliver the exam to the next Intent
                startActivityForResult(intent, 1);
            }
        });

        // CAST THE LINEARLAYOUT HOLDING THE MAIN PROGRESS (SPINNER)
        //linlaHeaderProgress = (LinearLayout) findViewById(R.id.linlaHeaderProgress);
    }

    private String userChoice(String choice) {

        //reset EditText to ""
        mGetExam.setText("");

        if (InputUtility.validateCourseID(choice))
            return "http://tentatime-jhejderup.rhcloud.com/v1/exams.json/" + choice;
        else if (InputUtility.validateName(choice))
            return "http://tentatime-jhejderup.rhcloud.com/v1/exams.json?course_name=" + choice;
        else
            return "";
    }

    private class DownloadJsonTask extends AsyncTask<String, Void, SearchResponse> {

        // CAST THE LINEARLAYOUT HOLDING THE MAIN PROGRESS (SPINNER)
        //LinearLayout linlaHeaderProgress = (LinearLayout) findViewById(R.id.linlaHeaderProgress);

        @Override
        protected SearchResponse doInBackground(String... urls) {
            //TODO: check that only one url exists!
            SearchResponse response = new SearchResponse();
            for (String url : urls) {
                //TODO: add handling of missing internet conenctivity...
                DefaultHttpClient client = new DefaultHttpClient();
                HttpGet httpGet = new HttpGet(url);
                try {
                    HttpResponse execute = client.execute(httpGet);
                    InputStream content = execute.getEntity().getContent();
                    //System.out.print(content.toString());
                    InputStreamReader reader = new InputStreamReader(content);
                    Gson gson = new Gson();
                    response = gson.fromJson(reader, SearchResponse.class); //TODO: check json for null...
                } catch (Exception e) {
                    e.printStackTrace();
                    //onPostExecute will handle this instead...
                    response = null;
                }
            }
            return response;
        }

        @Override
        protected void onPreExecute() {
            // SHOW THE SPINNER WHILE LOADING FEEDS
            //linlaHeaderProgress.setVisibility(View.VISIBLE);
            //Clear the list
            examsView.setAdapter(null);
        }

        @Override
        protected void onPostExecute(SearchResponse response) {
            //TODO: fix return to main thread... DON'T NEED

            // HIDE THE SPINNER AFTER LOADING FEEDS
            //linlaHeaderProgress.setVisibility(View.GONE);

            if (response != null) {
                results = response.getResults();

                String examNames[] = new String[results.size()];
                int pos = 0;

                for (ExamResult exam : results) {
                    examNames[pos] = exam.getCode() + ": " + exam.getName().trim() + "\n" + exam.getBeginsAt() + " "
                            + exam.getExamDate();
                    pos++;
                }

                // SET THE ADAPTER TO THE LISTVIEW
                examsView.setAdapter(new ArrayAdapter<String>(com.joda.tentatime.FindExamActivity.this,
                        android.R.layout.simple_list_item_1, examNames));

                // CHANGE THE LOADINGMORE STATUS TO PERMIT FETCHING MORE DATA
                //loadingMore = false;

            } else
                //Todo: make a toast: list is empty... DONE
                Toast.makeText(getApplicationContext(), "No exams were found, please try again!", Toast.LENGTH_LONG)
                        .show();

        }
    }
}