ObjectScreen.java :  » UnTagged » interactive-museum-guide » museum » android » screens » Android Open Source

Android Open Source » UnTagged » interactive museum guide 
interactive museum guide » museum » android » screens » ObjectScreen.java
/*
Copyright 2011 Dietmar Wieser, Norbert Lanzanasto, Margit Mutschlechner.
Distributed under the terms of the GNU Lesser General Public License (LGPL).

This file is part of Interactive Museum Guide.

Interactive Museum Guide is free software: you can redistribute it and/or modify
it under the terms of the GNU Lesser General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.

Interactive Museum Guide is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
GNU Lesser General Public License for more details.

You should have received a copy of the GNU Lesser General Public License
along with Interactive Museum Guide.  If not, see <http://www.gnu.org/licenses/>.
*/

package museum.android.screens;

import java.io.ByteArrayInputStream;

import museum.android.connect.ServerConnection;
import museum.android.decode.IntentIntegrator;
import museum.android.decode.IntentResult;
import museum.android.persistence.Settings;
import museum.server.model.MuseumObject;
import museum.server.model.MuseumObjectResponse;
import museum.server.model.Property;
import android.app.Activity;
import android.content.Intent;
import android.graphics.drawable.Drawable;
import android.media.MediaPlayer;
import android.os.Bundle;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.RatingBar;
import android.widget.TableLayout;
import android.widget.TextView;
import android.widget.Toast;

/**
 * Screen to display an object.
 * 
 * @author Norbert Lanzanasto
 */
public class ObjectScreen extends Activity {

  private static final String TAG = "ObjectScreen";
  /** response of the server containing the requested object **/
  private static MuseumObjectResponse objectResp;
  /** true if user has already an id **/
  private static boolean hasUserId;
  private LayoutInflater mInflater;
  private RatingBar ratingBar;
  private MediaPlayer mp = new MediaPlayer();

  /**
   * Called when the activity is first created. Calls a method to scan a
   * qr-code or calls a method to initialize the screen if an object id is
   * already given.
   * 
   * @param savedInstanceState
   *            If the activity is being re-initialized after previously being
   *            shut down then this Bundle contains the data it most recently
   *            supplied in onSaveInstanceState(Bundle). Otherwise it is null.
   */
  @Override
  protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    hasUserId = false;

    boolean scan = getIntent().getBooleanExtra("scan", true);

    if (scan) {
      IntentIntegrator.initiateScan(ObjectScreen.this);
    } else {
      String objectId = getIntent().getStringExtra("object_id");
      initialize(objectId);
    }
  }

  /**
   * Called when an activity you launched exits, giving you the requestCode
   * you started it with, the resultCode it returned, and any additional data
   * from it. Gets called after scanning the qr-code. Displays an error
   * message if an error occured or calls a method to parse the result of the
   * scanning.
   * 
   * @param requestCode
   *            The integer request code originally supplied to
   *            startActivityForResult(), allowing you to identify who this
   *            result came from.
   * @param resultCode
   *            The integer result code returned by the child activity through
   *            its setResult().
   * @param data
   *            An Intent, which can return result data to the caller (various
   *            data can be attached to Intent "extras").
   */
  protected void onActivityResult(int requestCode, int resultCode, Intent data) {
    switch (requestCode) {
    case IntentIntegrator.REQUEST_CODE:
      if (resultCode != RESULT_CANCELED) {
        IntentResult scanResult = IntentIntegrator.parseActivityResult(
            requestCode, resultCode, data);
        if (scanResult != null) {
          String content = data.getStringExtra("SCAN_RESULT");
          initialize(content);
        } else {
          Log.d(TAG, "no scan result");
          Toast
              .makeText(getApplicationContext(),
                  "QR code could not be decoded!",
                  Toast.LENGTH_SHORT).show();
          finish();
        }
      } else {
        Log.d(TAG, "scan canceled");
        finish();
      }
      break;
    default:
      Log.d(TAG, "no scan result");
      Toast.makeText(getApplicationContext(),
          "QR code could not be decoded!", Toast.LENGTH_SHORT).show();
      finish();
    }
  }

  /**
   * Initializes the screen. Requests information for the object from the
   * server and calls a function to display it.
   * 
   * @param objectId
   *            id of the object to be displayed
   */
  private void initialize(String objectId) {
    setContentView(R.layout.object);
    if (objectId != null) {
      String userId = Settings.INSTANCE.getUserId();

      if (userId == null || userId.equals("")) {
        Log.d(TAG, "No user id found");
      } else {
        Log.d(TAG, "User id found: " + userId);
        hasUserId = true;
      }

      objectResp = ServerConnection.getObjectById(objectId, userId);

      if (objectResp != null) {
        if (objectResp.getErrorCode() == 0) {

          if (!hasUserId) {
            userId = objectResp.getUserId();
            Settings.INSTANCE.setUserId(userId);
            System.out.println("userid saved");
          }
          MuseumObject museumObject = objectResp.getObject();
          if (museumObject != null) {
            displayObject(museumObject);
          } else {
            Log.d(TAG, "no museum object found");
            Toast.makeText(getApplicationContext(),
                "Sorry, server temporary not available!",
                Toast.LENGTH_SHORT).show();
            finish();
          }
        } else {
          Log.d(TAG, objectResp.getErrorMsg());
          Toast.makeText(getApplicationContext(),
              objectResp.getErrorMsg(), Toast.LENGTH_SHORT)
              .show();
          finish();
        }
      } else {
        Log.d(TAG, "no response found");
        Toast.makeText(getApplicationContext(),
            "Sorry, server temporary not available!",
            Toast.LENGTH_SHORT).show();
        finish();
      }

    } else {
      Log.d(TAG, "no object id");
      Toast.makeText(getApplicationContext(),
          "QR code could not be decoded!", Toast.LENGTH_SHORT).show();
      finish();
    }
  }

  /**
   * Displays an object on the ObjectScreen.
   * 
   * @param museumObject
   *            object to be displayed
   */
  private void displayObject(MuseumObject museumObject) {

    TextView nameTextView = (TextView) findViewById(R.id.objectNameTextView);
    nameTextView.setText(museumObject.getName());

    ImageView imageView = (ImageView) findViewById(R.id.objectImageView);
    if (museumObject.getIcon() == null)
      imageView.setImageResource(R.drawable.icon);
    else
      imageView.setImageDrawable(Drawable.createFromStream(
          new ByteArrayInputStream(museumObject.getIcon()),
          museumObject.getName()));

    TextView infoTextView = (TextView) findViewById(R.id.objectInfoTextView);
    infoTextView.setText(museumObject.getDescription());
    ratingBar = (RatingBar) findViewById(R.id.objectRatingbar);
    Log.i("-----------------", "" + objectResp.getRating());
    ratingBar.setRating(objectResp.getRating());
    TableLayout keyvalue = (TableLayout) findViewById(R.id.objectKeyValuePairsTable);
    mInflater = LayoutInflater.from(this);
    for (int i = 0; i < museumObject.propertySize(); i++) {
      final Property prop = museumObject.propertyAt(i);
      View aView = mInflater.inflate(R.layout.object_property, null);
      TextView txtKey = (TextView) aView.findViewById(R.id.txtKey);
      txtKey.setText(prop.getName());
      TextView txtValue = (TextView) aView.findViewById(R.id.txtValue);
      txtValue.setText(prop.getValue());
      final Button butUrl = (Button) aView.findViewById(R.id.butUrl);
      butUrl.setText("Play");
      butUrl.setOnClickListener(new OnClickListener() {
        public void onClick(View v) {
          if (butUrl.getText().equals("Play")) {
            try {
              mp = new MediaPlayer();
              mp.setDataSource(prop.getMediaUrl());
              mp.prepare();
            } catch (Exception e) {
              e.printStackTrace();
            }

            mp.start();
            butUrl.setText("Stop");
          } else {
            mp.stop();
            mp.release();
            butUrl.setText("Play");
          }
        }
      });
      if (prop.getMediaUrl() == null || prop.getMediaUrl().equals(""))
        butUrl.setVisibility(View.GONE);
      keyvalue.addView(aView);
    }

  }

  /**
   * Initialize the contents of the Activity's standard options menu.
   * 
   * @param menu
   *            The options menu in which you place your items.
   * @return boolean You must return true for the menu to be displayed; if you
   *         return false it will not be shown.
   */
  public boolean onCreateOptionsMenu(Menu menu) {
    MenuInflater inflater = getMenuInflater();
    inflater.inflate(R.menu.object_menu, menu);
    return true;
  }

  /**
   * This hook is called whenever an item in the options menu is selected.
   * 
   * @param item
   *            The menu item that was selected.
   * @return boolean Return false to allow normal menu processing to proceed,
   *         true to consume it here.
   */
  public boolean onOptionsItemSelected(MenuItem item) {
    switch (item.getItemId()) {
    case (R.id.menu_quit):
      moveTaskToBack(true);
      break;
    case (R.id.menu_rate):
      RatingDialog customizeDialog = new RatingDialog(ObjectScreen.this,
          objectResp.getObject().getObjectId());
      customizeDialog.show();
      break;
    }
    return true;
  }

  /**
   * Called whenever the user rated the current visited object.
   * 
   * @param rating
   *            new rating for the object
   */
  public void refreshRating(float rating) {
    if (ratingBar != null) {
      ratingBar.setRating(rating);
      System.out.println("refresh rating to " + rating);
    }
  }
}
java2s.com  | Contact Us | Privacy Policy
Copyright 2009 - 12 Demo Source and Support. All rights reserved.
All other trademarks are property of their respective owners.