gtikhono.msse.asu.edu.moviedescriptions.MovieLibrary.java Source code

Java tutorial

Introduction

Here is the source code for gtikhono.msse.asu.edu.moviedescriptions.MovieLibrary.java

Source

package gtikhono.msse.asu.edu.moviedescriptions;

import android.app.Activity;
import org.json.JSONObject;
import org.json.JSONTokener;

import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.Serializable;
import java.util.HashMap;
import java.util.Iterator;

/*
* Copyright  2016 Gabriela Tikhonova
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* Purpose: load the movie.json into a HashMap of Movie Descriptions and
* make an object out of it for the Main Activity to utilize
*
* JSON string source: http://www.omdbapi.com/
*
* Ser423 Mobile Applications
* @author   Gabriela Tikhonova  mailto:gtikhono@asu.edu.
* @version February 11, 2016
*/
public class MovieLibrary implements Serializable {

    private transient MainActivity mainActivity;
    protected HashMap<String, MovieDescription> movieHashmap;

    MovieLibrary(MainActivity main) {
        movieHashmap = new HashMap();
        mainActivity = main;
        this.loadMovies(mainActivity);
    }

    public void loadMovies(Activity main) {

        try {
            InputStream jsonMoviesStream = main.getApplicationContext().getResources()
                    .openRawResource(R.raw.movies);
            BufferedReader reader = new BufferedReader(new InputStreamReader(jsonMoviesStream));

            JSONObject jsonMoviesObject = new JSONObject(new JSONTokener(reader.readLine()));
            Iterator<String> iterator = jsonMoviesObject.keys();

            while (iterator.hasNext()) {
                String titleKey = iterator.next();

                JSONObject movie = jsonMoviesObject.optJSONObject(titleKey);

                if (movie != null) {
                    MovieDescription moviedescription = new MovieDescription(movie.toString());
                    movieHashmap.put(titleKey, moviedescription);
                    System.out.println(moviedescription);

                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public HashMap getMovieHashmap() {
        return movieHashmap;
    }

}