# Table of Contents
- [Initial page | CISC 349](#initial-page-cisc-349)
- [GitHub Instructions | CISC 349](#github-instructions-cisc-349)
- [Introduction to Java programming | CISC 349](#introduction-to-java-programming-cisc-349)
- [Your First Android Application | CISC 349](#your-first-android-application-cisc-349)
- [Android and Model-View-Controller | CISC 349](#android-and-model-view-controller-cisc-349)
- [The Activity Lifecycle | CISC 349](#the-activity-lifecycle-cisc-349)
- [Your Second Activity | CISC 349](#your-second-activity-cisc-349)
- [List View | CISC 349](#list-view-cisc-349)
- [Custom ArrayAdapter | CISC 349](#custom-arrayadapter-cisc-349)
- [Network Image View | CISC 349](#network-image-view-cisc-349)
- [Networking HTTP | CISC 349](#networking-http-cisc-349)
- [Code of Ethics | CISC 349](#code-of-ethics-cisc-349)
- [Flask | CISC 349](#flask-cisc-349)
- [MongoDB Code | CISC 349](#mongodb-code-cisc-349)
- [ASSIGNMENTS | CISC 349](#assignments-cisc-349)
- [Fragments | CISC 349](#fragments-cisc-349)
- [Java Introductory Exercise | CISC 349](#java-introductory-exercise-cisc-349)
- [Bottom Navigation Bar in Android | CISC 349](#bottom-navigation-bar-in-android-cisc-349)
- [Upload Images to Server | CISC 349](#upload-images-to-server-cisc-349)
- [Programming Project 02: Dynamic List View | CISC 349](#programming-project-02-dynamic-list-view-cisc-349)
- [Programming Project 03: HUstagram | CISC 349](#programming-project-03-hustagram-cisc-349)
- [Programming Project 04: Machine Learning with TFLite | CISC 349](#programming-project-04-machine-learning-with-tflite-cisc-349)
- [Programming Project 01: Calculator | CISC 349](#programming-project-01-calculator-cisc-349)
- [Project Proposal | CISC 349](#project-proposal-cisc-349)
- [Your First Android Application | CISC 349](#your-first-android-application-cisc-349)
- [Introduction to Java programming | CISC 349](#introduction-to-java-programming-cisc-349)
- [Programming Project 01: Calculator | CISC 349](#programming-project-01-calculator-cisc-349)
- [Project Proposal | CISC 349](#project-proposal-cisc-349)
---
# Initial page | CISC 349
[NextGitHub Instructions](https://developer-mina.gitbook.io/cisc-349/github-instructions)
Last updated 4 years ago
Was this helpful?
---
# GitHub Instructions | CISC 349
[](https://developer-mina.gitbook.io/cisc-349/github-instructions#work-submission)
Work Submission
-------------------------------------------------------------------------------------------------------
In this course, you will be using [https://github.com/](https://github.com/)
to submit your code, your repository should be private, make sure to add me as a contributor so I can check your work, you will find me on Github under this email: `phil@insufficient-light.com`, you will be asked to submit a link to your repository on CANVAS.
To add a contributor you need to go to settings →\\rightarrow→ Manage Access →\\rightarrow→Invite a collaborator
your repository should be called:
Copy
{your first name}_{your last name}_CISC349
The repository folder structure should look like this:
Copy
John_Smith_CISC349/
├─ exercises/
│ ├─ exercises_00
│ ├─ exercises_01
│ ├─ exercises_02
│ ├─ exercises_ ...
│ ├─ exercises_n
├─ projects/
│ ├─ project_01
│ ├─ project_02
│ ├─ project_03
│ ├─ project_04
├─ assignments/
│ ├─ assignment_01
│ ├─ assignment_02
│ ├─ assignment_03
│ ├─ assignment_04
├─ final_project
Copy
│ ├─ exercises_00 ( put any java code for testing)
you will need to use 4 simple commands:
clone your repository
Copy
> git clone {link}
add new files and folder
Copy
> git add .
commit your changes
Copy
> git commit -m "{message}"
push your changes to Github
Copy
> git push
> **If you add, commit and push your assignment to GitHub after the due date and time posted in CANVAS you will be graded according to the late policy in the syllabus.**
**in canvas, you need to submit your repository link, you can find the link here:**

[PreviousInitial page](https://developer-mina.gitbook.io/cisc-349)
[NextIntroduction to Java programming](https://developer-mina.gitbook.io/cisc-349/introduction-to-java/introduction-to-java-programming)
Last updated 2 years ago
Was this helpful?
---
# Introduction to Java programming | CISC 349
[](https://developer-mina.gitbook.io/cisc-349/introduction-to-java/introduction-to-java-programming#ide)
IDE
-----------------------------------------------------------------------------------------------------------------
In this tutorial, I will use [https://repl.it/](https://repl.it/)
as my IDE, and then we will move to Android Studio
[](https://developer-mina.gitbook.io/cisc-349/introduction-to-java/introduction-to-java-programming#write-code)
Write Code
-------------------------------------------------------------------------------------------------------------------------------
when you create a new repl using the Java language you will see the following code:
Copy
class Main {
public static void main(String[] args) {
System.out.println("Hello world!");
}
}
run the previous code you should see "Hello world!" output on the right screen
[](https://developer-mina.gitbook.io/cisc-349/introduction-to-java/introduction-to-java-programming#base-java-language-structure)
Base Java language structure
-------------------------------------------------------------------------------------------------------------------------------------------------------------------
###
[](https://developer-mina.gitbook.io/cisc-349/introduction-to-java/introduction-to-java-programming#class)
Class
A class is a template that describes the data and behavior associated with an instance of that class.
A class is defined by the _class_ keyword and must start with a capital letter. The body of a class is surrounded by {}.
Copy
class MyClass {
}
The data associated with a class is stored in _variables_ the behavior associated with a class or object is implemented with _methods_.
A class is contained in a text file with the same name as the class plus the `.java` extension. It is also possible to define inner classes, these are classes defined within another class, in this case, you do not need a separate file for this class.
###
[](https://developer-mina.gitbook.io/cisc-349/introduction-to-java/introduction-to-java-programming#object)
Object
An object is an instance of a class.
The object is the real element that has data and can perform actions. Each object is created based on the class definition. The class can be seen as the blueprint of an object, i.e., it describes how an object is created.
###
[](https://developer-mina.gitbook.io/cisc-349/introduction-to-java/introduction-to-java-programming#inheritance)
Inheritance
A class can be derived from another class. In this case, this class is called a _subclass_. Another common phrase is that _a class extends another class._
Inheritance is an important pillar of OOP(Object Oriented Programming). It is the mechanism in java by which one class is allowed to inherit the features(fields and methods) of another class.
**Important terminology:**
* **Super Class:** The class whose features are inherited is known as a superclass(or a base class or a parent class).
* **Sub Class:** The class that inherits the other class is known as a subclass(or a derived class, extended class, or child class). The subclass can add its own fields and methods in addition to the superclass fields and methods.
* **Reusability:** Inheritance supports the concept of “reusability”, i.e. when we want to create a new class and there is already a class that includes some of the code that we want, we can derive our new class from the existing class. By doing this, we are reusing the fields and methods of the existing class.
**Example:** In **the** below example of inheritance, class Bicycle is a base class, class MountainBike is a derived class that extends Bicycle class and class Test is a driver class to run the program.
Copy
//Java program to illustrate the
// concept of inheritance
// base class
class Bicycle
{
// the Bicycle class has two fields
public int gear;
public int speed;
// the Bicycle class has one constructor
public Bicycle(int gear, int speed)
{
this.gear = gear;
this.speed = speed;
}
// the Bicycle class has three methods
public void applyBrake(int decrement)
{
speed -= decrement;
}
public void speedUp(int increment)
{
speed += increment;
}
// toString() method to print info of Bicycle
public String toString()
{
return("No of gears are "+gear
+"\n"
+ "speed of bicycle is "+speed);
}
}
// derived class
class MountainBike extends Bicycle
{
// the MountainBike subclass adds one more field
public int seatHeight;
// the MountainBike subclass has one constructor
public MountainBike(int gear,int speed,
int startHeight)
{
// invoking base-class(Bicycle) constructor
super(gear, speed);
seatHeight = startHeight;
}
// the MountainBike subclass adds one more method
public void setHeight(int newValue)
{
seatHeight = newValue;
}
// overriding toString() method
// of Bicycle to print more info
@Override
public String toString()
{
return (super.toString()+
"\nseat height is "+seatHeight);
}
}
// driver class
public class Test
{
public static void main(String args[])
{
MountainBike mb = new MountainBike(3, 100, 25);
System.out.println(mb.toString());
}
}
Copy
No of gears are 3
speed of bicycle is 100
seat height is 25
**How to use inheritance in Java**
The keyword used for inheritance is **extends**
Copy
class derived-class extends base-class
{
//methods and fields
}
**Types of Inheritance in Java**
Below are the different types of inheritance which are supported by Java.
**Single Inheritance:** In single inheritance, subclasses inherit the features of one superclass.
Copy
class one
{
public void print_geek()
{
System.out.println("Geeks");
}
}
class two extends one
{
public void print_for()
{
System.out.println("for");
}
}
// Driver class
public class Main
{
public static void main(String[] args)
{
two g = new two();
g.print_geek();
g.print_for();
g.print_geek();
}
}
Copy
Geeks
for
Geeks
###
[](https://developer-mina.gitbook.io/cisc-349/introduction-to-java/introduction-to-java-programming#java_interfaces)
Java interfaces
####
[](https://developer-mina.gitbook.io/cisc-349/introduction-to-java/introduction-to-java-programming#javadef_interface)
What is an interface in Java?
An _interface_ is a type similar to a class and is defined via the `interface` keyword. Interfaces are used to define the common behavior of implementing classes. If two classes implement the same interface, other code that works on the interface level can use objects of both classes.
Like a class an interface defines methods. Classes can implement one or several interfaces. A class that implements an interface must provide an implementation for all abstract methods defined in the interface.
Copy
public interface MyInterface {
// constant definition
String URL = "https://www.vogella.com/";
// public abstract methods
void test();
void write(String s);
// default method
default String reserveString(String s){
return new StringBuilder(s).reverse().toString();
}
}
####
[](https://developer-mina.gitbook.io/cisc-349/introduction-to-java/introduction-to-java-programming#javadef_interfaceimplementing)
Implementing Interfaces
Copy
public class MyClassImpl implements MyInterface {
@Override
public void test() {
}
@Override
public void write(String s) {
}
public static void main(String[] args) {
MyClassImpl impl = new MyClassImpl();
System.out.println(impl.reserveString("Lars Vogel"));
}
}
####
[](https://developer-mina.gitbook.io/cisc-349/introduction-to-java/introduction-to-java-programming#reference)
Reference:
[Inheritance in Java - GeeksforGeeksGeeksforGeeks](https://www.geeksforgeeks.org/inheritance-in-java/)
[Introduction to Java programming - Tutorialwww.vogella.com](https://www.vogella.com/tutorials/JavaIntroduction/article.html)
[PreviousGitHub Instructions](https://developer-mina.gitbook.io/cisc-349/github-instructions)
[NextYour First Android Application](https://developer-mina.gitbook.io/cisc-349/android-programming/your-first-android-application)
Last updated 4 years ago
Was this helpful?
---
# Your First Android Application | CISC 349
The application you are going to create is called GeoQuiz. GeoQuiz tests the user’s knowledge of geography. The user presses TRUE or FALSE to answer the question on screen, and GeoQuiz provides instant feedback.

[](https://developer-mina.gitbook.io/cisc-349/android-programming/your-first-android-application#app-basics)
App Basics
----------------------------------------------------------------------------------------------------------------------------
Your GeoQuiz application will consist of an activity and a layout:
* An activity is an instance of Activity, a class in the Android SDK. An activity is responsible for managing user interaction with a screen of information.
* A layout defines a set of UI objects and their positions on the screen. A layout is made up of definitions written in XML.
The relationship between QuizActivity and activity\_quiz.xml is diagrammed in the figure below

[](https://developer-mina.gitbook.io/cisc-349/android-programming/your-first-android-application#creating-an-android-project)
Creating an Android Project
--------------------------------------------------------------------------------------------------------------------------------------------------------------
The first step is to create an Android project. An Android project contains the files that make up an application. To create a new project, first open Android Studio.

Creating a new application

Specifying device support

Choosing a type of activity _If your wizard looks very different, then the tools have changed more drastically. Do not panic._

[](https://developer-mina.gitbook.io/cisc-349/android-programming/your-first-android-application#navigating-in-android-studio)
Navigating in Android Studio
----------------------------------------------------------------------------------------------------------------------------------------------------------------
The lefthand view is the project tool window. From here, you can view and manage the files associated with your project.

[](https://developer-mina.gitbook.io/cisc-349/android-programming/your-first-android-application#laying-out-the-ui)
Laying Out the UI
------------------------------------------------------------------------------------------------------------------------------------------
Copy
Widgets are the building blocks you use to compose a UI. A widget can show text or graphics, interact with the user, or arrange other widgets on the screen. Buttons, text input controls, and checkboxes are all types of widgets. The Android SDK includes many widgets that you can configure to get the appearance and behavior you want. Every widget is an instance of the View class or one of its subclasses (such as TextView or Button).
But these are not the widgets you are looking for. The interface for QuizActivity requires five widgets:
* a vertical LinearLayout
* a TextView
* a horizontal LinearLayout
* two Buttons

Copy
[](https://developer-mina.gitbook.io/cisc-349/android-programming/your-first-android-application#the-view-hierarchy)
The view hierarchy
--------------------------------------------------------------------------------------------------------------------------------------------

[](https://developer-mina.gitbook.io/cisc-349/android-programming/your-first-android-application#widget-attributes)
Widget attributes
------------------------------------------------------------------------------------------------------------------------------------------
###
[](https://developer-mina.gitbook.io/cisc-349/android-programming/your-first-android-application#android-layout_width-and-android-layout_height)
android:layout\_width and android:layout\_height
The android:layout\_width and android:layout\_height attributes are required for almost every type of widget. They are typically set to either match\_parent or wrap\_content:
Attribute
Description
match\_parent
view will be as big as its parent
wrap\_content
view will be as big as its contents require
###
[](https://developer-mina.gitbook.io/cisc-349/android-programming/your-first-android-application#android-orientation)
android:orientation
The android:orientation attribute on the two LinearLayout widgets determines whether their children will appear vertically or horizontally. The root LinearLayout is vertical; its child LinearLayout is horizontal.
###
[](https://developer-mina.gitbook.io/cisc-349/android-programming/your-first-android-application#android-text)
android:text
The TextView and Button widgets have android:text attributes. This attribute tells the widget what text to display.
[](https://developer-mina.gitbook.io/cisc-349/android-programming/your-first-android-application#creating-string-resources)
Creating string resources
----------------------------------------------------------------------------------------------------------------------------------------------------------
Open res/values/strings.xml. The template has already added one string resource for you. Add the three new strings that your layout requires.
Copy
GeoQuizCanberra is the capital of Australia.TrueFalse
[](https://developer-mina.gitbook.io/cisc-349/android-programming/your-first-android-application#previewing-the-layout)
Previewing the layout
--------------------------------------------------------------------------------------------------------------------------------------------------
Your layout is now complete, and you can preview the layout in the graphical layout tool.

[](https://developer-mina.gitbook.io/cisc-349/android-programming/your-first-android-application#from-layout-xml-to-view-objects)
From Layout XML to View Objects
----------------------------------------------------------------------------------------------------------------------------------------------------------------------
When you created the GeoQuiz project, a subclass of Activity named QuizActivity was created for you. The class file for QuizActivity is in the app/java directory of your project. The java directory is where the Java code for your project lives.
Copy
package com.bignerdranch.android.geoquiz;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
public class QuizActivity extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_quiz);
}
}
_Wondering what AppCompatActivity is? It is a subclass of Android’s Activity class that provides compatibility support for older versions of Android. You will learn much more about AppCompatActivity in Chapter 13_
The onCreate(Bundle) method is called when an instance of the activity subclass is created. When an activity is created, it needs a UI to manage. To get the activity its UI, you call the following Activity method:
Copy
public void setContentView(int layoutResID)
This method inflates a layout and puts it on screen.
[](https://developer-mina.gitbook.io/cisc-349/android-programming/your-first-android-application#resources-and-resource-ids)
Resources and resource IDs
------------------------------------------------------------------------------------------------------------------------------------------------------------
A layout is a resource. A resource is a piece of your application that is not code – things like image files, audio files, and XML files.
To access a resource in code, you use its resource ID. The resource ID for your layout is R.layout.activity\_quiz.
To generate a resource ID for a widget, you include an android:id attribute in the widget’s definition. In activity\_quiz.xml, add an android:id attribute to each button.
Copy
[](https://developer-mina.gitbook.io/cisc-349/android-programming/your-first-android-application#wiring-up-widgets)
Wiring Up Widgets
------------------------------------------------------------------------------------------------------------------------------------------
Now that the buttons have resource IDs, you can access them in QuizActivity. The first step is to add two member variables.
Copy
public class QuizActivity extends AppCompatActivity {
private Button mTrueButton;
private Button mFalseButton;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_quiz);
}
}
[](https://developer-mina.gitbook.io/cisc-349/android-programming/your-first-android-application#getting-references-to-widgets)
Getting references to widgets
------------------------------------------------------------------------------------------------------------------------------------------------------------------
In an activity, you can get a reference to an inflated widget by calling the following Activity method:
Copy
public View findViewById(int id)
This method accepts a resource ID of a widget and returns a View object.
Copy
public class QuizActivity extends AppCompatActivity {
private Button mTrueButton;
private Button mFalseButton;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_quiz);
mTrueButton = (Button) findViewById(R.id.true_button);
mFalseButton = (Button) findViewById(R.id.false_button);
}
}
[](https://developer-mina.gitbook.io/cisc-349/android-programming/your-first-android-application#setting-listeners)
Setting listeners
------------------------------------------------------------------------------------------------------------------------------------------
Android applications are typically event driven. Unlike command-line programs or scripts, event driven applications start and then wait for an event, such as the user pressing a button.
Start with the TRUE button. In QuizActivity.java, add the following code to onCreate(Bundle) just after the variable assignment.
Copy
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_quiz);
mTrueButton = (Button) findViewById(R.id.true_button);
mTrueButton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
// Does nothing yet, but soon!
}
});
mFalseButton = (Button) findViewById(R.id.false_button);
}
}
Set a similar listener for the FALSE button.
Copy
mTrueButton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
// Does nothing yet, but soon!
}
});
mFalseButton = (Button) findViewById(R.id.false_button);
mFalseButton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
// Does nothing yet, but soon!
}
});
}
[](https://developer-mina.gitbook.io/cisc-349/android-programming/your-first-android-application#making-toasts)
Making Toasts
----------------------------------------------------------------------------------------------------------------------------------
Now to make the buttons fully armed and operational. You are going to have a press of each button trigger a pop-up message called a toast. A toast is a short message that informs the user of something but does not require any input or action.

First, return to strings.xml and add the string resources that your toasts will display.
Copy
GeoQuizCanberra is the capital of Australia.TrueFalseCorrect!Incorrect!
Copy
mTrueButton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Toast.makeText(QuizActivity.this,
R.string.correct_toast,
Toast.LENGTH_SHORT).show();
}
});
mFalseButton = (Button) findViewById(R.id.false_button);
mFalseButton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Toast.makeText(QuizActivity.this,
R.string.incorrect_toast,
Toast.LENGTH_SHORT).show();
}
});
[](https://developer-mina.gitbook.io/cisc-349/android-programming/your-first-android-application#challenge-customizing-the-toast)
Challenge: Customizing the Toast
-----------------------------------------------------------------------------------------------------------------------------------------------------------------------
In this challenge, you will customize the toast to show at the top instead of the bottom of the screen. To change how the toast is displayed, use the Toast class’s setGravity method.
[PreviousIntroduction to Java programming](https://developer-mina.gitbook.io/cisc-349/introduction-to-java/introduction-to-java-programming)
[NextAndroid and Model-View-Controller](https://developer-mina.gitbook.io/cisc-349/android-programming/android-and-model-view-controller)
Last updated 4 years ago
Was this helpful?
---
# Android and Model-View-Controller | CISC 349
In this chapter, you are going to upgrade GeoQuiz to present more than one question

To make this happen, you are going to add a class named Question to the GeoQuiz project. An instance of this class will encapsulate a single true-false question.
Then, you will create an array of Question objects for QuizActivity to manage.
[](https://developer-mina.gitbook.io/cisc-349/android-programming/android-and-model-view-controller#creating-a-new-class)
Creating a New Class
---------------------------------------------------------------------------------------------------------------------------------------------------
In the project tool window, right-click the com.bignerdranch.android.geoquiz package and select New → Java Class. Name the class Question and click OK

Copy
public class Question {
private int mTextResId;
private boolean mAnswerTrue;
public Question(int textResId, boolean answerTrue) {
mTextResId = textResId;
mAnswerTrue = answerTrue;
}
}
The Question class holds two pieces of data: the question text and the question answer (true or false).
These variables need getter and setter methods. Rather than typing them in yourself, you can have Android Studio generate the implementations for you.
[](https://developer-mina.gitbook.io/cisc-349/android-programming/android-and-model-view-controller#generating-getters-and-setters)
Generating getters and setters
-----------------------------------------------------------------------------------------------------------------------------------------------------------------------
Copy
public class Question {
private int mTextResId;
private boolean mAnswerTrue;
...
public int getTextResId() {
return mTextResId;
}
public void setTextResId(int textResId) {
mTextResId = textResId;
}
public boolean isAnswerTrue() {
return mAnswerTrue;
}
public void setAnswerTrue(boolean answerTrue) {
mAnswerTrue = answerTrue;
}
}
###
[](https://developer-mina.gitbook.io/cisc-349/android-programming/android-and-model-view-controller#object-diagram-for-geoquiz)
Object diagram for GeoQuiz

[](https://developer-mina.gitbook.io/cisc-349/android-programming/android-and-model-view-controller#model-view-controller-and-android)
Model-View-Controller and Android
-----------------------------------------------------------------------------------------------------------------------------------------------------------------------------
* A model object holds the application’s data and “business logic.”
* View objects know how to draw themselves on the screen and how to respond to user input, like touches. A simple rule of thumb is that if you can see it on screen, then it is a view.
* Controller objects tie the view and model objects together. They contain “application logic.” Controllers are designed to respond to various events triggered by view objects and to manage the flow of data to and from model objects and the view layer.
###
[](https://developer-mina.gitbook.io/cisc-349/android-programming/android-and-model-view-controller#mvc-flow-with-user-input)
MVC flow with user input

[](https://developer-mina.gitbook.io/cisc-349/android-programming/android-and-model-view-controller#updating-the-view-layer)
Updating the View Layer
---------------------------------------------------------------------------------------------------------------------------------------------------------
Now that you have been introduced to MVC, you are going to update GeoQuiz’s view layer to include a NEXT button.

So the changes you need to make to the view layer are:
* Remove the android:text attribute from the TextView. You no longer want a hardcoded question to be part of its definition.
* Give the TextView an android:id attribute. This widget will need a resource ID so that you can set its text in QuizActivity’s code.
* Add the new Button widget as a child of the root LinearLayout.
####
[](https://developer-mina.gitbook.io/cisc-349/android-programming/android-and-model-view-controller#new-button...-and-changes-to-the-text-view)
New button... and changes to the text view
Copy
...
Return to res/values/strings.xml. Rename question\_text and add a string for the new button.
Copy
GeoQuizCanberra is the capital of Australia.TrueFalseNextCorrect!
While you have strings.xml open, go ahead and add the strings for the rest of the geography questions that will be shown to the user.
Copy
Canberra is the capital of Australia.The Pacific Ocean is larger than
the Atlantic Ocean.The Suez Canal connects the Red Sea
and the Indian Ocean.The source of the Nile River is in Egypt.The Amazon River is the longest river
in the Americas.Lake Baikal is the world\'s oldest and deepest
freshwater lake.
...
Notice that you use the escape sequence \\' in the last value to get an apostrophe in your string.
[](https://developer-mina.gitbook.io/cisc-349/android-programming/android-and-model-view-controller#updating-the-controller-layer)
Updating the Controller Layer
---------------------------------------------------------------------------------------------------------------------------------------------------------------------
Open QuizActivity.java. Add variables for the TextView and the new Button. Also, create an array of Question objects and an index for the array.
####
[](https://developer-mina.gitbook.io/cisc-349/android-programming/android-and-model-view-controller#adding-variables-and-a-question-array)
Adding variables and a Question array
Copy
private Button mTrueButton;
private Button mFalseButton;
private Button mNextButton;
private TextView mQuestionTextView;
private Question[] mQuestionBank = new Question[] {
new Question(R.string.question_australia, true),
new Question(R.string.question_oceans, true),
new Question(R.string.question_mideast, false),
new Question(R.string.question_africa, false),
new Question(R.string.question_americas, true),
new Question(R.string.question_asia, true),
};
private int mCurrentIndex = 0;
...
###
[](https://developer-mina.gitbook.io/cisc-349/android-programming/android-and-model-view-controller#wiring-up-the-textview)
Wiring up the TextView
Copy
public class QuizActivity extends AppCompatActivity {
...
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_quiz);
mQuestionTextView = (TextView) findViewById(R.id.question_text_view);
int question = mQuestionBank[mCurrentIndex].getTextResId();
mQuestionTextView.setText(question);
mTrueButton = (Button) findViewById(R.id.true_button);
...
}
}
###
[](https://developer-mina.gitbook.io/cisc-349/android-programming/android-and-model-view-controller#wiring-up-the-new-button)
Wiring up the new button
Copy
public class QuizActivity extends AppCompatActivity {
...
@Override
protected void onCreate(Bundle savedInstanceState) {
...
mFalseButton.setOnClickListener(new View.OnClickListener() {
...
}
});
mNextButton = (Button) findViewById(R.id.next_button);
mNextButton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
mCurrentIndex = (mCurrentIndex + 1) % mQuestionBank.length;
int question = mQuestionBank[mCurrentIndex].getTextResId();
mQuestionTextView.setText(question);
}
});
}
}
###
[](https://developer-mina.gitbook.io/cisc-349/android-programming/android-and-model-view-controller#encapsulating-with-updatequestion)
Encapsulating with updateQuestion()
Copy
public class QuizActivity extends AppCompatActivity {
...
@Override
protected void onCreate(Bundle savedInstanceState) {
...
mQuestionTextView = (TextView) findViewById(R.id.question_text_view);
int question = mQuestionBank[mCurrentIndex].getTextResId();
mQuestionTextView.setText(question);
...
mNextButton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
mCurrentIndex = (mCurrentIndex + 1) % mQuestionBank.length;
int question = mQuestionBank[mCurrentIndex].getTextResId();
mQuestionTextView.setText(question);
updateQuestion();
}
});
updateQuestion();
}
private void updateQuestion() {
int question = mQuestionBank[mCurrentIndex].getTextResId();
mQuestionTextView.setText(question);
}
}
Run GeoQuiz and test your new NEXT button
Now that you have the questions behaving appropriately, it is time to turn to the answers. At the moment, GeoQuiz thinks that the answer to every question is “true.” Let’s rectify that. Here again, you will implement a private method to encapsulate code rather than writing similar code in two places.
The method that you are going to add to QuizActivity is:
Copy
private void checkAnswer(boolean userPressedTrue)
###
[](https://developer-mina.gitbook.io/cisc-349/android-programming/android-and-model-view-controller#adding-checkanswer-boolean)
Adding checkAnswer(boolean)
Copy
public class QuizActivity extends AppCompatActivity {
...
@Override
protected void onCreate(Bundle savedInstanceState) {
...
}
private void updateQuestion() {
int question = mQuestionBank[mCurrentIndex].getTextResId();
mQuestionTextView.setText(question);
}
private void checkAnswer(boolean userPressedTrue) {
boolean answerIsTrue = mQuestionBank[mCurrentIndex].isAnswerTrue();
int messageResId = 0;
if (userPressedTrue == answerIsTrue) {
messageResId = R.string.correct_toast;
} else {
messageResId = R.string.incorrect_toast;
}
Toast.makeText(this, messageResId, Toast.LENGTH_SHORT)
.show();
}
}
###
[](https://developer-mina.gitbook.io/cisc-349/android-programming/android-and-model-view-controller#calling-checkanswer-boolean)
Calling checkAnswer(boolean)
Copy
public class QuizActivity extends AppCompatActivity {
...
@Override
protected void onCreate(Bundle savedInstanceState) {
...
mTrueButton = (Button) findViewById(R.id.true_button);
mTrueButton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
checkAnswer(true);
}
});
mFalseButton = (Button) findViewById(R.id.false_button);
mFalseButton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
checkAnswer(false);
}
});
...
}
...
}
[](https://developer-mina.gitbook.io/cisc-349/android-programming/android-and-model-view-controller#challenge)
Challenge
-----------------------------------------------------------------------------------------------------------------------------
###
[](https://developer-mina.gitbook.io/cisc-349/android-programming/android-and-model-view-controller#adding-an-icon)
Adding an Icon
Add Next and Previous Icons instead of text, some information you will need to know are:
The suffixes on these directory names refer to the screen pixel density of a device:
Suffixes
Description
mdpi
medium-density screens (~160dpi)
hdpi
high-density screens (~240dpi)
xhdpi
extra-high-density screens (~320dpi)
xxhdpi
extra-extra-high-density screens (~480dpi)
####
[](https://developer-mina.gitbook.io/cisc-349/android-programming/android-and-model-view-controller#adding-an-icon-to-the-next-button)
Adding an icon to the NEXT button
Copy
...
...
[PreviousYour First Android Application](https://developer-mina.gitbook.io/cisc-349/android-programming/your-first-android-application)
[NextThe Activity Lifecycle](https://developer-mina.gitbook.io/cisc-349/android-programming/the-activity-lifecycle)
Last updated 4 years ago
Was this helpful?
---
# The Activity Lifecycle | CISC 349
Every instance of Activity has a lifecycle. During this lifecycle, an activity transitions between three states: running, paused, and stopped. For each transition, there is an Activity method that notifies the activity of the change in its state.
[Understand the Activity Lifecycle](https://developer.android.com/guide/components/activities/activity-lifecycle)

You are already acquainted with one of these methods – onCreate(Bundle). The OS calls this method after the activity instance is created but before it is put on screen.
Typically, an activity overrides onCreate(...) to prepare the specifics of its user interface:
* inflating widgets and putting them on screen (in the call to (setContentView(int))
* getting references to inflated widgets
* setting listeners on widgets to handle user interaction
* connecting to external model data
It is important to understand that you never call onCreate(...) or any of the other Activity lifecycle methods yourself. You override them in your activity subclasses, and Android calls them at the appropriate time.
[](https://developer-mina.gitbook.io/cisc-349/android-programming/the-activity-lifecycle#logging-the-activity-lifecycle)
Logging the Activity Lifecycle
------------------------------------------------------------------------------------------------------------------------------------------------------------
In this section, you are going to override lifecycle methods to eavesdrop on QuizActivity’s lifecycle. Each implementation will simply log a message informing you that the method has been called.
**Making log messages**
In Android, the android.util.Log class sends log messages to a shared system-level log. Log has several methods for logging messages. Here is the one that you will use most often in this book:
Copy
public static int d(String tag, String msg)
The **d** stands for “debug” and refers to the level of the log message, Adding log statement to **onCreate(…)**
Copy
public class QuizActivity extends AppCompatActivity {
...
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
Log.d(TAG, "onCreate(Bundle) called");
setContentView(R.layout.activity_quiz);
...
}
}
Overriding more lifecycle methods:
Copy
private void updateQuestion(){
int question = mQuestionBank[mCurrentIndex].getmTextResId();
mQuestionTextView.setText(question);
}
@Override
public void onStart() {
super.onStart();
Log.d(TAG, "onStart() called");
}
@Override
public void onPause() {
super.onPause();
Log.d(TAG, "onPause() called");
}
@Override
public void onResume() {
super.onResume();
Log.d(TAG, "onResume() called");
}
@Override
public void onStop() {
super.onStop();
Log.d(TAG, "onStop() called");
}
@Override
public void onDestroy() {
super.onDestroy();
Log.d(TAG, "onDestroy() called");
}
...
}
You may have been wondering about the **@Override annotation**. This asks the compiler to ensure that the class actually has the method that you are attempting to override. For example, the compiler would be able to alert you to the following misspelled method name:
Copy
public class QuizActivity extends AppCompatActivity {
@Override
public void onCreat(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_quiz);
}
...
[](https://developer-mina.gitbook.io/cisc-349/android-programming/the-activity-lifecycle#device-configurations-and-alternative-resources)
Device configurations and alternative resources
----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
Rotating the device changes the device configuration. The device configuration is a set of characteristics that describe the current state of an individual device. The characteristics that make up the configuration include screen orientation, screen density, screen size, keyboard type, dock mode, language, and more.
[](https://developer-mina.gitbook.io/cisc-349/android-programming/the-activity-lifecycle#an-alternative-landscape-layout)
An alternative landscape layout
--------------------------------------------------------------------------------------------------------------------------------------------------------------

The **FrameLayout** will replace the **LinearLayout**. **FrameLayout** is the simplest **ViewGroup** and does not arrange its children in any particular manner. In this layout, child views will be arranged according to their android:layout\_gravity attributes.
The **TextView, LinearLayout,** and **Button** children of the FrameLayout need android:layout\_gravity attributes. The **Button** children of the **LinearLayout** will stay exactly the same.
Copy

Note that Android destroys the current activity and creates a new one whenever any runtime configuration change occurs.
[](https://developer-mina.gitbook.io/cisc-349/android-programming/the-activity-lifecycle#saving-data-across-rotation)
Saving Data Across Rotation
------------------------------------------------------------------------------------------------------------------------------------------------------
Android does a great job of providing alternative resources at the right time. However, destroying and re-creating activities on rotation can cause headaches, too, like GeoQuiz’s bug of reverting back to the first question when the device is rotated.
To fix this bug, the post-rotation QuizActivity needs to know the old value of **mCurrentIndex**. You need a way to save this data across a runtime configuration change, like rotation. One way to do this is to override the **Activity** method:
Copy
protected void onSaveInstanceState(Bundle outState)
This method is normally called by the system before **onPause(), onStop(),** and **onDestroy().**
The default implementation of **onSaveInstanceState(…)** directs all of the activity’s views to save their state as data in the **Bundle** object. A **Bundle** is a structure that maps string keys to values of certain limited types.
You have seen this **Bundle** before. It is passed into **onCreate(Bundle):**
Copy
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
...
}
When you override **onCreate(…)**, you call **onCreate(…)** on the activity’s superclass and pass in the bundle you just received. In the superclass implementation, the saved state of the views is retrieved and used to re-create the activity’s view hierarchy.
[](https://developer-mina.gitbook.io/cisc-349/android-programming/the-activity-lifecycle#overriding-onsaveinstancestate-bundle)
Overriding onSaveInstanceState(Bundle)
---------------------------------------------------------------------------------------------------------------------------------------------------------------------------
add a constant that will be the key for the key-value pair that will be stored in the bundle.
Copy
public class QuizActivity extends AppCompatActivity {
private static final String TAG = "QuizActivity";
private static final String KEY_INDEX = "index";
private Button mTrueButton;
...
Next, override onSaveInstanceState(…) to write the value of **mCurrentIndex** to the bundle with the constant as its key.
Copy
mNextButton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
mCurrentIndex = (mCurrentIndex + 1) % mQuestionBank.length;
updateQuestion();
}
});
updateQuestion();
}
@Override
public void onSaveInstanceState(Bundle savedInstanceState) {
super.onSaveInstanceState(savedInstanceState);
Log.i(TAG, "onSaveInstanceState");
savedInstanceState.putInt(KEY_INDEX, mCurrentIndex);
}
Finally, in **onCreate(…)**, check for this value. If it exists, assign it to mCurrentIndex.
Copy
...
if (savedInstanceState != null) {
mCurrentIndex = savedInstanceState.getInt(KEY_INDEX, 0);
}
updateQuestion();
}
[getint](https://developer.android.com/reference/android/os/BaseBundle.html#getInt(java.lang.String,%20int))
Returns the value associated with the given key, or defaultValue if no mapping of the desired type exists for the given key.

Run GeoQuiz and press Next. No matter how many device rotations you perform, the newly minted QuizActivity will “remember” what question you were on.
[](https://developer-mina.gitbook.io/cisc-349/android-programming/the-activity-lifecycle#the-activity-lifecycle-revisited)
The Activity Lifecycle, Revisited
-----------------------------------------------------------------------------------------------------------------------------------------------------------------
Overriding **onSaveInstanceState(Bundle)** is not just for handling rotation. An activity can also be destroyed if the user navigates away for a while and Android needs to reclaim memory.
Android will never destroy a running activity to reclaim memory.
When **onSaveInstanceState(…)** is called, the data is saved to the **Bundle** object. That **Bundle** object is then stuffed into your activity’s activity record by the OS.
[PreviousAndroid and Model-View-Controller](https://developer-mina.gitbook.io/cisc-349/android-programming/android-and-model-view-controller)
[NextYour Second Activity](https://developer-mina.gitbook.io/cisc-349/android-programming/your-second-activity)
Last updated 4 years ago
Was this helpful?
---
# Your Second Activity | CISC 349
**CheatActivity** offers the chance to peek at the answer

If the user chooses to view the answer and then returns to the QuizActivity and answers the question, he or she will get a new message.
**QuizActivity** knows if you’ve been cheating

Why is this a good Android programming exercise? You will learn how to:
* Create a new activity and a new layout for it.
* Start an activity from another activity. Starting an activity means asking the OS to create an activity instance and call its **onCreate(Bundle)** method.
* Pass data between the parent (starting) activity and the child (started) activity.
[](https://developer-mina.gitbook.io/cisc-349/android-programming/your-second-activity#setting-up-a-second-activity)
Setting Up a Second Activity
------------------------------------------------------------------------------------------------------------------------------------------------------
But before you invoke the magic, open **strings.xml** and add all the strings you will need for this chapter.
Copy
...
Lake Baikal is the world\'s oldest and deepest
freshwater lake.Are you sure you want to do this?Show AnswerCheat!Cheating is wrong.
[](https://developer-mina.gitbook.io/cisc-349/android-programming/your-second-activity#creating-a-new-activity)
Creating a new activity
--------------------------------------------------------------------------------------------------------------------------------------------
Creating an activity typically involves touching at least three files: the Java class file, an XML layout, and the application manifest. If you touch those files in the wrong ways, Android can get mad. To ensure that you do it right, you should use Android Studio’s New Activity wizard.

Set Activity Name to **CheatActivity**. This is the name of your Activity subclass. Layout Name should be automatically set to **activity\_cheat**. This will be the base name of the layout file the wizard creates. Title will be set to “**CheatActivity**” for you, but since this is a string the user will see, change it to simply “Cheat”.
**The New Blank Activity wizard**

Diagram of layout for CheatActivity

Copy
[](https://developer-mina.gitbook.io/cisc-349/android-programming/your-second-activity#a-new-activity-subclass)
A new activity subclass
--------------------------------------------------------------------------------------------------------------------------------------------
In the Project tool window, find the _com.bignerdranch.android.geoquiz_ Java package and open the CheatActivity class, which is in the CheatActivity.java file.
[](https://developer-mina.gitbook.io/cisc-349/android-programming/your-second-activity#declaring-activities-in-the-manifest)
Declaring activities in the manifest
----------------------------------------------------------------------------------------------------------------------------------------------------------------------
The manifest is an _XML_ file containing metadata that describes your application to the Android OS. The file is always named AndroidManifest.xml, and it lives in the app/manifests directory of your project.
Copy
[](https://developer-mina.gitbook.io/cisc-349/android-programming/your-second-activity#adding-a-cheat-button-to-quizactivity)
Adding a Cheat! button to QuizActivity
-------------------------------------------------------------------------------------------------------------------------------------------------------------------------
The plan is for the user to press a button in QuizActivity to get an instance of CheatActivity on screen. So you need new buttons in layout/activity\_quiz.xml and layout-land/ activity\_quiz.xml.
Copy
In the landscape layout, have the new button appear at the bottom and center of the root FrameLayout.
Copy
...
**Wiring up the Cheat! button (QuizActivity.java)**
Copy
public class QuizActivity extends AppCompatActivity {
...
private Button mNextButton;
private Button mCheatButton;
...
@Override
protected void onCreate(Bundle savedInstanceState) {
...
mCheatButton = (Button)findViewById(R.id.cheat_button);
mCheatButton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
// Start CheatActivity
}
});
if (savedInstanceState != null) {
mCurrentIndex = savedInstanceState.getInt(KEY_INDEX, 0);
}
updateQuestion();
}
...
[](https://developer-mina.gitbook.io/cisc-349/android-programming/your-second-activity#starting-an-activity)
Starting an Activity
--------------------------------------------------------------------------------------------------------------------------------------
The simplest way one activity can start another is with the Activity method:
Copy
public void startActivity(Intent intent)
You might guess that **startActivity(…)** is a static method that you call on the Activity subclass that you want to start. But it is not. When an activity calls **startActivity(…)**, this call is sent to the OS.
**Starting an activity**

How does the **ActivityManager** know which **Activity** to start? That information is in the **Intent** parameter.
[](https://developer-mina.gitbook.io/cisc-349/android-programming/your-second-activity#communicating-with-intents)
Communicating with intents
--------------------------------------------------------------------------------------------------------------------------------------------------
An intent is an object that a component can use to communicate with the OS. The only components you have seen so far are activities, but there are also services, broadcast receivers, and content providers.
Intents are multi-purpose communication tools, and the **Intent** class provides different constructors depending on what you are using the intent to do.
In this case, you are using an intent to tell the **ActivityManager** which activity to start, so you will use this constructor:
Copy
public Intent(Context packageContext, Class> cls)
The intent: telling **ActivityManager** what to do

Starting **CheatActivity** (QuizActivity.java)
[](https://developer-mina.gitbook.io/cisc-349/android-programming/your-second-activity#starting-cheatactivity-quizactivity.java)
Starting CheatActivity (QuizActivity.java)
--------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
Copy
...
mCheatButton = (Button)findViewById(R.id.cheat_button);
mCheatButton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
// Start CheatActivity
Intent i = new Intent(QuizActivity.this, CheatActivity.class);
startActivity(i);
}
});
...
[](https://developer-mina.gitbook.io/cisc-349/android-programming/your-second-activity#explicit-and-implicit-intents)
Explicit and implicit intents
--------------------------------------------------------------------------------------------------------------------------------------------------------
When you create an **Intent** with a **Context** and a **Class** object, you are creating an explicit intent. You use explicit intents to start activities within your application.
It may seem strange that two activities within your application must communicate via the **ActivityManager**, which is outside of your application. However, this pattern makes it easy for an activity in one application to work with an activity in another application.
[](https://developer-mina.gitbook.io/cisc-349/android-programming/your-second-activity#passing-data-between-activities)
Passing Data Between Activities
------------------------------------------------------------------------------------------------------------------------------------------------------------
Now that you have a QuizActivity and a CheatActivity, you can think about passing data between them.
**The conversation between QuizActivity and CheatActivity**

The **QuizActivity** will inform the **CheatActivity** of the answer to the current question when the CheatActivity is started.
When the user presses the Back button to return to the **QuizActivity**, the **CheatActivity** will be destroyed. In its last gasp, it will send data to the **QuizActivity** about whether the user cheated.
###
[](https://developer-mina.gitbook.io/cisc-349/android-programming/your-second-activity#using-intent-extras)
Using intent extras
To inform the CheatActivity of the answer to the current question, you will pass it the value of
Copy
mQuestionBank[mCurrentIndex].isAnswerTrue()
You will send this value as an extra on the **Intent** that is passed into **startActivity(Intent).**
**Intent extras: communicating with other activities**

An extra is structured as a key-value pair, like the one you used to save out the value of mCurrentIndex in **QuizActivity.onSaveInstanceState(Bundle).**
To add an extra to an intent, you use Intent.putExtra(…). In particular, you will be calling
Copy
public Intent putExtra(String name, boolean value)
**Intent.putExtra(…)** comes in many flavors, but it always has two arguments. The first argument is always a **String** key, and the second argument is the value, whose type will vary. It returns the **Intent** itself, so you can chain multiple calls if you need to
###
[](https://developer-mina.gitbook.io/cisc-349/android-programming/your-second-activity#adding-extra-constant-cheatactivity.java)
Adding extra constant (CheatActivity.java)
Copy
public class CheatActivity extends AppCompatActivity {
private static final String EXTRA_ANSWER_IS_TRUE =
"com.bignerdranch.android.geoquiz.answer_is_true";
...
An activity may be started from several different places, so you should define keys for extras on the activities that retrieve and use them. Using your package name as a qualifier for your extra, as shown, prevents name collisions with extras from other apps.
###
[](https://developer-mina.gitbook.io/cisc-349/android-programming/your-second-activity#a-newintent-...-method-for-cheatactivity-cheatactivity.java)
A newIntent(…) method for CheatActivity (CheatActivity.java)
Copy
public class CheatActivity extends AppCompatActivity {
private static final String EXTRA_ANSWER_IS_TRUE =
"com.bignerdranch.android.geoquiz.answer_is_true";
public static Intent newIntent(Context packageContext, boolean answerIsTrue) {
Intent i = new Intent(packageContext, CheatActivity.class);
i.putExtra(EXTRA_ANSWER_IS_TRUE, answerIsTrue);
return i;
}
...
###
[](https://developer-mina.gitbook.io/cisc-349/android-programming/your-second-activity#using-an-extra-cheatactivity.java)
Using an extra (CheatActivity.java)
Copy
public class CheatActivity extends AppCompatActivity {
private static final String EXTRA_ANSWER_IS_TRUE =
"com.bignerdranch.android.geoquiz.answer_is_true";
private boolean mAnswerIsTrue;
...
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_cheat);
mAnswerIsTrue = getIntent().getBooleanExtra(EXTRA_ANSWER_IS_TRUE, false);
}
...
}
###
[](https://developer-mina.gitbook.io/cisc-349/android-programming/your-second-activity#enabling-cheating-cheatactivity.java)
Enabling cheating (CheatActivity.java)
Copy
public class CheatActivity extends AppCompatActivity {
...
private boolean mAnswerIsTrue;
private TextView mAnswerTextView;
private Button mShowAnswer;
...
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_cheat);
mAnswerIsTrue = getIntent().getBooleanExtra(EXTRA_ANSWER_IS_TRUE, false);
mAnswerTextView = (TextView) findViewById(R.id.answer_text_view);
mShowAnswer = (Button) findViewById(R.id.show_answer_button);
mShowAnswer.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
if (mAnswerIsTrue) {
mAnswerTextView.setText(R.string.true_button);
} else {
mAnswerTextView.setText(R.string.false_button);
}
}
});
}
}
###
[](https://developer-mina.gitbook.io/cisc-349/android-programming/your-second-activity#full-example)
Full Example
This goes in the MainActivity should be a unique message ID
Copy
public static final String EXTRA_MESSAGE = "com.example.geoquiz.MESSAGE";
in click event to go to the new activity
Copy
mCheatButton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Logger.w("Cheat Button Clicked");
Intent i = new Intent(MainActivity.this, CheatActivty.class);
String message = "Hello from MainActivity";
i.putExtra(EXTRA_MESSAGE, message);
startActivity(i);
}
get the message in the new activity
Copy
public class CheatActivty extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_cheat_activty);
Logger.addLogAdapter(new AndroidLogAdapter());
Intent i = getIntent();
String message = getIntent().getStringExtra(MainActivity.EXTRA_MESSAGE);
Logger.d(message);
}
}
###
[](https://developer-mina.gitbook.io/cisc-349/android-programming/your-second-activity#getting-a-result-back-from-a-child-activity)
Getting a result back from a child activity
At this point, the user can cheat with impunity. Let’s fix that by having the CheatActivity tell the QuizActivity whether the user chose to view the answer.
When you want to hear back from the child activity, you call the following Activity method:
Copy
public void startActivityForResult(Intent intent, int requestCode)
Copy
private static final int REQUEST_CODE_CHEAT = 0;
.......
mCheatButton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Logger.w("Cheat Button Clicked");
Intent i = new Intent(MainActivity.this, CheatActivty.class);
String message = "Hello from MainActivity";
i.putExtra(EXTRA_MESSAGE, message);
startActivityForResult(i, REQUEST_CODE_CHEAT);
}
});
in your second activity:
Copy
public class CheatActivty extends AppCompatActivity {
private Button mShowAnswer;
......
mShowAnswer = (Button) findViewById(R.id.show_answer_button);
mShowAnswer.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Intent returnIntent = new Intent();
returnIntent.putExtra("result", "Hello from Cheat Activity");
setResult(Activity.RESULT_OK, returnIntent);
finish();
}
});
Please note **Setting a result**
There are two methods you can call in the child activity to send data back to the parent:
Copy
public final void setResult(int resultCode)
public final void setResult(int resultCode, Intent data)
Typically, the result code is one of two predefined constants: Activity.RESULT\_OK or Activity.RESULT\_CANCELED. (You can use another constant, RESULT\_FIRST\_USER, as an offset when defining your own result codes.)
Setting result codes is useful when the parent needs to take different action depending on how the child activity finished. For example, if a child activity had an OK button and a Cancel button, the child activity would set a different result code depending on which button was pressed. Then the parent activity would take different action depending on the result code.
**Now you need To override the onActivityResult in your first activity**
Copy
@Override
protected void onActivityResult(int requestCode, int resultCode,
@Nullable Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == REQUEST_CODE_CHEAT){
Logger.d(requestCode);
}
}
[PreviousThe Activity Lifecycle](https://developer-mina.gitbook.io/cisc-349/android-programming/the-activity-lifecycle)
[NextList View](https://developer-mina.gitbook.io/cisc-349/android-programming/list-view)
Last updated 4 years ago
Was this helpful?
---
# List View | CISC 349
Displays a vertically-scrollable collection of views, where each view is positioned immediately below the previous view in the list.
To display a list, you can include a list view in your layout XML file:
Copy
A list view is an [adapter view](https://developer.android.com/guide/topics/ui/declaring-layout#AdapterViews)
that does not know the details, such as type and contents, of the views it contains. Instead, list view requests views on demand from a [`ListAdapter`](https://developer.android.com/reference/android/widget/ListAdapter)
as needed, such as to display new views as the user scrolls up or down.
In order to display items in the list, call [`setAdapter(android.widget.ListAdapter)`](https://developer.android.com/reference/android/widget/ListView#setAdapter(android.widget.ListAdapter))
to associate an adapter with the list. For a simple example, see the discussion of filling an adapter view with text in the [Layouts](https://developer.android.com/guide/topics/ui/declaring-layout#FillingTheLayout)
guide.
To display a more custom view for each item in your dataset, implement a ListAdapter. For example, extend [`BaseAdapter`](https://developer.android.com/reference/android/widget/BaseAdapter)
and create and configure the view for each data item in `getView(...)`:
Copy
private class MyAdapter extends BaseAdapter {
// override other abstract methods here
@Override
public View getView(int position, View convertView, ViewGroup container) {
if (convertView == null) {
convertView = getLayoutInflater().inflate(R.layout.list_item,
container, false);
}
((TextView) convertView.findViewById(android.R.id.text1))
.setText(getItem(position));
return convertView;
}
}
[](https://developer-mina.gitbook.io/cisc-349/android-programming/list-view#example)
Example
-------------------------------------------------------------------------------------------------
Start by creating a new project, select empty activity as shown below:


Call your project SimpleList
in **activity\_main.xml** remove the hello world **text view,** and add a listview, your layout XML file should look like this:
Copy
...
android:layout_height="match_parent"
tools:context=".MainActivity">
Now we will treat every row in the text view as a separate layout, add a new layout and call it **my\_list.xml**

Right click on layout
Since this is a simple layout all we need is a **TextView** your **my\_list.xml** should look like the following:
Copy
We need some data to fill the list, one way of doing this is using the string resources XML file as following:
Copy
SimpleListAndroidJavaPhpHadoopSapPythonAjaxC++RubyRails.NetPerl
Now in the activity class, we need to inflate the list with data, first we define all the resources we need to use in our class:
Copy
ListView listView;
TextView textView;
String[] listItem;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
listView = findViewById(R.id.listView);
textView = findViewById(R.id.textView);
listItem = getResources().getStringArray(R.array.array_technology);
}
Note how to get the array string list using:
Copy
getResources().getStringArray(R.array.array_technology);
**array\_technology** is the name of the **string-array** as stated in the resource file.
it is always a good idea to testing logging the information to make sure that everything is working as it should:
Copy
private static final String TAG = "MainActivity";
ListView listView;
TextView textView;
String[] listItem;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
listView = findViewById(R.id.listView);
textView = findViewById(R.id.textView);
listItem = getResources().getStringArray(R.array.array_technology);
for (String s : listItem) {
Log.d(TAG, s);
}
}
[](https://developer-mina.gitbook.io/cisc-349/android-programming/list-view#building-layouts-with-an-adapter)
Building Layouts with an Adapter
---------------------------------------------------------------------------------------------------------------------------------------------------
When the content for your layout is dynamic or not pre-determined, you can use a layout that subclasses AdapterView to populate the layout with views at runtime. A subclass of the AdapterView class uses an Adapter to bind data to its layout. The Adapter behaves as a middleman between the data source and the AdapterView layout—the Adapter retrieves the data (from a source such as an array or a database query) and converts each entry into a view that can be added into the AdapterView layout.
Common layouts backed by an adapter include:
**List View and Grid View**

Displays a scrolling single column list.

Displays a scrolling grid of columns and rows.
[](https://developer-mina.gitbook.io/cisc-349/android-programming/list-view#filling-an-adapter-view-with-data)
Filling an adapter view with data
-----------------------------------------------------------------------------------------------------------------------------------------------------
You can populate an AdapterView such as ListView or GridView by binding the AdapterView instance to an Adapter, which retrieves data from an external source and creates a View that represents each data entry.
Android provides several subclasses of Adapter that are useful for retrieving different kinds of data and building views for an AdapterView. The two most common adapters are:
[](https://developer-mina.gitbook.io/cisc-349/android-programming/list-view#arrayadapter)
ArrayAdapter
-----------------------------------------------------------------------------------------------------------
Use this adapter when your data source is an array. By default, **ArrayAdapter** creates a view for each array item by calling **toString()** on each item and placing the contents in a TextView. For example, if you have an array of strings you want to display in a **ListView**, initialize a new **ArrayAdapter** using a constructor to specify the layout for each string and the string array:
Copy
ArrayAdapter adapter = new ArrayAdapter(this, R.layout.my_list,
listItem);
####
[](https://developer-mina.gitbook.io/cisc-349/android-programming/list-view#the-arguments-for-this-constructor-are)
The arguments for this constructor are:
* Your app [`Context`](https://developer.android.com/reference/android/content/Context)
* The layout that contains a [`TextView`](https://developer.android.com/reference/android/widget/TextView)
for each string in the array
* The string array
Then simply call **setAdapter()** on your **ListView**:
Copy
listView.setAdapter(adapter);

[](https://developer-mina.gitbook.io/cisc-349/android-programming/list-view#handling-click-events)
Handling click events
-----------------------------------------------------------------------------------------------------------------------------
You can respond to click events on each item in an AdapterView by implementing the AdapterView.OnItemClickListener interface. For example:
Copy
listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
@Override
public void onItemClick(AdapterView> parent, View view,
int position, long id) {
String value=adapter.getItem(position);
Toast.makeText(getApplicationContext(),value,Toast.LENGTH_SHORT).show();
}
});
[](https://developer-mina.gitbook.io/cisc-349/android-programming/list-view#on-item-click-method)
On Item Click Method
---------------------------------------------------------------------------------------------------------------------------
Callback method to be invoked when an item in this AdapterView has been clicked.
Implementers can call getItemAtPosition(position) if they need to access the data associated with the selected item.
Copy
public abstract void onItemClick (AdapterView> parent,
View view,
int position,
long id)

[PreviousYour Second Activity](https://developer-mina.gitbook.io/cisc-349/android-programming/your-second-activity)
[NextCustom ArrayAdapter](https://developer-mina.gitbook.io/cisc-349/android-programming/custom-arrayadapter)
Last updated 4 years ago
Was this helpful?
---
# Custom ArrayAdapter | CISC 349
[](https://developer-mina.gitbook.io/cisc-349/android-programming/custom-arrayadapter#using-a-custom-arrayadapter)
Using a Custom ArrayAdapter
---------------------------------------------------------------------------------------------------------------------------------------------------
When we want to display a series of items from a list using a custom representation of the items, we need to use our own custom XML layout for each item. To do this, we need to create our own **custom** **ArrayAdapter** class.
[](https://developer-mina.gitbook.io/cisc-349/android-programming/custom-arrayadapter#defining-the-model)
Defining the Model
---------------------------------------------------------------------------------------------------------------------------------
First, you have to define your custom class, in this example, I will use a class called **User.java**
Copy
public class User {
private String name;
private String phone;
public User(String name, String phone) {
this.name = name;
this.phone = phone;
}
public String getName() {
return name;
}
public String getPhone() {
return phone;
}
}
[](https://developer-mina.gitbook.io/cisc-349/android-programming/custom-arrayadapter#creating-the-view-template)
Creating the View Template
-------------------------------------------------------------------------------------------------------------------------------------------------
Next, we need to create an XML layout that represents the view template for each item in `res/layout/item_user.xml:`
Copy
**This is not your MainActivity layout**
Your MainActivity Layout should only contain **ListView** as following:
Copy
[](https://developer-mina.gitbook.io/cisc-349/android-programming/custom-arrayadapter#defining-the-adapter)
Defining the Adapter
-------------------------------------------------------------------------------------------------------------------------------------
Copy
public class UserAdapter extends BaseAdapter {
private Context context;
private ArrayList arrayList;
private TextView name, phone;
public UserAdapter(Context context, ArrayList arrayList) {
this.context = context;
this.arrayList = arrayList;
}
@Override
public int getCount() {
return arrayList.size();
}
@Override
public Object getItem(int position) {
return position;
}
@Override
public long getItemId(int position) {
return position;
}
@Override
public View getView(int position, View convertView, ViewGroup parent) {
convertView = LayoutInflater.from(context).inflate(R.layout.item_user,
parent, false );
name = convertView.findViewById(R.id.name);
phone = convertView.findViewById(R.id.phone);
name.setText(arrayList.get(position).name);
phone.setText(arrayList.get(position).phone);
return convertView;
}
}
`LayoutInflater` will take an XML file and convert it to view object
[](https://developer-mina.gitbook.io/cisc-349/android-programming/custom-arrayadapter#inflate)
inflate
-----------------------------------------------------------------------------------------------------------
Copy
public View inflate (XmlPullParser parser,
ViewGroup root,
boolean attachToRoot)
Inflate a new view hierarchy from the specified XML node. Throws InflateException if there is an error.
Important For performance reasons view inflation relies heavily on pre-processing of XML files that is done at build time. Therefore, it is not currently possible to use LayoutInflater with an XmlPullParser over a plain XML file at runtime.

[](https://developer-mina.gitbook.io/cisc-349/android-programming/custom-arrayadapter#mainactivity)
MainActivity
---------------------------------------------------------------------------------------------------------------------
Copy
package com.example.customelist;
import androidx.appcompat.app.AppCompatActivity;
import android.os.Bundle;
import android.widget.ListView;
import java.util.ArrayList;
public class MainActivity extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
ArrayList arrayOfUsers = new ArrayList<>();
arrayOfUsers.add(new User("Eve", "777-777-7777"));
arrayOfUsers.add(new User("John", "777-777-7777"));
arrayOfUsers.add(new User("Mark", "777-777-7777"));
arrayOfUsers.add(new User("Michael", "777-777-7777"));
arrayOfUsers.add(new User("Adam", "777-777-7777"));
arrayOfUsers.add(new User("Mary", "777-777-7777"));
arrayOfUsers.add(new User("Olivia", "777-777-7777"));
// Create the adapter to convert the array to views
UserAdapter adapter = new UserAdapter(this, arrayOfUsers);
// Attach the adapter to a ListView
ListView listView = (ListView) findViewById(R.id.my_list_view);
listView.setAdapter(adapter);
}
}
[PreviousList View](https://developer-mina.gitbook.io/cisc-349/android-programming/list-view)
[NextNetworking HTTP](https://developer-mina.gitbook.io/cisc-349/android-programming/networking-http)
Last updated 4 years ago
Was this helpful?
---
# Network Image View | CISC 349
Reference: [Android Volley ImageLoader and NetworkImageView Example](https://www.truiton.com/2015/03/android-volley-imageloader-networkimageview-example/)
Displaying images over a network is fundamental for most mobile apps. **Volley** provides a good method of doing this.
Earlier to load images in an Android ImageView, the standard approach taken was the usage of **HttpURLConnection** class. But now with volley, this is simplified as we may not need to get into such complex code. Volley gives us two new classes which make life easier.
[](https://developer-mina.gitbook.io/cisc-349/android-programming/network-image-view#android-volley-imageloader)
Android Volley ImageLoader
------------------------------------------------------------------------------------------------------------------------------------------------
Volley uses ImageLoader to load images from the network, and also to cache them into your Android phone’s in-memory cache by using the [LruCache](https://developer.android.com/reference/android/util/LruCache)
class.
Copy
public class MainActivity extends AppCompatActivity {
private NetworkImageView image;
private ImageLoader imageLoader;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
image = (NetworkImageView) findViewById(R.id.networkImageView);
}
@Override
protected void onStart() {
super.onStart();
RequestQueue queue = Volley.newRequestQueue(this);
imageLoader = new ImageLoader(queue, new ImageLoader.ImageCache() {
private final LruCache mCache = new LruCache(20);
@Override
public Bitmap getBitmap(String url) {
return mCache.get(url);
}
@Override
public void putBitmap(String url, Bitmap bitmap) {
mCache.put(url, bitmap);
}
});
final String url =
"https://static.toiimg.com/photo/msid-67586673/67586673.jpg";
image.setImageUrl(url, imageLoader);
}
}
The ImageLoader class provides a centralized point for loading images in **Volley**. Using ImageLoader is the preferred way for getting images from remote sources.
Don't forget to add the **Volley** library:
Copy
implementation 'com.android.volley:volley:1.1.1'
Don't forget the **INTERNET** and **ACCESS NETWORK STATE** permissions
Copy
[](https://developer-mina.gitbook.io/cisc-349/android-programming/network-image-view#android-volley-networkimageview)
Android Volley NetworkImageView
----------------------------------------------------------------------------------------------------------------------------------------------------------
A new view introduced with Android volley is NetworkImageView. As a matter of fact this view replaces the standard **ImageView**, when comes to the usage of volley. Android Volley NetworkImageView is designed in such a way that it creates an image request, sends it and even displays the image, after it is downloaded from the URL. Also, it cancels the request on its own if it is detached from the view hierarchy. Hence no need to handle the request cancellations with Volley NetworkImageView. Have a look at the layout for this Android Volley ImageLoader and NetworkImageView Example, it just includes a NetworkImageView instead of ImageView:
Copy
**dimen** XML file
Copy
16dp16dp
**Output:**

[PreviousNetworking HTTP](https://developer-mina.gitbook.io/cisc-349/android-programming/networking-http)
[NextFlask](https://developer-mina.gitbook.io/cisc-349/android-programming/flask)
Last updated 4 years ago
Was this helpful?
---
# Networking HTTP | CISC 349
Resources: [Developer Android](https://developer.android.com/training/volley)
[](https://developer-mina.gitbook.io/cisc-349/android-programming/networking-http#volley-overview)
Volley overview
-----------------------------------------------------------------------------------------------------------------------
Volley is an HTTP library that makes networking for Android apps easier and most importantly, faster.
**Volley offers the following benefits**:
* Automatic scheduling of network requests.
* Multiple concurrent network connections.
* Ease of customization, for example, for retry and backoff.
* Strong ordering that makes it easy to correctly populate your UI with data fetched asynchronously from the network.
* Debugging and tracing tools.
[](https://developer-mina.gitbook.io/cisc-349/android-programming/networking-http#adding-volley)
Adding Volley
-------------------------------------------------------------------------------------------------------------------
The easiest way to add Volley to your project is to add the following dependency to your app's **build.gradle** file:
Copy
dependencies {
...
implementation 'com.android.volley:volley:1.1.1'
}
[](https://developer-mina.gitbook.io/cisc-349/android-programming/networking-http#send-a-simple-request)
Send a simple request
-----------------------------------------------------------------------------------------------------------------------------------
At a high level, you use Volley by creating a RequestQueue and passing it Request objects.
###
[](https://developer-mina.gitbook.io/cisc-349/android-programming/networking-http#add-the-internet-permission)
Add the INTERNET permission
To perform network operations in your application, your manifest must include the following permissions:
Copy
###
[](https://developer-mina.gitbook.io/cisc-349/android-programming/networking-http#simple)
Use newRequestQueue
Volley provides a convenience method **Volley.newRequestQueue** that sets up a RequestQueue for you, using default values, and starts the queue. For example:
Copy
final TextView textView = (TextView) findViewById(R.id.text);
// Instantiate the RequestQueue.
RequestQueue queue = Volley.newRequestQueue(this);
String url ="https://www.google.com";
// Request a string response from the provided URL.
StringRequest stringRequest = new StringRequest(Request.Method.GET, url,
new Response.Listener() {
@Override
public void onResponse(String response) {
// Display the first 500 characters of the response string.
textView.setText(response.substring(0,500));
}
}, new Response.ErrorListener() {
@Override
public void onErrorResponse(VolleyError error) {
textView.setText("That didn't work!");
}
});
// Add the request to the RequestQueue.
queue.add(stringRequest);
}

[](https://developer-mina.gitbook.io/cisc-349/android-programming/networking-http#json-format)
JSON Format
---------------------------------------------------------------------------------------------------------------
JSON stands for **J**ava**S**cript **O**bject **N**otation
JSON is a **text format** for storing and transporting data
JSON is "self-describing" and easy to understand
###
[](https://developer-mina.gitbook.io/cisc-349/android-programming/networking-http#json-example)
JSON Example
This example is a JSON string:
Copy
'{"name":"John", "age":30, "car":null}'
It defines an object with 3 properties:
* name
* age
* car
Each property has a value.
If you parse the JSON string with a JavaScript program, you can access the data as an object:
Copy
String personName = obj.name;
String personAge = obj.age;
###
[](https://developer-mina.gitbook.io/cisc-349/android-programming/networking-http#json-syntax-rules)
JSON Syntax Rules
JSON syntax is derived from JavaScript object notation syntax:
* Data is in name/value pairs
* Data is separated by commas
* Curly braces hold objects
* Square brackets hold arrays
###
[](https://developer-mina.gitbook.io/cisc-349/android-programming/networking-http#json-data-a-name-and-a-value)
JSON Data - A Name and a Value
JSON data is written as name/value pairs (aka key/value pairs).
A name/value pair consists of a field name (in double quotes), followed by a colon, followed by a value:
Copy
"name":"John"
###
[](https://developer-mina.gitbook.io/cisc-349/android-programming/networking-http#json-values)
JSON Values
In **JSON**, _values_ must be one of the following data types:
* a string
* a number
* an object
* an array
* a boolean
* null
Copy
person = {name:"John", age:31, city:"New York"};
###
[](https://developer-mina.gitbook.io/cisc-349/android-programming/networking-http#json-files)
JSON Files
* The file type for JSON files is ".json"
[](https://developer-mina.gitbook.io/cisc-349/android-programming/networking-http#request-json)
Request JSON
-----------------------------------------------------------------------------------------------------------------
Volley provides the following classes for JSON requests:
* JsonArrayRequest—A request for retrieving a JSONArray response body at a given URL.
* JsonObjectRequest—A request for retrieving a JSONObject response body at a given URL, allowing for an optional JSONObject to be passed in as part of the request body.
Copy
final TextView textView = (TextView) findViewById(R.id.text);
// Instantiate the RequestQueue.
RequestQueue queue = Volley.newRequestQueue(this);
//JSONArrayRequest
JsonArrayRequest jsonArrayRequest =
new JsonArrayRequest(Request.Method.GET,
"https://api.androidhive.info/json/movies.json", null,
new Response.Listener() {
@Override
public void onResponse(JSONArray response) {
for (int i = 0; i < response.length(); i++) {
try {
JSONObject jsonObjectFromArray =
response.getJSONObject(i);
Log.d("JSONArray Response", "Movie Title: " +
jsonObjectFromArray.getString("title"));
} catch (JSONException e) {
e.printStackTrace();
}
}
}
}, new Response.ErrorListener() {
@Override
public void onErrorResponse(VolleyError error) {
Log.d("JSONArray Error", "Error:" + error);
}
});
queue.add(jsonArrayRequest);
**Output:**
Copy
D: Response: Dawn of the Planet of the Apes
D: Response: District 9
D: Response: Transformers: Age of Extinction
D: Response: X-Men: Days of Future Past
D: Response: The Machinist
D: Response: The Last Samurai
D: Response: The Amazing Spider-Man 2
D: Response: Tangled
D: Response: Rush
D: Response: Drag Me to Hell
D: Response: Despicable Me 2
D: Response: Kill Bill: Vol. 1
D: Response: A Bug's Life
D: Response: Life of Brian
D: Response: How to Train Your Dragon
[](https://developer-mina.gitbook.io/cisc-349/android-programming/networking-http#json-deserialization)
JSON Deserialization
---------------------------------------------------------------------------------------------------------------------------------
It is the process of converting a JSON string to a JAVA object, to convert from JSON to Java you need a **POJO** (Plain Old Java Object) class.
**POJOs** basically defines an entity. Like in your program, if you want an employee class then you can create a POJO as follows:
Copy
public class Employee
{
String name;
public String id;
private double salary;
public Employee(String name, String id,
double salary)
{
this.name = name;
this.id = id;
this.salary = salary;
}
public String getName()
{
return name;
}
public String getId()
{
return id;
}
public Double getSalary()
{
return salary;
}
}
In our example found in the JSON object from the following link:
Copy
https://api.androidhive.info/json/movies.json
The equivalent Java class will be:
Copy
public class Movie {
private String title;
private String image;
private Double rating;
private Integer releaseYear;
private ArrayList genre;
public Movie(String title, String image, Double rating,
Integer releaseYear, ArrayList genre) {
this.title = title;
this.image = image;
this.rating = rating;
this.releaseYear = releaseYear;
this.genre = genre;
}
public String getTitle() {
return title;
}
public void setTitle(String title) {
this.title = title;
}
public String getImage() {
return image;
}
public void setImage(String image) {
this.image = image;
}
public Double getRating() {
return rating;
}
public void setRating(Double rating) {
this.rating = rating;
}
public Integer getReleaseYear() {
return releaseYear;
}
public void setReleaseYear(Integer releaseYear) {
this.releaseYear = releaseYear;
}
public ArrayList getGenre() {
return genre;
}
public void setGenre(ArrayList genre) {
this.genre = genre;
}
}
The following code will ERROR at the end, you need to fix the bug
Copy
ArrayList movies = new ArrayList<>();
final TextView textView = (TextView) findViewById(R.id.text);
// Instantiate the RequestQueue.
RequestQueue queue = Volley.newRequestQueue(this);
//JSONArrayRequest
JsonArrayRequest jsonArrayRequest = new JsonArrayRequest(Request.Method.GET,
"https://api.androidhive.info/json/movies.json", null,
new Response.Listener() {
@Override
public void onResponse(JSONArray response) {
for (int i = 0; i < response.length(); i++) {
try {
JSONObject jsonObjectFromArray =
response.getJSONObject(i);
JSONArray genre = jsonObjectFromArray
.getJSONArray("genre");
ArrayList genre_list = new ArrayList<>();
for (int j = 0; j < genre.length(); j++) {
genre_list.add(genre.get(j).toString());
}
Movie movie = new Movie(
jsonObjectFromArray.getString("title"),
jsonObjectFromArray.getString("image"),
jsonObjectFromArray.getDouble("rating"),
jsonObjectFromArray.getInt("releaseYear"),
genre_list
);
movies.add(movie);
} catch (JSONException e) {
e.printStackTrace();
}
}
}
}, new Response.ErrorListener() {
@Override
public void onErrorResponse(VolleyError error) {
Log.d("JSONArray Error", "Error:" + error);
}
});
queue.add(jsonArrayRequest);
//Log the first movie
Log.d("Movie" , movies.get(0).getImage());

[](https://developer-mina.gitbook.io/cisc-349/android-programming/networking-http#gson-library)
Gson Library
-----------------------------------------------------------------------------------------------------------------
[Gson](https://github.com/google/gson)
is a Java library that can be used to convert Java Objects into their JSON representation. It can also be used to convert a JSON string to an equivalent Java object.
###
[](https://developer-mina.gitbook.io/cisc-349/android-programming/networking-http#download-and-install)
Download and Install
Copy
dependencies {
implementation 'com.google.code.gson:gson:2.8.6'
}
####
[](https://developer-mina.gitbook.io/cisc-349/android-programming/networking-http#change-the-movie-class-as-following)
Change the Movie class as following:
> ####
>
> [](https://developer-mina.gitbook.io/cisc-349/android-programming/networking-http#serializedname-an-annotation-that-indicates-this-member-should-be-serialized-to-json-with-the-provid)
>
> @SerializedName : An annotation that indicates this member should be serialized to JSON with the provided name value as its field name.
Copy
import java.util.ArrayList;
import java.util.List;
public class Movie {
@SerializedName("title")
private String title;
@SerializedName("image")
private String image;
@SerializedName("rating")
private Double rating;
@SerializedName("releaseYear")
private Integer releaseYear;
@SerializedName("genre")
private ArrayList genre;
public Movie(String title, String image, Double rating,
Integer releaseYear, ArrayList genre) {
this.title = title;
this.image = image;
this.rating = rating;
this.releaseYear = releaseYear;
this.genre = genre;
}
public String getTitle() {
return title;
}
public void setTitle(String title) {
this.title = title;
}
public String getImage() {
return image;
}
public void setImage(String image) {
this.image = image;
}
public Double getRating() {
return rating;
}
public void setRating(Double rating) {
this.rating = rating;
}
public Integer getReleaseYear() {
return releaseYear;
}
public void setReleaseYear(Integer releaseYear) {
this.releaseYear = releaseYear;
}
public ArrayList getGenre() {
return genre;
}
public void setGenre(ArrayList genre) {
this.genre = genre;
}
}
###
[](https://developer-mina.gitbook.io/cisc-349/android-programming/networking-http#mainactivity)
MainActivity
Copy
package com.example.testvolley;
import androidx.appcompat.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.widget.TextView;
import com.android.volley.Request;
import com.android.volley.RequestQueue;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.JsonArrayRequest;
import com.android.volley.toolbox.JsonObjectRequest;
import com.android.volley.toolbox.StringRequest;
import com.android.volley.toolbox.Volley;
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import java.util.ArrayList;
import java.util.List;
public class MainActivity extends AppCompatActivity {
private Gson gson;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
ArrayList movies = new ArrayList<>();
GsonBuilder gsonBuilder = new GsonBuilder();
gson = gsonBuilder.create();
final TextView textView = (TextView) findViewById(R.id.text);
// Instantiate the RequestQueue.
RequestQueue queue = Volley.newRequestQueue(this);
//JSONArrayRequest
JsonArrayRequest jsonArrayRequest =
new JsonArrayRequest(Request.Method.GET,
"https://api.androidhive.info/json/movies.json", null,
new Response.Listener() {
@Override
public void onResponse(JSONArray response) {
for (int i = 0; i < response.length(); i++) {
try {
Movie movie =
gson.fromJson(response.getJSONObject(i)
.toString(),
Movie.class);
movies.add(movie);
} catch (JSONException e) {
e.printStackTrace();
}
}
Log.d("Movie", movies.get(0).getTitle());
}
}, new Response.ErrorListener() {
@Override
public void onErrorResponse(VolleyError error) {
Log.d("JSONArray Error", "Error:" + error);
}
});
queue.add(jsonArrayRequest);
}
}
###
[](https://developer-mina.gitbook.io/cisc-349/android-programming/networking-http#using-break-points)
Using Break-Points

[PreviousCustom ArrayAdapter](https://developer-mina.gitbook.io/cisc-349/android-programming/custom-arrayadapter)
[NextNetwork Image View](https://developer-mina.gitbook.io/cisc-349/android-programming/network-image-view)
Last updated 3 years ago
Was this helpful?
---
# Code of Ethics | CISC 349
The Code as a whole is concerned with how fundamental ethical principles apply to a computing professional’s conduct. The Code is not an algorithm for solving ethical problems; rather it serves as a basis for ethical decision-making. When thinking through a particular issue, a computing professional may find that multiple principles should be taken into account and that different principles will have different relevance to the issue.
[](https://developer-mina.gitbook.io/cisc-349/android-programming/code-of-ethics#id-1.-general-ethical-principles)
1\. General Ethical Principles
------------------------------------------------------------------------------------------------------------------------------------------------------
###
[](https://developer-mina.gitbook.io/cisc-349/android-programming/code-of-ethics#id-1.1-contribute-to-society-and-to-human-well-being-acknowledging-that-all-people-are-stakeholders-in)
1.1 Contribute to society and to human well-being, acknowledging that all people are stakeholders in computing.
This principle, which concerns the quality of life of all people, affirms an obligation of computing professionals, both individually and collectively, to use their skills for the benefit of society, its members, and the environment surrounding them. This obligation includes promoting fundamental human rights and protecting each individual’s right to autonomy. An essential aim of computing professionals is to minimize the negative consequences of computing, including threats to health, safety, personal security, and privacy. When the interests of multiple groups conflict, the needs of those less advantaged should be given increased attention and priority.
Computing professionals should consider whether the results of their efforts will respect diversity, will be used in socially responsible ways, will meet social needs, and will be broadly accessible. They are encouraged to actively contribute to society by engaging in pro bono or volunteer work that benefits the public good. In addition to a safe social environment, human well-being requires a safe natural environment. Therefore, computing professionals should promote environmental sustainability both locally and globally.
###
[](https://developer-mina.gitbook.io/cisc-349/android-programming/code-of-ethics#id-1.2-avoid-the-harm)
1.2 Avoid the harm.
In this document, “harm” means negative consequences, especially when those consequences are significant and unjust. Examples of harm include unjustified physical or mental injury, unjustified destruction or disclosure of information, and unjustified damage to property, reputation, and the environment. This list is not exhaustive. Well-intended actions, including those that accomplish assigned duties, may lead to harm. When that harm is unintended, those responsible are obliged to undo or mitigate the harm as much as possible.
Avoiding harm begins with careful consideration of potential impacts on all those affected by decisions. When harm is an intentional part of the system, those responsible are obligated to ensure that the harm is ethically justified. In either case, ensure that all harm is minimized. To minimize the possibility of indirectly or unintentionally harming others, computing professionals should follow generally accepted best practices unless there is a compelling ethical reason to do otherwise. Additionally, the consequences of data aggregation and emergent properties of systems should be carefully analyzed. Those involved with pervasive or infrastructure systems should also consider Principle 3.7.
A computing professional has an additional obligation to report any signs of system risks that might result in harm. If leaders do not act to curtail or mitigate such risks, it may be necessary to “blow the whistle” to reduce potential harm. However, capricious or misguided reporting of risks can itself be harmful. Before reporting risks, a computing professional should carefully assess relevant aspects of the situation.
###
[](https://developer-mina.gitbook.io/cisc-349/android-programming/code-of-ethics#id-1.3-be-honest-and-trustworthy)
1.3 Be honest and trustworthy.
Honesty is an essential component of trustworthiness. A computing professional should be transparent and provide full disclosure of all pertinent system capabilities, limitations, and potential problems to the appropriate parties. Making deliberately false or misleading claims, fabricating or falsifying data, offering or accepting bribes, and other dishonest conduct are violations of the Code. Computing professionals should be honest about their qualifications, and about any limitations in their competence to complete a task. Computing professionals should be forthright about any circumstances that might lead to either real or perceived conflicts of interest or otherwise tend to undermine the independence of their judgment. Furthermore, commitments should be honored. Computing professionals should not misrepresent an organization’s policies or procedures, and should not speak on behalf of an organization unless authorized to do so.
###
[](https://developer-mina.gitbook.io/cisc-349/android-programming/code-of-ethics#id-1.4-be-fair-and-take-action-not-to-discriminate)
1.4 Be fair and take action not to discriminate.
The values of equality, tolerance, respect for others, and justice govern this principle. Fairness requires that even careful decision processes provide some avenue for redress of grievances. Computing professionals should foster fair participation of all people, including those of underrepresented groups. Prejudicial discrimination on the basis of age, color, disability, ethnicity, family status, gender identity, labor union membership, military status, nationality, race, religion or belief, sex, sexual orientation, or any other inappropriate factor is an explicit violation of the Code. Harassment, including sexual harassment, bullying, and other abuses of power and authority, is a form of discrimination that, amongst other harms, limits fair access to the virtual and physical spaces where such harassment takes place. The use of information and technology may cause new, or enhance existing, inequities. Technologies and practices should be as inclusive and accessible as possible and computing professionals should take action to avoid creating systems or technologies that disenfranchise or oppress people. Failure to design for inclusiveness and accessibility may constitute unfair discrimination.
###
[](https://developer-mina.gitbook.io/cisc-349/android-programming/code-of-ethics#id-1.5-respect-the-work-required-to-produce-new-ideas-inventions-creative-works-and-computing-artifacts)
1.5 Respect the work required to produce new ideas, inventions, creative works, and computing artifacts.
Developing new ideas, inventions, creative works, and computing artifacts creates value for society, and those who expend this effort should expect to gain value from their work. Computing professionals should therefore credit the creators of ideas, inventions, work, and artifacts, and respect copyrights, patents, trade secrets, license agreements, and other methods of protecting authors’ works. Both custom and the law recognize that some exceptions to a creator’s control of a work are necessary for the public good. Computing professionals should not unduly oppose reasonable uses of their intellectual works. Efforts to help others by contributing time and energy to projects that help society illustrate a positive aspect of this principle. Such efforts include free and open source software and work put into the public domain. Computing professionals should not claim private ownership of work that they or others have shared as public resources.
###
[](https://developer-mina.gitbook.io/cisc-349/android-programming/code-of-ethics#id-1.6-respect-privacy)
1.6 Respect privacy.
The responsibility of respecting privacy applies to computing professionals in a particularly profound way. Technology enables the collection, monitoring, and exchange of personal information quickly, inexpensively, and often without the knowledge of the people affected. Therefore, a computing professional should become conversant in the various definitions and forms of privacy and should understand the rights and responsibilities associated with the collection and use of personal information. Computing professionals should only use personal information for legitimate ends and without violating the rights of individuals and groups. This requires taking precautions to prevent re-identification of anonymized data or unauthorized data collection, ensuring the accuracy of data, understanding the provenance of the data, and protecting it from unauthorized access and accidental disclosure. Computing professionals should establish transparent policies and procedures that allow individuals to understand what data is being collected and how it is being used, to give informed consent for automatic data collection, and to review, obtain, correct inaccuracies in, and delete their personal data. Only the minimum amount of personal information necessary should be collected in a system. The retention and disposal periods for that information should be clearly defined, enforced, and communicated to data subjects. Personal information gathered for a specific purpose should not be used for other purposes without the person’s consent. Merged data collections can compromise privacy features present in the original collections. Therefore, computing professionals should take special care of privacy when merging data collections.
###
[](https://developer-mina.gitbook.io/cisc-349/android-programming/code-of-ethics#id-1.7-honor-confidentiality)
1.7 Honor confidentiality.
Computing professionals are often entrusted with confidential information such as trade secrets, client data, nonpublic business strategies, financial information, research data, pre-publication scholarly articles, and patent applications. Computing professionals should protect confidentiality except in cases where it is evidence of the violation of law, of organizational regulations, or of the Code. In these cases, the nature or contents of that information should not be disclosed except to appropriate authorities. A computing professional should consider thoughtfully whether such disclosures are consistent with the Code.
[](https://developer-mina.gitbook.io/cisc-349/android-programming/code-of-ethics#id-2.-professional-responsibilities)
2\. Professional Responsibilities
------------------------------------------------------------------------------------------------------------------------------------------------------------
###
[](https://developer-mina.gitbook.io/cisc-349/android-programming/code-of-ethics#id-2.1-strive-to-achieve-high-quality-in-both-the-processes-and-products-of-professional-work)
2.1 Strive to achieve high quality in both the processes and products of professional work.
Make a positive impact. Computing professionals should insist on and support high-quality work from themselves and from colleagues. The dignity of employers, employees, colleagues, clients, users, and anyone else affected either directly or indirectly by the work should be respected throughout the process. Computing professionals should respect the right of those involved to transparent communication about the project. Professionals should be cognizant of any serious negative consequences affecting any stakeholder that may result from poor quality work and should resist inducements to neglect this responsibility.
###
[](https://developer-mina.gitbook.io/cisc-349/android-programming/code-of-ethics#id-2.2-maintain-high-standards-of-professional-competence-conduct-and-ethical-practice)
2.2 Maintain high standards of professional competence, conduct, and ethical practice.
High-quality computing depends on individuals and teams who take personal and group responsibility for acquiring and maintaining professional competence. Professional competence starts with technical knowledge and with awareness of the social context in which their work may be deployed. Professional competence also requires skill in communication, in reflective analysis, and in recognizing and navigating ethical challenges. Upgrading skills should be an ongoing process and might include independent study, attending conferences or seminars, and other informal or formal education. Professional organizations and employers should encourage and facilitate these activities.
###
[](https://developer-mina.gitbook.io/cisc-349/android-programming/code-of-ethics#id-2.3-know-and-respect-existing-rules-pertaining-to-professional-work)
2.3 Know and respect existing rules pertaining to professional work.
“Rules” here include local, regional, national, and international laws and regulations, as well as any policies and procedures of the organizations to which the professional belongs. Computing professionals must abide by these rules unless there is a compelling ethical justification to do otherwise. Rules that are judged unethical should be challenged. A rule may be unethical when it has an inadequate moral basis or causes recognizable harm. A computing professional should consider challenging the rule through existing channels before violating the rule. A computing professional who decides to violate a rule because it is unethical, or for any other reason, must consider potential consequences and accept responsibility for that action.
###
[](https://developer-mina.gitbook.io/cisc-349/android-programming/code-of-ethics#id-2.4-accept-and-provide-appropriate-professional-review)
2.4 Accept and provide appropriate professional review.
High-quality professional work in computing depends on professional review at all stages. Whenever appropriate, computing professionals should seek and utilize peer and stakeholder review. Computing professionals should also provide constructive, critical reviews of others’ work.
###
[](https://developer-mina.gitbook.io/cisc-349/android-programming/code-of-ethics#id-2.5-give-comprehensive-and-thorough-evaluations-of-computer-systems-and-their-impacts-including-anal)
2.5 Give comprehensive and thorough evaluations of computer systems and their impacts, including analysis of possible risks.
Computing is a service to society. Computing professionals are in a position of trust, and therefore have a special responsibility to provide objective, credible evaluations and testimony to employers, employees, clients, users, and the public. Computing professionals should strive to be perceptive, thorough, and objective when evaluating, recommending, and presenting system descriptions and alternatives. Extraordinary care should be taken to identify and mitigate potential risks in machine learning systems. A system for which future risks cannot be reliably predicted requires frequent reassessment of risk as the system evolves in use, or it should not be deployed. Any issues that might result in major risk must be reported to appropriate parties.
###
[](https://developer-mina.gitbook.io/cisc-349/android-programming/code-of-ethics#id-2.6-perform-work-only-in-areas-of-competence)
2.6 Perform work only in areas of competence.
A computing professional is responsible for evaluating potential work assignments. This includes evaluating the work’s feasibility and advisability, and making a judgment about whether the work assignment is within the professional’s areas of competence. If at any time before or during the work assignment the professional identifies a lack of a necessary expertise, they must disclose this to the employer or client. The client or employer may decide to pursue the assignment with the professional after additional time to acquire the necessary competencies, to pursue the assignment with someone else who has the required expertise, or to forgo the assignment. A computing professional’s ethical judgment should be the final guide in deciding whether to work on the assignment.
###
[](https://developer-mina.gitbook.io/cisc-349/android-programming/code-of-ethics#id-2.7-foster-public-awareness-and-understanding-of-computing-related-technologies-and-their-consequenc)
2.7 Foster public awareness and understanding of computing, related technologies, and their consequences.
As appropriate to the context and one’s abilities, computing professionals should share technical knowledge with the public, foster awareness of computing, and encourage understanding of computing. These communications with the public should be clear, respectful, and welcoming. Important issues include the impacts of computer systems, their limitations, their vulnerabilities, and the opportunities that they present. Additionally, a computing professional should respectfully address inaccurate or misleading information related to computing.
###
[](https://developer-mina.gitbook.io/cisc-349/android-programming/code-of-ethics#id-2.8-access-computing-and-communication-resources-only-when-authorized-or-when-compelled-by-the-publi)
2.8 Access computing and communication resources only when authorized or when compelled by the public good.
Individuals and organizations have the right to restrict access to their systems and data so long as the restrictions are consistent with other principles in the Code. Consequently, computing professionals should not access another’s computer system, software, or data without a reasonable belief that such an action would be authorized or a compelling belief that it is consistent with the public good. A system being publicly accessible is not sufficient grounds on its own to imply authorization. Under exceptional circumstances a computing professional may use unauthorized access to disrupt or inhibit the functioning of malicious systems; extraordinary precautions must be taken in these instances to avoid harm to others.
###
[](https://developer-mina.gitbook.io/cisc-349/android-programming/code-of-ethics#id-2.9-design-and-implement-systems-that-are-robustly-and-usably-secure)
2.9 Design and implement systems that are robustly and usably secure.
Breaches of computer security cause harm. Robust security should be a primary consideration when designing and implementing systems. Computing professionals should perform due diligence to ensure the system functions as intended, and take appropriate action to secure resources against accidental and intentional misuse, modification, and denial of service. As threats can arise and change after a system is deployed, computing professionals should integrate mitigation techniques and policies, such as monitoring, patching, and vulnerability reporting. Computing professionals should also take steps to ensure parties affected by data breaches are notified in a timely and clear manner, providing appropriate guidance and remediation.
[](https://developer-mina.gitbook.io/cisc-349/android-programming/code-of-ethics#id-3.-professional-leadership-principles)
3\. Professional Leadership Principles
----------------------------------------------------------------------------------------------------------------------------------------------------------------------
Leadership may either be a formal designation or arise informally from influence over others. In this section, “leader” means any member of an organization or group who has influence, educational responsibilities, or managerial responsibilities. While these principles apply to all computing professionals, leaders bear a heightened responsibility to uphold and promote them, both within and through their organizations.
###
[](https://developer-mina.gitbook.io/cisc-349/android-programming/code-of-ethics#id-3.1-ensure-that-the-public-good-is-the-central-concern-during-all-professional-computing-work)
3.1 Ensure that the public good is the central concern during all professional computing work.
People—including users, customers, colleagues, and others affected directly or indirectly—should always be the central concern in computing. The public good should always be an explicit consideration when evaluating tasks associated with research, requirements analysis, design, implementation, testing, validation, deployment, maintenance, retirement, and disposal. Computing professionals should keep this focus no matter which methodologies or techniques they use in their practice.
###
[](https://developer-mina.gitbook.io/cisc-349/android-programming/code-of-ethics#id-3.2-articulate-encourage-acceptance-of-and-evaluate-fulfillment-of-social-responsibilities-by-member)
3.2 Articulate, encourage acceptance of, and evaluate fulfillment of social responsibilities by members of the organization or group.
Technical organizations and groups affect broader society, and their leaders should accept the associated responsibilities. Organizations—through procedures and attitudes oriented toward quality, transparency, and the welfare of society—reduce harm to the public and raise awareness of the influence of technology in our lives. Therefore, leaders should encourage full participation of computing professionals in meeting relevant social responsibilities and discourage tendencies to do otherwise.
###
[](https://developer-mina.gitbook.io/cisc-349/android-programming/code-of-ethics#id-3.3-manage-personnel-and-resources-to-enhance-the-quality-of-working-life)
3.3 Manage personnel and resources to enhance the quality of working life.
Leaders should ensure that they enhance, not degrade, the quality of working life. Leaders should consider the personal and professional development, accessibility requirements, physical safety, psychological well-being, and human dignity of all workers. Appropriate human-computer ergonomic standards should be used in the workplace.
###
[](https://developer-mina.gitbook.io/cisc-349/android-programming/code-of-ethics#id-3.4-articulate-apply-and-support-policies-and-processes-that-reflect-the-principles-of-the-code)
3.4 Articulate, apply, and support policies and processes that reflect the principles of the Code.
Leaders should pursue clearly defined organizational policies that are consistent with the Code and effectively communicate them to relevant stakeholders. In addition, leaders should encourage and reward compliance with those policies, and take appropriate action when policies are violated. Designing or implementing processes that deliberately or negligently violate, or tend to enable the violation of, the Code’s principles is ethically unacceptable.
###
[](https://developer-mina.gitbook.io/cisc-349/android-programming/code-of-ethics#id-3.5-create-opportunities-for-members-of-the-organization-or-group-to-grow-as-professionals)
3.5 Create opportunities for members of the organization or group to grow as professionals.
Educational opportunities are essential for all organization and group members. Leaders should ensure that opportunities are available to computing professionals to help them improve their knowledge and skills in professionalism, in the practice of ethics, and in their technical specialties. These opportunities should include experiences that familiarize computing professionals with the consequences and limitations of particular types of systems. Computing professionals should be fully aware of the dangers of oversimplified approaches, the improbability of anticipating every possible operating condition, the inevitability of software errors, the interactions of systems and their contexts, and other issues related to the complexity of their profession—and thus be confident in taking on responsibilities for the work that they do.
###
[](https://developer-mina.gitbook.io/cisc-349/android-programming/code-of-ethics#id-3.6-use-care-when-modifying-or-retiring-systems)
3.6 Use care when modifying or retiring systems.
Interface changes, the removal of features, and even software updates have an impact on the productivity of users and the quality of their work. Leaders should take care when changing or discontinuing support for system features on which people still depend. Leaders should thoroughly investigate viable alternatives to removing support for a legacy system. If these alternatives are unacceptably risky or impractical, the developer should assist stakeholders’ graceful migration from the system to an alternative. Users should be notified of the risks of continued use of the unsupported system long before support ends. Computing professionals should assist system users in monitoring the operational viability of their computing systems, and help them understand that timely replacement of inappropriate or outdated features or entire systems may be needed.
###
[](https://developer-mina.gitbook.io/cisc-349/android-programming/code-of-ethics#id-3.7-recognize-and-take-special-care-of-systems-that-become-integrated-into-the-infrastructure-of-soc)
3.7 Recognize and take special care of systems that become integrated into the infrastructure of society.
Support ethical conduct of all computing professionals. Even the simplest computer systems have the potential to impact all aspects of society when integrated with everyday activities such as commerce, travel, government, healthcare, and education. When organizations and groups develop systems that become an important part of the infrastructure of society, their leaders have an added responsibility to be good stewards of these systems. Part of that stewardship requires establishing policies for fair system access, including for those who may have been excluded. That stewardship also requires that computing professionals monitor the level of integration of their systems into the infrastructure of society. As the level of adoption changes, the ethical responsibilities of the organization or group are likely to change as well. Continual monitoring of how society is using a system will allow the organization or group to remain consistent with their ethical obligations outlined in the Code. When appropriate standards of care do not exist, computing professionals have a duty to ensure they are developed.
[](https://developer-mina.gitbook.io/cisc-349/android-programming/code-of-ethics#id-4.-compliance-with-the-code)
4\. Compliance with the Code
--------------------------------------------------------------------------------------------------------------------------------------------------
###
[](https://developer-mina.gitbook.io/cisc-349/android-programming/code-of-ethics#id-4.1-uphold-promote-and-respect-the-principles-of-the-code)
4.1 Uphold, promote, and respect the principles of the Code.
The future of computing depends on both technical and ethical excellence. Computing professionals should adhere to the principles of the Code and contribute to improving them. Computing professionals who recognize breaches of the Code should take actions to resolve the ethical issues they recognize, including, when reasonable, expressing their concern to the person or persons thought to be violating the Code.
###
[](https://developer-mina.gitbook.io/cisc-349/android-programming/code-of-ethics#id-4.2-treat-violations-of-the-code-as-inconsistent-with-membership-in-the-acm)
4.2 Treat violations of the Code as inconsistent with membership in the ACM.
Each ACM member should encourage and support adherence by all computing professionals regardless of ACM membership. ACM members who recognize a breach of the Code should consider reporting the violation to the ACM, which may result in remedial action as specified in the ACM’s Code of Ethics and Professional Conduct Enforcement Policy.
[Case Studies and Resource](https://www.acm.org/binaries/content/assets/about/acm-code-of-ethics-booklet.pdf)
[PreviousFlask](https://developer-mina.gitbook.io/cisc-349/android-programming/flask)
[NextMongoDB Code](https://developer-mina.gitbook.io/cisc-349/android-programming/mongodb-code)
Last updated 3 years ago
Was this helpful?
---
# Flask | CISC 349
A REST API (also known as RESTful API) is an application programming interface (API or web API) that conforms to the constraints of REST architectural style and allows for interaction with RESTful web services. REST stands for representational state transfer and was created by computer scientist Roy Fielding.
[](https://developer-mina.gitbook.io/cisc-349/android-programming/flask#whats-an-api)
What's an API?
---------------------------------------------------------------------------------------------------------
An API is a set of definitions and protocols for building and integrating application software. It’s sometimes referred to as a contract between an information provider and an information user—establishing the content required from the consumer (the call) and the content required by the producer (the response). For example, the API design for a weather service could specify that the user supplies a zip code and that the producer replies with a 2-part answer, the first being the high temperature, and the second being low.
[](https://developer-mina.gitbook.io/cisc-349/android-programming/flask#rest)
REST
---------------------------------------------------------------------------------------
REST is a set of architectural constraints, not a protocol or a standard. API developers can implement REST in a variety of ways.
When a client request is made via a RESTful API, it transfers a representation of the state of the resource to the requester or endpoint. This information, or representation, is delivered in one of several formats via HTTP: JSON (Javascript Object Notation), HTML, XLT, Python, PHP, or plain text. JSON is the most generally popular file format to use because, despite its name, it’s language-agnostic, as well as readable by both humans and machines.
Something else to keep in mind: Headers and parameters are also important in the HTTP methods of a RESTful API HTTP request, as they contain important identifier information as to the request's metadata, authorization, uniform resource identifier (URI), caching, cookies, and more. There are request headers and response headers, each with their own HTTP connection information and status codes.
In order for an API to be considered RESTful, it has to conform to these criteria:
* A client-server architecture made up of clients, servers, and resources, with requests managed through HTTP.
* **Stateless** client-server communication, meaning no client information is stored between **get** requests and each request is separate and unconnected.
* Cacheable data that streamlines client-server interactions.
[](https://developer-mina.gitbook.io/cisc-349/android-programming/flask#what-is-web-framework)
What is Web Framework?
--------------------------------------------------------------------------------------------------------------------------
Web Application Framework or simply Web Framework represents a collection of libraries and modules that enables a web application developer to write applications without having to bother about low-level details such as protocols, thread management etc.
###
[](https://developer-mina.gitbook.io/cisc-349/android-programming/flask#what-is-flask)
What is Flask?
Flask is a web application framework written in Python. It is developed by **Armin Ronacher**, who leads an international group of Python enthusiasts named Pocco. Flask is based on the Werkzeug WSGI toolkit and Jinja2 template engine. Both are Pocco projects.
###
[](https://developer-mina.gitbook.io/cisc-349/android-programming/flask#prerequisite)
Prerequisite
Python 2.6 or higher is usually required for the installation of Flask. Although Flask and its dependencies work well with Python 3 (Python 3.3 onwards), many Flask extensions do not support it properly. Hence, it is recommended that Flask should be installed on Python 2.7.
###
[](https://developer-mina.gitbook.io/cisc-349/android-programming/flask#install-flask)
Install Flask
Copy
pip install Flask
###
[](https://developer-mina.gitbook.io/cisc-349/android-programming/flask#application)
Application
In order to test **Flask** installation, type the following code in the editor as **Hello.py**
Copy
from flask import Flask
app = Flask(__name__)
@app.route('/')
def hello_world():
return 'Hello World’
if __name__ == '__main__':
app.run()pyth
the **run()** method of Flask class runs the application on the local development server.
Copy
app.run(host, port, debug)
All parameters are optional:
Param
Description
host
Hostname to listen on. Defaults to 127.0.0.1 (localhost). Set to ‘0.0.0.0’ to have the server available externally
port
default 5000
debug
Defaults to false. If set to true, provides a debug information
The above given **Python** script is executed from Python shell.
Copy
Python app.py
A message in Python shell informs you that
Copy
* Running on http://127.0.0.1:5000/ (Press CTRL+C to quit)
Open the above URL **(localhost:5000)** in the browser. **‘Hello World’** message will be displayed on it.
###
[](https://developer-mina.gitbook.io/cisc-349/android-programming/flask#request-in-flask)
Request in Flask
To gain access to the request object in Flask, you will need to import it from the Flask library:
Copy
from flask import request
Import Flask and the request object. And also establish routes for `query-example`, `form-example`, and `json-example`:
Copy
# import main Flask class and request object
from flask import Flask, request
# create the Flask app
app = Flask(__name__)
@app.route('/query-example')
def query_example():
return 'Query String Example'
@app.route('/form-example')
def form_example():
return 'Form Data Example'
@app.route('/json-example')
def json_example():
return 'JSON Object Example'
if __name__ == '__main__':
# run app in debug mode on port 5000
app.run(debug=True, port=5000)
###
[](https://developer-mina.gitbook.io/cisc-349/android-programming/flask#using-query-arguments)
Using Query Arguments
Let’s read the `language` key and display it as output.
Modify the `query-example` route in `app.py` with the following code:
Copy
@app.route('/query-example')
def query_example():
# if key doesn't exist, returns None
language = request.args.get('language')
return '''
The language value is: {}
'''.format(language)pyth
Then, run the app and navigate to the URL:
Copy
http://127.0.0.1:5000/query-example?language=Python
And if you want more, continue adding ampersands and key-value pairs.
Copy
@app.route('/query-example')
def query_example():
# if key doesn't exist, returns None
language = request.args.get('language')
# if key doesn't exist, returns a 400, bad request error
framework = request.args['framework']
# if key doesn't exist, returns None
website = request.args.get('website')
return '''
The language value is: {}
The framework value is: {}
The website value is: {}'''.format(language, framework, website)
Then, run the app and navigate to the URL:
Copy
http://127.0.0.1:5000/query-example?language=Python&framework=Flask&website=DigitalOcean
###
[](https://developer-mina.gitbook.io/cisc-349/android-programming/flask#get-and-post-request)
GET and POST Request
the HTTP protocol is the foundation of data communication on the world wide web. Different methods of data retrieval from specified URLs are defined in this protocol.
The following table summarizes different HTTP methods:
Method
Description
GET
Sends data in unencrypted form to the server. Most common method.
POST
Used to send HTML form data to server. Data received by POST method is not cached by server.
By default, the Flask route responds to the **GET** requests. However, this preference can be altered by providing methods argument to **route()** decorator. Modify the `form-example` route in `app.py` with the following code:
Copy
# allow both GET and POST requests
@app.route('/form-example', methods=['GET', 'POST'])
def form_example():
# handle the POST request
if request.method == 'POST':
language = request.form.get('language')
framework = request.form.get('framework')
return 'POST'
# otherwise handle the GET request
return ' GET'
Then, run the app and navigate to the URL:
Copy
http://127.0.0.1:5000/form-example
use [https://insomnia.rest/](https://insomnia.rest/)
to test your requests fisrt

###
[](https://developer-mina.gitbook.io/cisc-349/android-programming/flask#using-json-data)
Using JSON Data
JSON data is normally constructed by a process that calls the route.
An example JSON object looks like this:
Copy
{
"language" : "Python",
"framework" : "Flask",
"website" : "Scotch",
"version_info" : {
"python" : "3.9.0",
"flask" : "1.1.2"
},
"examples" : ["query", "form", "json"],
"boolean_test" : true
}
This structure can allow for much more complicated data to be passed as opposed to query strings and form data. In the example, you see nested JSON objects and an array of items. Flask can handle this format of data.
Modify the `form-example` route in `app.py` to accept POST requests and ignore other requests like GET:
Copy
@app.route('/json-example', methods=['POST'])
def json_example():
return 'JSON Object Example'
Now let’s work on the code to read the incoming JSON data.
First, let’s assign everything from the JSON object into a variable using `request.get_json()`.
`request.get_json()` converts the JSON object into Python data. Let’s assign the incoming request data to variables and return them by making the following changes to the `json-example` route:
Copy
# GET requests will be blocked
@app.route('/json-example', methods=['POST'])
def json_example():
request_data = request.get_json()
language = request_data['language']
framework = request_data['framework']
# two keys are needed because of the nested object
python_version = request_data['version_info']['python']
# an index is needed because of the array
example = request_data['examples'][0]
boolean_test = request_data['boolean_test']
return '''
The language value is: {}
The framework value is: {}
The Python version is: {}
The item at index 0 in the example list is: {}
The boolean value is: {}'''.format(language, framework,
python_version, example, boolean_test)
Note how you access elements that aren’t at the top level. `['version']['python']` is used because you are entering a nested object. And `['examples'][0]` is used to access the 0th index in the examples array.
If the JSON object sent with the request doesn’t have a key that is accessed in your view function, then the request will fail. If you don’t want it to fail when a key doesn’t exist, you’ll have to check if the key exists before trying to access it.
Copy
# GET requests will be blocked
@app.route('/json-example', methods=['POST'])
def json_example():
request_data = request.get_json()
boolean_test = None
if request_data:
if 'language' in request_data:
language = request_data['language']
if 'framework' in request_data:
framework = request_data['framework']
if 'version_info' in request_data:
if 'python' in request_data['version_info']:
python_version = request_data['version_info']['python']
if 'examples' in request_data:
if (type(request_data['examples']) == list) and (len(request_data['examples']) > 0):
example = request_data['examples'][0]
if 'boolean_test' in request_data:
boolean_test = request_data['boolean_test']
return '''
The language value is: {}
The framework value is: {}
The Python version is: {}
The item at index 0 in the example list is: {}
The boolean value is: {}'''.format(language,
framework, python_version, example, boolean_test)
Run the app and submit the example JSON request using Postman. In the response, you will get the following output:
Copy
OutputThe language value is: Python
The framework value is: Flask
The Python version is: 3.9
The item at index 0 in the example list is: query
The boolean value is: false
Resources:
* [https://www.redhat.com/en/topics/api/what-is-a-rest-api](https://www.redhat.com/en/topics/api/what-is-a-rest-api)
* [https://www.tutorialspoint.com/flask/flask\_routing.htm](https://www.tutorialspoint.com/flask/flask_routing.htm)
* [https://www.digitalocean.com/community/tutorials/processing-incoming-request-data-in-flask](https://www.digitalocean.com/community/tutorials/processing-incoming-request-data-in-flask)
[PreviousNetwork Image View](https://developer-mina.gitbook.io/cisc-349/android-programming/network-image-view)
[NextCode of Ethics](https://developer-mina.gitbook.io/cisc-349/android-programming/code-of-ethics)
Last updated 3 years ago
Was this helpful?
---
# MongoDB Code | CISC 349
Copy
import json
from matplotlib import collections
from app import app
from pymongo import MongoClient
from flask import request
from flask.json import jsonify
client = MongoClient('mongodb+srv://mina:@cluster0.g4yji.mongodb.net/myFirstDatabase?retryWrites=true&w=majority')
db = client["myFirstDatabase"]
# A welcome message to test our server
@app.route('/')
def index():
return "
Welcome to our server 123 !!
"
# Add user
@app.route('/add', methods=['POST'])
def add():
collection = db["customers"]
request_data = request.get_json()
name = request_data['name']
address = request_data['address']
data = { "name": name, "address": address }
_id = collection.insert_one(data)
return json.dumps({'id' : str(_id.inserted_id)})
# Select All users
@app.route('/all', methods=['POST'])
def all():
collection = db["customers"]
customers = list(collection.find())
# we need to convert _id to str.
return json.dumps(customers, default=str)
if __name__ == "__main__":
app.run(port=5000)
[PreviousCode of Ethics](https://developer-mina.gitbook.io/cisc-349/android-programming/code-of-ethics)
[NextUpload Images to Server](https://developer-mina.gitbook.io/cisc-349/android-programming/upload-images-to-server)
Last updated 3 years ago
Was this helpful?
Was this helpful?
---
# ASSIGNMENTS | CISC 349
[Java Introductory Exercise](https://developer-mina.gitbook.io/cisc-349/assignments/java-introductory-exercise)
[PreviousBottom Navigation Bar in Android](https://developer-mina.gitbook.io/cisc-349/android-programming/bottom-navigation-bar-in-android)
[NextJava Introductory Exercise](https://developer-mina.gitbook.io/cisc-349/assignments/java-introductory-exercise)
Last updated 3 years ago
Was this helpful?
Was this helpful?
---
# Fragments | CISC 349
A Fragment represents a reusable portion of your app's UI. A fragment defines and manages its own layout, has its own lifecycle, and can handle its own input events. Fragments cannot live on their own--they must be hosted by an activity or another fragment. The fragment’s view hierarchy becomes part of, or attaches to, the host’s view hierarchy.
[](https://developer-mina.gitbook.io/cisc-349/android-programming/fragments#modularity)
Modularity
-------------------------------------------------------------------------------------------------------
Fragments introduce modularity and reusability into your activity’s UI by allowing you to divide the UI into discrete chunks. Activities are an ideal place to put global elements around your app's user interface, such as a navigation drawer. Conversely, fragments are better suited to define and manage the UI of a single screen or portion of a screen.
Consider an app that responds to various screen sizes. On larger screens, the app should display a static navigation drawer and a list in a grid layout. On smaller screens, the app should display a bottom navigation bar and a list in a linear layout. Managing all of these variations in the activity can be unwieldy. Separating the navigation elements from the content can make this process more manageable. The activity is then responsible for displaying the correct navigation UI while the fragment displays the list with the proper layout.

[PreviousUpload Images to Server](https://developer-mina.gitbook.io/cisc-349/android-programming/upload-images-to-server)
[NextBottom Navigation Bar in Android](https://developer-mina.gitbook.io/cisc-349/android-programming/bottom-navigation-bar-in-android)
Last updated 4 years ago
Was this helpful?
Was this helpful?
---
# Java Introductory Exercise | CISC 349
Write a Java console application using the Java techniques and syntax that we have learned up to now.
####
[](https://developer-mina.gitbook.io/cisc-349/assignments/java-introductory-exercise#the-specifics-are)
The specifics are:
Write a program for a human resources department for use in tracking employee information. The system should maintain a list of employees and should support adding employees, deleting employees, and viewing employee details. Optionally, also implement update functionality to allow an existing employee's record to be modified.
The company in question has three kinds of employees, each with some unique information associated with them
1\. Salaried, Full Time **(A full-time salaried employee is required to work 45 hours a week and is paid an annual salary for this.)**
2\. Salaried, Part Time **(A part-time salaried employee is assigned a number of hours between 20 and 40 that they must work each week, and is paid an annual salary for this.)**
3\. Contractor **(Contract employees are not required to work any specific number of hours, and are paid in an hourly fashion.)**
In addition, for all employees, the system should include the following information:
1\. Full Name
2\. Job Title
3\. SSN
and any other information you think is worth including.
When you finish you need to submit a GitHub link to your assignmnet code folder in CANVAS, code for this assignment should be stored in _**assignments/assignment\_01**_
[PreviousASSIGNMENTS](https://developer-mina.gitbook.io/cisc-349/assignments)
[NextProgramming Project 01: Calculator](https://developer-mina.gitbook.io/cisc-349/programming-assignment/assignment-01-calculator)
Last updated 3 years ago
Was this helpful?
Was this helpful?
---
# Bottom Navigation Bar in Android | CISC 349
[](https://developer-mina.gitbook.io/cisc-349/android-programming/bottom-navigation-bar-in-android#usage)
Usage
--------------------------------------------------------------------------------------------------------------------
Bottom navigation bars display three to five destinations at the bottom of a screen. Each destination is represented by an icon and an optional text label. When a bottom navigation icon is tapped, the user is taken to the top-level navigation destination associated with that icon.

[](https://developer-mina.gitbook.io/cisc-349/android-programming/bottom-navigation-bar-in-android#when-to-use)
When to use
--------------------------------------------------------------------------------------------------------------------------------
**Bottom navigation should be used for:**
* Top-level destinations that need to be accessible from anywhere in the app
* Three to five destinations
* Mobile or tablet only
[](https://developer-mina.gitbook.io/cisc-349/android-programming/bottom-navigation-bar-in-android#anatomy)
Anatomy
------------------------------------------------------------------------------------------------------------------------

There are three destinations in this bottom navigation, each with an icon and text label.
1. Container
2. Inactive icon
3. Inactive text label
4. Active icon
5. Active text label
[](https://developer-mina.gitbook.io/cisc-349/android-programming/bottom-navigation-bar-in-android#icons)
Icons
--------------------------------------------------------------------------------------------------------------------
Bottom navigation destinations always include an icon. It’s best to pair icons with text labels, especially if the icon doesn’t have obvious meaning.

Icons paired with text labels in bottom navigation
[](https://developer-mina.gitbook.io/cisc-349/android-programming/bottom-navigation-bar-in-android#text-labels)
Text labels
--------------------------------------------------------------------------------------------------------------------------------
Text labels provide short, meaningful descriptions of bottom navigation destinations.

[](https://developer-mina.gitbook.io/cisc-349/android-programming/bottom-navigation-bar-in-android#implementation)
Implementation
--------------------------------------------------------------------------------------------------------------------------------------
[](https://developer-mina.gitbook.io/cisc-349/android-programming/bottom-navigation-bar-in-android#step-1-create-a-new-project)
Step 1: Create a new project
-----------------------------------------------------------------------------------------------------------------------------------------------------------------
create a new project with empty activity
[](https://developer-mina.gitbook.io/cisc-349/android-programming/bottom-navigation-bar-in-android#references)
References
------------------------------------------------------------------------------------------------------------------------------
[Material DesignMaterial Design](https://material.io/components/bottom-navigation#usage)
[PreviousFragments](https://developer-mina.gitbook.io/cisc-349/android-programming/fragments)
[NextASSIGNMENTS](https://developer-mina.gitbook.io/cisc-349/assignments)
Last updated 3 years ago
Was this helpful?
* [Usage](https://developer-mina.gitbook.io/cisc-349/android-programming/bottom-navigation-bar-in-android#usage)
* [When to use](https://developer-mina.gitbook.io/cisc-349/android-programming/bottom-navigation-bar-in-android#when-to-use)
* [Anatomy](https://developer-mina.gitbook.io/cisc-349/android-programming/bottom-navigation-bar-in-android#anatomy)
* [Icons](https://developer-mina.gitbook.io/cisc-349/android-programming/bottom-navigation-bar-in-android#icons)
* [Text labels](https://developer-mina.gitbook.io/cisc-349/android-programming/bottom-navigation-bar-in-android#text-labels)
* [Implementation](https://developer-mina.gitbook.io/cisc-349/android-programming/bottom-navigation-bar-in-android#implementation)
* [Step 1: Create a new project](https://developer-mina.gitbook.io/cisc-349/android-programming/bottom-navigation-bar-in-android#step-1-create-a-new-project)
* [References](https://developer-mina.gitbook.io/cisc-349/android-programming/bottom-navigation-bar-in-android#references)
Was this helpful?
---
# Upload Images to Server | CISC 349
Copy
package com.example.imageupload;
import androidx.appcompat.app.AppCompatActivity;
import android.os.Bundle;
import androidx.annotation.Nullable;
import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.drawable.BitmapDrawable;
import android.provider.MediaStore;
import android.util.Base64;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.Toast;
import com.android.volley.Request;
import com.android.volley.RequestQueue;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.JsonObjectRequest;
import com.android.volley.toolbox.Volley;
import com.orhanobut.logger.AndroidLogAdapter;
import com.orhanobut.logger.Logger;
import org.json.JSONException;
import org.json.JSONObject;
import java.io.ByteArrayOutputStream;
public class MainActivity extends AppCompatActivity {
private Context context;
static final int REQUEST_IMAGE_CAPTURE = 1;
static final String TAG = "MainActivity";
private ImageView imageView;
BitmapDrawable drawable = null;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
context = this;
Button capture = findViewById(R.id.take_image_from_camera);
imageView = findViewById(R.id.image_from_camera);
Logger.addLogAdapter(new AndroidLogAdapter());
capture.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Log.d(TAG,"in Click");
Intent cameraIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
startActivityForResult(cameraIntent, REQUEST_IMAGE_CAPTURE);
}
});
}
@Override
protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == REQUEST_IMAGE_CAPTURE) {
if (resultCode == RESULT_OK) {
assert data != null;
Bundle extras = data.getExtras();
Bitmap imageBitmap = (Bitmap) extras.get("data");
imageView.setImageBitmap(imageBitmap);
drawable = (BitmapDrawable) imageView.getDrawable();
final Bitmap bitmap = drawable.getBitmap();
uploadToServer(encodeToBase64(bitmap,Bitmap.CompressFormat.PNG,100));
} else if (resultCode == RESULT_CANCELED) {
Toast.makeText(this, "You cancelled the operation", Toast.LENGTH_SHORT).show();
}
}
}
public static String encodeToBase64(Bitmap image, Bitmap.CompressFormat compressFormat, int quality) {
ByteArrayOutputStream byteArrayOS = new ByteArrayOutputStream();
image.compress(compressFormat, quality, byteArrayOS);
return Base64.encodeToString(byteArrayOS.toByteArray(), Base64.DEFAULT);
}
private void uploadToServer(final String image) {
RequestQueue queue = Volley.newRequestQueue(context);
JSONObject json = new JSONObject();
try {
json.put("store", "amz");
json.put("image", image);
} catch (JSONException e) {
e.printStackTrace();
}
String url = "http://10.1.121.45:5000/image";
JsonObjectRequest jsonObjectRequest = new JsonObjectRequest(Request.Method.POST, url, json,
new Response.Listener() {
@Override
public void onResponse(JSONObject response) {
Log.d("Hello", "Response: " + response.toString());
Logger.d("hello");
Logger.json(String.valueOf(response));
Logger.e("error");
}
}, new Response.ErrorListener() {
@Override
public void onErrorResponse(VolleyError error) {
Log.d("Hello", error.getMessage());
}
});
queue.add(jsonObjectRequest);
}
}
[PreviousMongoDB Code](https://developer-mina.gitbook.io/cisc-349/android-programming/mongodb-code)
[NextFragments](https://developer-mina.gitbook.io/cisc-349/android-programming/fragments)
Last updated 3 years ago
Was this helpful?
Was this helpful?
Copy
Copy
Copy
import json
from matplotlib import collections
from app import app
from pymongo import MongoClient
from flask import request
from flask.json import jsonify
import sys
import base64
from datetime import datetime
client = MongoClient('mongodb+srv://mina:mina@cluster0.g4yji.mongodb.net/myFirstDatabase?retryWrites=true&w=majority')
db = client["myFirstDatabase"]
# A welcome message to test our server
@app.route('/')
def index():
return "
Welcome to our server 123 !!
"
# Add user
@app.route('/add', methods=['POST'])
def add():
collection = db["customers"]
request_data = request.get_json()
name = request_data['name']
address = request_data['address']
data = { "name": name, "address": address }
_id = collection.insert_one(data)
return json.dumps({'id' : str(_id.inserted_id)})
# Select All users
@app.route('/all', methods=['POST'])
def all():
collection = db["customers"]
customers = list(collection.find())
# we need to convert _id to str.
return json.dumps(customers, default=str)
@app.route("/image", methods=["GET", "POST"])
def fun():
print(request.is_json)
content = request.get_json()
print(content['store'])
image = content['image']
image_name = datetime.now().strftime("%Y_%m_%d-%I_%M_%S_%p") + ".png"
with open(image_name, "wb") as fh:
fh.write(base64.decodebytes(image.encode()))
data = {'a': 1, 'b': 2}
return jsonify(data)
if __name__ == "__main__":
app.run(host='10.1.121.45', port=5000)
Copy
---
# Programming Project 02: Dynamic List View | CISC 349
[](https://developer-mina.gitbook.io/cisc-349/assignment-02-dynamic-list-view#overview)
Overview
-----------------------------------------------------------------------------------------------------
For this homework, you will be building a **ListView** of **Spotify Holiday Songs**:
* The row layout should contain a thumbnail image and text fields.
* Thumbnail images should be asynchronously downloaded and cashed.
* You should use the **JSON** dataset from [https://setify-server.herokuapp.com/holiday\_songs\_spotify](https://setify-server.herokuapp.com/holiday_songs_spotify)
* Give yourself enough time to read and understand the dataset schema.
* Example of the **JSON** object:
Copy
[\
...\
{\
"acousticness":0.82,\
"album_img":"https://i.scdn.co/image/...",\
"album_name":"Merry Christmas",\
"artist_name":"Johnny Mathis",\
"danceability":0.195,\
"duration_ms":213107,\
"energy":0.348,\
"instrumentalness":0.0,\
"key":"A#",\
"key_mode":"A# major",\
"liveness":0.126,\
"loudness":-10.106,\
"mode":"major",\
"playlist_img":"https://mosaic.scdn.co/640/..",\
"playlist_name":"new_holiday_songs","\
speechiness":0.0332,\
"tempo":166.824,\
"time_signature":3,\
"track_name":"Silver Bells",\
"track_uri":"00IqwkT0PZhJ86PJajRCqk",\
"valence":0.262\
},\
...\
]
* In this homework you will only need the following elements:
* album\_img (String)
* album\_name (String)
* artist\_name (String)
* danceability (Double)
* duration\_ms (Integer) should be in Minutes and Seconds
* playlist\_img (String)
* you should design your Java class to **deserialize** the JSON accordingly.
* Here is an example of how the layout should look like:

Duration should be displayed in **Minutes** and **Seconds**
* you are ONLY allowed to use two external libraries:
* Android [Volley](https://developer.android.com/training/volley)
* [LruCache](https://developer.android.com/reference/android/util/LruCache)
Don't use **GSON** ( if you are not sure about an external library please email me and ask)
* you can redesign the layout as you want as long as you are keeping the basic information shown in the image above.
* in this homework you will need a **BaseAdapter** your adapter should be called **HolidaySongsAdapter**
* you will also need to create a POJO (Plain Old Java Object) class this class should be called **HolidaySongs.**
* your main activity should be called **MainActivity.**
####
[](https://developer-mina.gitbook.io/cisc-349/assignment-02-dynamic-list-view#click-event)
Click Event
* You need to set a click event to every row, when the user clicks on the raw it should start another activity called **ViewSongs** this activity should only display the related playlist image - found in the dataset - to the album, for example, if the user clicks on Merry Chrismas album they should see the name of the album and the image of the playlist (playlist might be the same for all albums)

####
[](https://developer-mina.gitbook.io/cisc-349/assignment-02-dynamic-list-view#grading)
**Grading**
* **Layout - 40%:** Does the application have a listview, adapter, required classes, activities, and layout? is dataset request implemented? Are they aligned well and work on different-sized devices?
* **Logic - 30%:** Does the list and the activity work as expected? Does it have all of the necessary functionality?
* **Design - 10%:** Did you customize the theme/style? Do the list and the display activity look good?
* **Code Style - 20%:** See the style section below
* **Extra Credit:**
* Make your list look better than the example. The customization has to be complicated and more than making small changes like simply changing the default theme colors or changing text size.
* Add more functionality to your listview (ie sort by a feature, add search functionality, circular image view, feel free to use any external library for any extra features you add to your application)
* GitHub submission (ex. commit messages are informative, using the correct directory for submission, etc.)
Extra points will be given based on the difficulty of your extra implementations.
**Code Style**
You will be graded on
1. Your code is easy to understand. This includes the naming of file, variable, and method names.
2. **Logic is not duplicated** (ie. Don't have separate methods that essentially do the same thing. Think about how you can write less code to accomplish more).
3. Are you using resource files (ie colors.xml and strings.xml)?
**Deliverables**
* Project GitHub link submitted to CANVAS page
* Readme.txt file for more instructions (use this file to describe your application and all extra features you add to your application)
[PreviousProgramming Project 01: Calculator](https://developer-mina.gitbook.io/cisc-349/programming-assignment/assignment-01-calculator)
[NextProgramming Project 03: HUstagram](https://developer-mina.gitbook.io/cisc-349/programming-project-03-hustagram)
Last updated 3 years ago
Was this helpful?
Was this helpful?
---
# Programming Project 03: HUstagram | CISC 349
This is your third assignment, you will receive step-by-step instructions on how to get this app working. We hope that through this assignment you will gain significant knowledge on how to create an interesting Android app for your final project.
**Please start early, and read through all the directions before starting**
Note that you don't have to follow all the steps exactly, however, you have to implement all the required functionality of the application.
In this assignment, We'll be making a very simple image uploading app. Broadly, a user would be able to take a picture with the phone's camera, have it uploaded to a server, and then view their images on their phone. Each picture will have some metadata associated with it: a comment, and the date it was taken.
**MongoDB Storage**
* you will use [https://cloud.mongodb.com/](https://cloud.mongodb.com/)
for data storage.
* for this assignmnet you only need one collection, call it **image** in this collection you need to store image name, comment and date time of image upload.
* you don't have to worry about edit and delete, you can do this manually and not through the application.
**Camera**
* you need to use the Android native camera API as discussed in class (if you need more information you can check the **Upload Images to Server page**)
* users can cancel image capture, if so, you need to notify them using a **Toast**.
* image thumbnail is acceptable.
* when the image is captured you need to display it to the user as shown in the first activity in the image below.
* comment and image are required for server upload.
**Server**
* use FLASK server as an endpoint for all requests and image uploads.
* FLASK can also be used as images static file serving, you can identify a static folder as follows in your app.py file, where **/images** directory is where you need to store your images:
In this project, you also need two activities to show all uploaded images, you can use a 3 X n grid to show images, make sure that the user can navigate back to the mainactivity where they can upload more images.
users can also click on any of the uploaded images and go to another activity to see the full image and the image comment as shown in the last mockup in the image below.

**Grading**
In general, if you've followed the instructions above, you'll earn the vast majority of the points below.
* **(35%) Logic** - does the app make sense? does it cover all the requirements?
* **(25%) Storage** - is MongoDB and FLASK used correctly? Do bitmaps get correctly encoded and stored on the server?
* **(20%) Camera** - is the camera functionality implemented correctly?
* **(10%) Design** - is the app well designed? Do views overlap?
* **(10%) Style** - are styles or logic duplicated? Is the flow of control intuitive?
**Deliverables**
* Project GitHub link submitted to CANVAS page.
* inside the project directory, you need to include your FLASK .py files in another directory called **server.**
* Readme.txt file for more instructions (use this file to describe your application and all extra features you add to your application)
[PreviousProgramming Project 02: Dynamic List View](https://developer-mina.gitbook.io/cisc-349/assignment-02-dynamic-list-view)
[NextProgramming Project 04: Machine Learning with TFLite](https://developer-mina.gitbook.io/cisc-349/programming-project-04-machine-learning-with-tflite)
Last updated 3 years ago
Was this helpful?
Was this helpful?
Copy
from flask import Flask
app = Flask(__name__,
static_folder='images')
---
# Programming Project 04: Machine Learning with TFLite | CISC 349
[PreviousProgramming Project 03: HUstagram](https://developer-mina.gitbook.io/cisc-349/programming-project-03-hustagram)
[NextProject Proposal](https://developer-mina.gitbook.io/cisc-349/final-project/project-proposal)
Last updated 3 years ago
Was this helpful?
Was this helpful?
---
# Programming Project 01: Calculator | CISC 349
[](https://developer-mina.gitbook.io/cisc-349/programming-assignment/assignment-01-calculator#overview)
Overview
---------------------------------------------------------------------------------------------------------------------
For this homework, you will be building a simple calculator with the following functions:
* A display row showing the result of the most recent operation.
* Plus and minus buttons that allow you to add/subtract a new number from the current total. When one of the two operation buttons is pressed, it should change colors and the other should remain the default color. Any button press that is not the currently selected operation (so a number or another operation) should reset its color (ex. if you press +, it should change color, and then go back to the default color when any other button is pressed).
* After an operation is pressed, if the next button is a digit then the new digit should be displayed, along with any digits that follow. As soon as either the equals button or another operation button is pressed, the display row should update with the new total.
* An equals button that immediately executes whatever operation was chosen previously, and display the updated total in the row, after a SHORT button press.
* The equals button should also CLEAR the row and operation after a LONG button press. After clearing the display, make a Toast notifying the user that the screen has been cleared.
####
[](https://developer-mina.gitbook.io/cisc-349/programming-assignment/assignment-01-calculator#see-gif-below-for-sample-functionality)
See gif below for sample functionality

####
[](https://developer-mina.gitbook.io/cisc-349/programming-assignment/assignment-01-calculator#tips)
Tips
* The current total should initialize and clear to 00 0
* All the operations are integer based, so no need for decimals or doubles.
* After an operation has been pressed, if a new number is inputted and a different operation is pressed, the screen should still update as if an equal was pressed in between. 4+5−4 + 5 -4+5− should end as 999 , and 4+5−10+4 + 5 - 10 +4+5−10+ should end as −1\-1−1 .
* Equals just has to execute the current operation once, it doesn't have to update anything upon later presses. For example, 1+2\=1 + 2 =1+2\= should display 1,2,1, 2, 1,2, and then 333 . 1+2\=\=1 + 2 = =1+2\== should also display 1,2,1, 2,1,2, and then 333 . 1+2\=+3\=1 + 2 = + 3 = 1+2\=+3\= should end up displaying 666 .
* Take out a calculator and check out how it functions!
####
[](https://developer-mina.gitbook.io/cisc-349/programming-assignment/assignment-01-calculator#grading)
**Grading**
* **Layout - 40%:** Does the calculator have all the needed buttons? Are they aligned well and work on different sized devices?
* **Logic - 30%:** Does the calculator work as expected? Does it have all of the necessary functionality?
* **Design - 10%:** Did you customize the theme/style? Does the calculator look good?
* **Code Style - 20%:** See the style section below
* **Extra Credit:**
* Make your calculator look better than the example. The customization has to be complicated and more than making small changes like simply changing the default theme colors or changing text size.
* Add more functionality to your calculator (eg. multiplication, division, decimal points, negative numbers, etc).
* GitHub submission (ex. commit messages are informative, using the correct directory for submission, etc.)
Extra points will be given based on the difficulty of your extra implementations.
**Code Style**
You will be graded on
1. Your code is easy to understand. This includes the naming of file, variable, and method names.
2. **Logic is not duplicated** (ie. Don't have 10 separate methods that essentially do the same thing. Think about how you can write less code to accomplish more).
3. Are you referring to strings via the strings.xml file?
**Deliverables**
* Project GitHub link submitted to CANVAS page
* Readme.txt file for more instructions
[PreviousJava Introductory Exercise](https://developer-mina.gitbook.io/cisc-349/assignments/java-introductory-exercise)
[NextProgramming Project 02: Dynamic List View](https://developer-mina.gitbook.io/cisc-349/assignment-02-dynamic-list-view)
Last updated 3 years ago
Was this helpful?
Was this helpful?
---
# Project Proposal | CISC 349
Your project writeup should be a PDF file that is a few pages long, turned in via canvas.
Please clearly explain the following. use the following sections and subsections for your final project proposal:
1. INTRODUCTION
1. Motivation
2. Proposed System
3. Related Work
2. STRUCTURED ANALYSIS
1. Use Case Diagram
2. Data Flow Diagram
3. System Design
1. User Interface
2. Prototyping
3. Entity Relationship Diagram
4. Class Diagram
5. Application Architecture Diagram
4. IMPLEMENTATION
1. Programming Languages
2. IDEs, Tools, and Technologies
3. Milestones and Scheduling
Please communicate clearly and format your proposal so it is easy to read.
**Application Architecture Diagram:** a high-level overview of the components of your system. e.g database, web server, mobile, web services, etc.
In this project, your architecture should include but not limited to all of the following:
* Android SDK (Java or Kotlin)
* Database ( MongoDB or MySQL)
* Web Service ( using FLASK)
Make sure you have enough data to demonstrate the functionality of your application. such as enough location data, multiple users, images, etc. If you don't demonstrate the functionality, you won't get credit for it.
At the end of the semester, you will be required to present a final explanation and demonstration to the instructor and fellow students. The details will be posted on the class schedule.
[PreviousProgramming Project 04: Machine Learning with TFLite](https://developer-mina.gitbook.io/cisc-349/programming-project-04-machine-learning-with-tflite)
Last updated 4 years ago
Was this helpful?
Was this helpful?
---
# Your First Android Application | CISC 349
The application you are going to create is called GeoQuiz. GeoQuiz tests the user’s knowledge of geography. The user presses TRUE or FALSE to answer the question on screen, and GeoQuiz provides instant feedback.

[](https://developer-mina.gitbook.io/cisc-349/android-programming#app-basics)
App Basics
---------------------------------------------------------------------------------------------
Your GeoQuiz application will consist of an activity and a layout:
* An activity is an instance of Activity, a class in the Android SDK. An activity is responsible for managing user interaction with a screen of information.
* A layout defines a set of UI objects and their positions on the screen. A layout is made up of definitions written in XML.
The relationship between QuizActivity and activity\_quiz.xml is diagrammed in the figure below

[](https://developer-mina.gitbook.io/cisc-349/android-programming#creating-an-android-project)
Creating an Android Project
-------------------------------------------------------------------------------------------------------------------------------
The first step is to create an Android project. An Android project contains the files that make up an application. To create a new project, first open Android Studio.

Creating a new application

Specifying device support

Choosing a type of activity _If your wizard looks very different, then the tools have changed more drastically. Do not panic._

[](https://developer-mina.gitbook.io/cisc-349/android-programming#navigating-in-android-studio)
Navigating in Android Studio
---------------------------------------------------------------------------------------------------------------------------------
The lefthand view is the project tool window. From here, you can view and manage the files associated with your project.

[](https://developer-mina.gitbook.io/cisc-349/android-programming#laying-out-the-ui)
Laying Out the UI
-----------------------------------------------------------------------------------------------------------
Copy
Widgets are the building blocks you use to compose a UI. A widget can show text or graphics, interact with the user, or arrange other widgets on the screen. Buttons, text input controls, and checkboxes are all types of widgets. The Android SDK includes many widgets that you can configure to get the appearance and behavior you want. Every widget is an instance of the View class or one of its subclasses (such as TextView or Button).
But these are not the widgets you are looking for. The interface for QuizActivity requires five widgets:
* a vertical LinearLayout
* a TextView
* a horizontal LinearLayout
* two Buttons

Copy
[](https://developer-mina.gitbook.io/cisc-349/android-programming#the-view-hierarchy)
The view hierarchy
-------------------------------------------------------------------------------------------------------------

[](https://developer-mina.gitbook.io/cisc-349/android-programming#widget-attributes)
Widget attributes
-----------------------------------------------------------------------------------------------------------
###
[](https://developer-mina.gitbook.io/cisc-349/android-programming#android-layout_width-and-android-layout_height)
android:layout\_width and android:layout\_height
The android:layout\_width and android:layout\_height attributes are required for almost every type of widget. They are typically set to either match\_parent or wrap\_content:
Attribute
Description
match\_parent
view will be as big as its parent
wrap\_content
view will be as big as its contents require
###
[](https://developer-mina.gitbook.io/cisc-349/android-programming#android-orientation)
android:orientation
The android:orientation attribute on the two LinearLayout widgets determines whether their children will appear vertically or horizontally. The root LinearLayout is vertical; its child LinearLayout is horizontal.
###
[](https://developer-mina.gitbook.io/cisc-349/android-programming#android-text)
android:text
The TextView and Button widgets have android:text attributes. This attribute tells the widget what text to display.
[](https://developer-mina.gitbook.io/cisc-349/android-programming#creating-string-resources)
Creating string resources
---------------------------------------------------------------------------------------------------------------------------
Open res/values/strings.xml. The template has already added one string resource for you. Add the three new strings that your layout requires.
Copy
GeoQuizCanberra is the capital of Australia.TrueFalse
[](https://developer-mina.gitbook.io/cisc-349/android-programming#previewing-the-layout)
Previewing the layout
-------------------------------------------------------------------------------------------------------------------
Your layout is now complete, and you can preview the layout in the graphical layout tool.

[](https://developer-mina.gitbook.io/cisc-349/android-programming#from-layout-xml-to-view-objects)
From Layout XML to View Objects
---------------------------------------------------------------------------------------------------------------------------------------
When you created the GeoQuiz project, a subclass of Activity named QuizActivity was created for you. The class file for QuizActivity is in the app/java directory of your project. The java directory is where the Java code for your project lives.
Copy
package com.bignerdranch.android.geoquiz;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
public class QuizActivity extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_quiz);
}
}
_Wondering what AppCompatActivity is? It is a subclass of Android’s Activity class that provides compatibility support for older versions of Android. You will learn much more about AppCompatActivity in Chapter 13_
The onCreate(Bundle) method is called when an instance of the activity subclass is created. When an activity is created, it needs a UI to manage. To get the activity its UI, you call the following Activity method:
Copy
public void setContentView(int layoutResID)
This method inflates a layout and puts it on screen.
[](https://developer-mina.gitbook.io/cisc-349/android-programming#resources-and-resource-ids)
Resources and resource IDs
-----------------------------------------------------------------------------------------------------------------------------
A layout is a resource. A resource is a piece of your application that is not code – things like image files, audio files, and XML files.
To access a resource in code, you use its resource ID. The resource ID for your layout is R.layout.activity\_quiz.
To generate a resource ID for a widget, you include an android:id attribute in the widget’s definition. In activity\_quiz.xml, add an android:id attribute to each button.
Copy
[](https://developer-mina.gitbook.io/cisc-349/android-programming#wiring-up-widgets)
Wiring Up Widgets
-----------------------------------------------------------------------------------------------------------
Now that the buttons have resource IDs, you can access them in QuizActivity. The first step is to add two member variables.
Copy
public class QuizActivity extends AppCompatActivity {
private Button mTrueButton;
private Button mFalseButton;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_quiz);
}
}
[](https://developer-mina.gitbook.io/cisc-349/android-programming#getting-references-to-widgets)
Getting references to widgets
-----------------------------------------------------------------------------------------------------------------------------------
In an activity, you can get a reference to an inflated widget by calling the following Activity method:
Copy
public View findViewById(int id)
This method accepts a resource ID of a widget and returns a View object.
Copy
public class QuizActivity extends AppCompatActivity {
private Button mTrueButton;
private Button mFalseButton;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_quiz);
mTrueButton = (Button) findViewById(R.id.true_button);
mFalseButton = (Button) findViewById(R.id.false_button);
}
}
[](https://developer-mina.gitbook.io/cisc-349/android-programming#setting-listeners)
Setting listeners
-----------------------------------------------------------------------------------------------------------
Android applications are typically event driven. Unlike command-line programs or scripts, event driven applications start and then wait for an event, such as the user pressing a button.
Start with the TRUE button. In QuizActivity.java, add the following code to onCreate(Bundle) just after the variable assignment.
Copy
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_quiz);
mTrueButton = (Button) findViewById(R.id.true_button);
mTrueButton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
// Does nothing yet, but soon!
}
});
mFalseButton = (Button) findViewById(R.id.false_button);
}
}
Set a similar listener for the FALSE button.
Copy
mTrueButton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
// Does nothing yet, but soon!
}
});
mFalseButton = (Button) findViewById(R.id.false_button);
mFalseButton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
// Does nothing yet, but soon!
}
});
}
[](https://developer-mina.gitbook.io/cisc-349/android-programming#making-toasts)
Making Toasts
---------------------------------------------------------------------------------------------------
Now to make the buttons fully armed and operational. You are going to have a press of each button trigger a pop-up message called a toast. A toast is a short message that informs the user of something but does not require any input or action.

First, return to strings.xml and add the string resources that your toasts will display.
Copy
GeoQuizCanberra is the capital of Australia.TrueFalseCorrect!Incorrect!
Copy
mTrueButton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Toast.makeText(QuizActivity.this,
R.string.correct_toast,
Toast.LENGTH_SHORT).show();
}
});
mFalseButton = (Button) findViewById(R.id.false_button);
mFalseButton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Toast.makeText(QuizActivity.this,
R.string.incorrect_toast,
Toast.LENGTH_SHORT).show();
}
});
[](https://developer-mina.gitbook.io/cisc-349/android-programming#challenge-customizing-the-toast)
Challenge: Customizing the Toast
----------------------------------------------------------------------------------------------------------------------------------------
In this challenge, you will customize the toast to show at the top instead of the bottom of the screen. To change how the toast is displayed, use the Toast class’s setGravity method.
[PreviousIntroduction to Java programming](https://developer-mina.gitbook.io/cisc-349/introduction-to-java/introduction-to-java-programming)
[NextAndroid and Model-View-Controller](https://developer-mina.gitbook.io/cisc-349/android-programming/android-and-model-view-controller)
Last updated 4 years ago
Was this helpful?
---
# Introduction to Java programming | CISC 349
[](https://developer-mina.gitbook.io/cisc-349/introduction-to-java#ide)
IDE
--------------------------------------------------------------------------------
In this tutorial, I will use [https://repl.it/](https://repl.it/)
as my IDE, and then we will move to Android Studio
[](https://developer-mina.gitbook.io/cisc-349/introduction-to-java#write-code)
Write Code
----------------------------------------------------------------------------------------------
when you create a new repl using the Java language you will see the following code:
Copy
class Main {
public static void main(String[] args) {
System.out.println("Hello world!");
}
}
run the previous code you should see "Hello world!" output on the right screen
[](https://developer-mina.gitbook.io/cisc-349/introduction-to-java#base-java-language-structure)
Base Java language structure
----------------------------------------------------------------------------------------------------------------------------------
###
[](https://developer-mina.gitbook.io/cisc-349/introduction-to-java#class)
Class
A class is a template that describes the data and behavior associated with an instance of that class.
A class is defined by the _class_ keyword and must start with a capital letter. The body of a class is surrounded by {}.
Copy
class MyClass {
}
The data associated with a class is stored in _variables_ the behavior associated with a class or object is implemented with _methods_.
A class is contained in a text file with the same name as the class plus the `.java` extension. It is also possible to define inner classes, these are classes defined within another class, in this case, you do not need a separate file for this class.
###
[](https://developer-mina.gitbook.io/cisc-349/introduction-to-java#object)
Object
An object is an instance of a class.
The object is the real element that has data and can perform actions. Each object is created based on the class definition. The class can be seen as the blueprint of an object, i.e., it describes how an object is created.
###
[](https://developer-mina.gitbook.io/cisc-349/introduction-to-java#inheritance)
Inheritance
A class can be derived from another class. In this case, this class is called a _subclass_. Another common phrase is that _a class extends another class._
Inheritance is an important pillar of OOP(Object Oriented Programming). It is the mechanism in java by which one class is allowed to inherit the features(fields and methods) of another class.
**Important terminology:**
* **Super Class:** The class whose features are inherited is known as a superclass(or a base class or a parent class).
* **Sub Class:** The class that inherits the other class is known as a subclass(or a derived class, extended class, or child class). The subclass can add its own fields and methods in addition to the superclass fields and methods.
* **Reusability:** Inheritance supports the concept of “reusability”, i.e. when we want to create a new class and there is already a class that includes some of the code that we want, we can derive our new class from the existing class. By doing this, we are reusing the fields and methods of the existing class.
**Example:** In **the** below example of inheritance, class Bicycle is a base class, class MountainBike is a derived class that extends Bicycle class and class Test is a driver class to run the program.
Copy
//Java program to illustrate the
// concept of inheritance
// base class
class Bicycle
{
// the Bicycle class has two fields
public int gear;
public int speed;
// the Bicycle class has one constructor
public Bicycle(int gear, int speed)
{
this.gear = gear;
this.speed = speed;
}
// the Bicycle class has three methods
public void applyBrake(int decrement)
{
speed -= decrement;
}
public void speedUp(int increment)
{
speed += increment;
}
// toString() method to print info of Bicycle
public String toString()
{
return("No of gears are "+gear
+"\n"
+ "speed of bicycle is "+speed);
}
}
// derived class
class MountainBike extends Bicycle
{
// the MountainBike subclass adds one more field
public int seatHeight;
// the MountainBike subclass has one constructor
public MountainBike(int gear,int speed,
int startHeight)
{
// invoking base-class(Bicycle) constructor
super(gear, speed);
seatHeight = startHeight;
}
// the MountainBike subclass adds one more method
public void setHeight(int newValue)
{
seatHeight = newValue;
}
// overriding toString() method
// of Bicycle to print more info
@Override
public String toString()
{
return (super.toString()+
"\nseat height is "+seatHeight);
}
}
// driver class
public class Test
{
public static void main(String args[])
{
MountainBike mb = new MountainBike(3, 100, 25);
System.out.println(mb.toString());
}
}
Copy
No of gears are 3
speed of bicycle is 100
seat height is 25
**How to use inheritance in Java**
The keyword used for inheritance is **extends**
Copy
class derived-class extends base-class
{
//methods and fields
}
**Types of Inheritance in Java**
Below are the different types of inheritance which are supported by Java.
**Single Inheritance:** In single inheritance, subclasses inherit the features of one superclass.
Copy
class one
{
public void print_geek()
{
System.out.println("Geeks");
}
}
class two extends one
{
public void print_for()
{
System.out.println("for");
}
}
// Driver class
public class Main
{
public static void main(String[] args)
{
two g = new two();
g.print_geek();
g.print_for();
g.print_geek();
}
}
Copy
Geeks
for
Geeks
###
[](https://developer-mina.gitbook.io/cisc-349/introduction-to-java#java_interfaces)
Java interfaces
####
[](https://developer-mina.gitbook.io/cisc-349/introduction-to-java#javadef_interface)
What is an interface in Java?
An _interface_ is a type similar to a class and is defined via the `interface` keyword. Interfaces are used to define the common behavior of implementing classes. If two classes implement the same interface, other code that works on the interface level can use objects of both classes.
Like a class an interface defines methods. Classes can implement one or several interfaces. A class that implements an interface must provide an implementation for all abstract methods defined in the interface.
Copy
public interface MyInterface {
// constant definition
String URL = "https://www.vogella.com/";
// public abstract methods
void test();
void write(String s);
// default method
default String reserveString(String s){
return new StringBuilder(s).reverse().toString();
}
}
####
[](https://developer-mina.gitbook.io/cisc-349/introduction-to-java#javadef_interfaceimplementing)
Implementing Interfaces
Copy
public class MyClassImpl implements MyInterface {
@Override
public void test() {
}
@Override
public void write(String s) {
}
public static void main(String[] args) {
MyClassImpl impl = new MyClassImpl();
System.out.println(impl.reserveString("Lars Vogel"));
}
}
####
[](https://developer-mina.gitbook.io/cisc-349/introduction-to-java#reference)
Reference:
[Inheritance in Java - GeeksforGeeksGeeksforGeeks](https://www.geeksforgeeks.org/inheritance-in-java/)
[Introduction to Java programming - Tutorialwww.vogella.com](https://www.vogella.com/tutorials/JavaIntroduction/article.html)
[PreviousGitHub Instructions](https://developer-mina.gitbook.io/cisc-349/github-instructions)
[NextYour First Android Application](https://developer-mina.gitbook.io/cisc-349/android-programming/your-first-android-application)
Last updated 4 years ago
Was this helpful?
---
# Programming Project 01: Calculator | CISC 349
[](https://developer-mina.gitbook.io/cisc-349/programming-assignment#overview)
Overview
--------------------------------------------------------------------------------------------
For this homework, you will be building a simple calculator with the following functions:
* A display row showing the result of the most recent operation.
* Plus and minus buttons that allow you to add/subtract a new number from the current total. When one of the two operation buttons is pressed, it should change colors and the other should remain the default color. Any button press that is not the currently selected operation (so a number or another operation) should reset its color (ex. if you press +, it should change color, and then go back to the default color when any other button is pressed).
* After an operation is pressed, if the next button is a digit then the new digit should be displayed, along with any digits that follow. As soon as either the equals button or another operation button is pressed, the display row should update with the new total.
* An equals button that immediately executes whatever operation was chosen previously, and display the updated total in the row, after a SHORT button press.
* The equals button should also CLEAR the row and operation after a LONG button press. After clearing the display, make a Toast notifying the user that the screen has been cleared.
####
[](https://developer-mina.gitbook.io/cisc-349/programming-assignment#see-gif-below-for-sample-functionality)
See gif below for sample functionality

####
[](https://developer-mina.gitbook.io/cisc-349/programming-assignment#tips)
Tips
* The current total should initialize and clear to 00 0
* All the operations are integer based, so no need for decimals or doubles.
* After an operation has been pressed, if a new number is inputted and a different operation is pressed, the screen should still update as if an equal was pressed in between. 4+5−4 + 5 -4+5− should end as 999 , and 4+5−10+4 + 5 - 10 +4+5−10+ should end as −1\-1−1 .
* Equals just has to execute the current operation once, it doesn't have to update anything upon later presses. For example, 1+2\=1 + 2 =1+2\= should display 1,2,1, 2, 1,2, and then 333 . 1+2\=\=1 + 2 = =1+2\== should also display 1,2,1, 2,1,2, and then 333 . 1+2\=+3\=1 + 2 = + 3 = 1+2\=+3\= should end up displaying 666 .
* Take out a calculator and check out how it functions!
####
[](https://developer-mina.gitbook.io/cisc-349/programming-assignment#grading)
**Grading**
* **Layout - 40%:** Does the calculator have all the needed buttons? Are they aligned well and work on different sized devices?
* **Logic - 30%:** Does the calculator work as expected? Does it have all of the necessary functionality?
* **Design - 10%:** Did you customize the theme/style? Does the calculator look good?
* **Code Style - 20%:** See the style section below
* **Extra Credit:**
* Make your calculator look better than the example. The customization has to be complicated and more than making small changes like simply changing the default theme colors or changing text size.
* Add more functionality to your calculator (eg. multiplication, division, decimal points, negative numbers, etc).
* GitHub submission (ex. commit messages are informative, using the correct directory for submission, etc.)
Extra points will be given based on the difficulty of your extra implementations.
**Code Style**
You will be graded on
1. Your code is easy to understand. This includes the naming of file, variable, and method names.
2. **Logic is not duplicated** (ie. Don't have 10 separate methods that essentially do the same thing. Think about how you can write less code to accomplish more).
3. Are you referring to strings via the strings.xml file?
**Deliverables**
* Project GitHub link submitted to CANVAS page
* Readme.txt file for more instructions
[PreviousJava Introductory Exercise](https://developer-mina.gitbook.io/cisc-349/assignments/java-introductory-exercise)
[NextProgramming Project 02: Dynamic List View](https://developer-mina.gitbook.io/cisc-349/assignment-02-dynamic-list-view)
Last updated 3 years ago
Was this helpful?
---
# Project Proposal | CISC 349
Your project writeup should be a PDF file that is a few pages long, turned in via canvas.
Please clearly explain the following. use the following sections and subsections for your final project proposal:
1. INTRODUCTION
1. Motivation
2. Proposed System
3. Related Work
2. STRUCTURED ANALYSIS
1. Use Case Diagram
2. Data Flow Diagram
3. System Design
1. User Interface
2. Prototyping
3. Entity Relationship Diagram
4. Class Diagram
5. Application Architecture Diagram
4. IMPLEMENTATION
1. Programming Languages
2. IDEs, Tools, and Technologies
3. Milestones and Scheduling
Please communicate clearly and format your proposal so it is easy to read.
**Application Architecture Diagram:** a high-level overview of the components of your system. e.g database, web server, mobile, web services, etc.
In this project, your architecture should include but not limited to all of the following:
* Android SDK (Java or Kotlin)
* Database ( MongoDB or MySQL)
* Web Service ( using FLASK)
Make sure you have enough data to demonstrate the functionality of your application. such as enough location data, multiple users, images, etc. If you don't demonstrate the functionality, you won't get credit for it.
At the end of the semester, you will be required to present a final explanation and demonstration to the instructor and fellow students. The details will be posted on the class schedule.
[PreviousProgramming Project 04: Machine Learning with TFLite](https://developer-mina.gitbook.io/cisc-349/programming-project-04-machine-learning-with-tflite)
Last updated 4 years ago
Was this helpful?
---