<commit_before>---
layout: post
cover: 'assets/images/crashing_waves.jpg'
title: Introduction to Android
date:   2016-07-16 10:18:00
tags: general programming
subclass: 'post tag-test tag-content'
categories: 'casper'
navigation: True
logo: 'assets/images/logo.png'
---

This introduction serves as a reference guide for people new to developing Android applications. 

### Notable Files

###### app/build.gradle

Gradle build scripts are a DSL, they come with a top-level build file and build files for each module.

###### app/src/main/AndroidManifest.xml

This file contains metadata that describes our application ot the OS. File is always named AndroidManifest.xml and lives in the root directory of our project.

When creating new activities, we need to add it to our AndroidManifest file so our OS can access it. The dot at the start of this attribute’s value tells the OS that this activity’s class is in the package specified in the package attribute in the manifest element at the top of the file.

````xml
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.shawnklein.carpk.cloudorder" >
    <activity android:name=".NewActivity"
              android:label="@string/app_name" />
</manifest>
````
This file also tells the OS which Activity is the launcher activity, that is the activity that first starts when the OS calls on the application. The manifest declaration specifies this with `intent-filter` element (pg109).

###### app/src/main/java/tld/company/user/project/*.java

These files hold the code that preforms the functionality we need our app to accomplish.

###### app/src/main/res/layout/*.xml

These files hold widgets that interprept what our activities will look like.

###### app/build/generated/source/r/debug/tld/company/user/project/R.java

The `R.java` file is our resources file.

````java
public static final class string {
    public static final int abc_action_bar_home_description=0x7f060000;
    public static final int abc_action_bar_home_description_format=0x7f060001;
    public static final int abc_action_bar_home_subtitle_description_format=0x7f060002;
    public static final int abc_action_bar_up_description=0x7f060003;
}
````    

### Activities
An activity is an instance of `Activity` and is responsible for managing user interactions with a screen of information.

Inside an activity are widgets: can show text, graphics, interact with user, or arrange other widgets on screen. buttons, text input, check boxes.

`@Override` annotation ensures the class actually has the method you are attempting to override. The compiler will notify you if it does not possess this class.

A `@TargetApi(11)` annotation is used to suppress build errors from Lint. It is used to say that the below method will only be referenced by an OS version that is passed in as an argument. In our case, version `11`, Honeycomb, instead of the version what is declared in our manifest.

We start an activity by using the `startActivity` method. `public void startActivity(Intent intent)` This sends a call to a part of the OS called the 'ActivityManager', which creates `Activity` instances and calls `onCreate()`. An intent is an object that a component can use to communicate with the OS, which are activities, services, broadcast recievers, and content providers. `public Intent(Context packageContext, Class class)` the Class specifies which activity the ActivityManager should start, Context tells which package the Class object can be found in. We can add additional information to the intent by calling `public Intent putExtra(String name, boolean value)`, this allows us to pass information between our current activity and the one will will be creating.

````java
// MainActivity.java
Intent i = new Intent(MainActivity.this, SideActivity.class);
i.putExtra(SideActivity.MY_EXTRA_VALUE, myValue);
startActivity(i);
// SideActivity.java
public static final String MY_EXTRA_VALUE = "net.ShawnKlein.testapp";
mMyValue = getIntent().getBooleanExtra(MY_EXTRA_VALUE, false);
````

The ActivityManager will then check the package's manifest for a declaration with the same name as the specified Class. If no declaration is found, it will respond with a ActivityNotFoundException. We call `Activity.getIntent()` to return the intent that started this activity and `public boolean getBooleanExtra(String name, boolean defaultValue)` to pull the information out of the intent. It is also important to note that we should define keys for extras on the activities that retrieve and use them, we do this with `public static final String MY_EXTRA_VALUE = "net.ShawnKlein.testapp";`.

The above example is a an _explicit intent_, when an activity wants to start an activity in another application, it would be considered and _implicit intent_.

For our child activity to return data back to our main activity, we will use `public void startActivityForResult(Intent intent, int requestCode)` instead of `startActivity(i)` and `protected void onActivityResult(int requestCode, int resultCode, Intent data)` to actually retrive the returning data. The Child activity will use `public final void setResult(int resultCode)` or `public final void setResult(int resultCode, Intent data)`, if no result code is set, and the parent expects a return, the OS will send RESULT_CANCELED as the `resultCode`. 

````java
// SideActivity.java
public static final String RETURNING_DATA =
    "net.shawnklein.testapp.data_result"
private void setReturningDataResult(boolen myValue) {
    Intent data = new Intent();
    data.putExtra(RETURNING_DATA, myValue);
    setResult(RESULT_OK, data);
}
// MainActivity.java
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
    myVariable = data.getBooleanExtra(Sideactivity.RETURNING_DATA, false);
}
````

To retrieve our returing data, we use `protected void onActivityResult()`

### Fragments

Is a controller object that an activity can deputize to perform tasks. Such as managing a user interface. To set our class to use a fragment, we replace `Activity` with `FragmentActivity`

````java
public class TestActivity extends FragmentActivity {
  ....
}
````

Our fragment class does not inflate using the `onCreate()` such as avtvity would, it inflates using `onCreateView()`.

````java
public class TestFragment extends Fragment {
  // ....
  @Override
  public View onCreateView(LayoutInflater inflater, ViewGroup parent, Bundle savedInstanceState) {
    View v = inflater.inlfate(R.layout.fragment_test, parent, false);
    return v;
  }
}
````


Now that we have created our fragment, we need 2 things to host a UI fragment, a spot in the layout for the fragment's view, and manage the lifecycle of the fragment. Fragments lifecycle are called by the hosting activity, instead of the OS. You can add a fragment to either the hosting activity's _layout_ or _code_.

###### Layout

A layout fragment is simple, but inflexable. We hard code the fragment and its view to the activity's view and cannot swap out the fragment during the activity's lifetime.



###### Code

A code fragment gives us more control of how our fragment will interact with our activity. It will allow us to determine when to add the fragment to the host activity, remove it, replace it with another, and add the initial fragment back again.<commit_msg>edit sections regarding fragments in Intro to Android<commit_after>---
layout: post
cover: 'assets/images/crashing_waves.jpg'
title: Introduction to Android
date:   2016-07-16 10:18:00
tags: general programming
subclass: 'post tag-test tag-content'
categories: 'casper'
navigation: True
logo: 'assets/images/logo.png'
---

This introduction serves as a reference guide for people new to developing Android applications. 

### Notable Files

###### app/build.gradle

Gradle build scripts are a DSL, they come with a top-level build file and build files for each module.

###### app/src/main/AndroidManifest.xml

This file contains metadata that describes our application ot the OS. File is always named AndroidManifest.xml and lives in the root directory of our project.

When creating new activities, we need to add it to our AndroidManifest file so our OS can access it. The dot at the start of this attribute’s value tells the OS that this activity’s class is in the package specified in the package attribute in the manifest element at the top of the file.

````xml
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.shawnklein.carpk.cloudorder" >
    <activity android:name=".NewActivity"
              android:label="@string/app_name" />
</manifest>
````
This file also tells the OS which Activity is the launcher activity, that is the activity that first starts when the OS calls on the application. The manifest declaration specifies this with `intent-filter` element (pg109).

###### app/src/main/java/tld/company/user/project/*.java

These files hold the code that preforms the functionality we need our app to accomplish.

###### app/src/main/res/layout/*.xml

These files hold widgets that interprept what our activities will look like.

###### app/build/generated/source/r/debug/tld/company/user/project/R.java

The `R.java` file is our resources file.

````java
public static final class string {
    public static final int abc_action_bar_home_description=0x7f060000;
    public static final int abc_action_bar_home_description_format=0x7f060001;
    public static final int abc_action_bar_home_subtitle_description_format=0x7f060002;
    public static final int abc_action_bar_up_description=0x7f060003;
}
````    

### Activities
An activity is an instance of `Activity` and is responsible for managing user interactions with a screen of information.

Inside an activity are widgets: can show text, graphics, interact with user, or arrange other widgets on screen. buttons, text input, check boxes.

`@Override` annotation ensures the class actually has the method you are attempting to override. The compiler will notify you if it does not possess this class.

A `@TargetApi(11)` annotation is used to suppress build errors from Lint. It is used to say that the below method will only be referenced by an OS version that is passed in as an argument. In our case, version `11`, Honeycomb, instead of the version what is declared in our manifest.

We start an activity by using the `startActivity` method. `public void startActivity(Intent intent)` This sends a call to a part of the OS called the 'ActivityManager', which creates `Activity` instances and calls `onCreate()`. An intent is an object that a component can use to communicate with the OS, which are activities, services, broadcast recievers, and content providers. `public Intent(Context packageContext, Class class)` the Class specifies which activity the ActivityManager should start, Context tells which package the Class object can be found in. We can add additional information to the intent by calling `public Intent putExtra(String name, boolean value)`, this allows us to pass information between our current activity and the one will will be creating.

````java
// MainActivity.java
Intent i = new Intent(MainActivity.this, SideActivity.class);
i.putExtra(SideActivity.MY_EXTRA_VALUE, myValue);
startActivity(i);
// SideActivity.java
public static final String MY_EXTRA_VALUE = "net.ShawnKlein.testapp";
mMyValue = getIntent().getBooleanExtra(MY_EXTRA_VALUE, false);
````

The ActivityManager will then check the package's manifest for a declaration with the same name as the specified Class. If no declaration is found, it will respond with a ActivityNotFoundException. We call `Activity.getIntent()` to return the intent that started this activity and `public boolean getBooleanExtra(String name, boolean defaultValue)` to pull the information out of the intent. It is also important to note that we should define keys for extras on the activities that retrieve and use them, we do this with `public static final String MY_EXTRA_VALUE = "net.ShawnKlein.testapp";`.

The above example is a an _explicit intent_, when an activity wants to start an activity in another application, it would be considered and _implicit intent_.

For our child activity to return data back to our main activity, we will use `public void startActivityForResult(Intent intent, int requestCode)` instead of `startActivity(i)` and `protected void onActivityResult(int requestCode, int resultCode, Intent data)` to actually retrive the returning data. The Child activity will use `public final void setResult(int resultCode)` or `public final void setResult(int resultCode, Intent data)`, if no result code is set, and the parent expects a return, the OS will send RESULT_CANCELED as the `resultCode`. 

````java
// SideActivity.java
public static final String RETURNING_DATA =
    "net.shawnklein.testapp.data_result"
private void setReturningDataResult(boolen myValue) {
    Intent data = new Intent();
    data.putExtra(RETURNING_DATA, myValue);
    setResult(RESULT_OK, data);
}
// MainActivity.java
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
    myVariable = data.getBooleanExtra(Sideactivity.RETURNING_DATA, false);
}
````

To retrieve our returing data, we use `protected void onActivityResult()`

### Fragments

Is a controller object that an activity can deputize to perform tasks. Such as managing a user interface. To set our class to use a fragment, we replace `Activity` with `FragmentActivity`

````java
public class TestActivity extends FragmentActivity {
  ....
}
````

Our fragment class does not inflate using the `onCreate()` such as activity would, it inflates using the `onCreateView()` method. and we explicitly inflate the the fragments view by calling `LayoutInflater.inflate()`. The first parameter is the resource ID, second is the parent's view, and third tells the inflater whether to add the inflated view to the parent.

````java
public class TestFragment extends Fragment {
  // ....
  @Override
  public View onCreateView(LayoutInflater inflater, ViewGroup parent, Bundle savedInstanceState) {
    View v = inflater.inlfate(R.layout.fragment_test, parent, false);
    return v;
  }
}
````


Now that we have created our fragment, we need 2 things to host a UI fragment, a spot in the layout for the fragment's view, and manage the lifecycle of the fragment. Fragments lifecycle are called by the hosting activity, instead of the OS. You can add a fragment to either the hosting activity's _layout_ or _code_.

###### Layout

A layout fragment is simple, but inflexable. We hard code the fragment and its view to the activity's view and cannot swap out the fragment during the activity's lifetime.



###### Code

A code fragment gives us more control of how our fragment will interact with our activity. It will allow us to determine when to add the fragment to the host activity, remove it, replace it with another, and add the initial fragment back again.
{'fraction_non_alphanumeric': 0.07008410092110533, 'fraction_numerical': 0.007208650380456548, 'mean_word_length': 4.829961089494163, 'pattern_counts': {'":': 0, '<': 9, '<?xml version=': 0, '>': 9, 'https://': 0, 'lorem ipsum': 0, 'www.': 0, 'xml': 10}, 'pii_count': 0, 'substrings_counts': 0, 'word_list_counts': {'cursed_substrings.json': 0, 'profanity_word_list.json': 0, 'sexual_word_list.json': 0, 'zh_pornsignals.json': 0}}
{'dir': 'git-commits-cleaned', 'id': '789', 'n_tokens_mistral': 3935, 'n_tokens_neox': 3757, 'n_words': 1935}