Android Development: How to use more than one activity in your App?

In most of your Apps you want to use more than one activity. But how can you use for an example to activities in one App? The solution is very simple, you create a second activity in your project. The next step is to make the two activities talk to each other. Intents are the solution.

This tutorial shows you how you create a second activity in your project and make them talk to each other with intents.

But before we begin with the programming. We have to cover a little bit of theory. An activity in Android is a single thing which covers one thing your user can work with or do something with it. To make a task with your App you have to add multiple activities together.

Now we can begin with our App. This App covers to easy activities. Both of them have a text field and a simple button.

Building your App

Create your project

First create the project in Android Studio:

CreateAndroidProject

Select the target. In this case I used API level 23 in most cases it is better to use a lower level. So your App will run on most devices. For an indication of the distribution of the specific Android versions you can have a look at this site http://developer.android.com/about/dashboards/index.html

CreateProjectTargetAndroid

Choose the Blank Activity

ChooseActivityAndroid

Name the activity. In this case I named the activity FirstActivity

CustomizeActivity

Customize your first activity

Now it’s time to add the text field and the button to your first activity.

Open the file content_first.xml to edit it. In this file we will add a button and the text field. After you opened the file you will see this code:

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:paddingBottom="@dimen/activity_vertical_margin"
    android:paddingLeft="@dimen/activity_horizontal_margin"
    android:paddingRight="@dimen/activity_horizontal_margin"
    android:paddingTop="@dimen/activity_vertical_margin"
    app:layout_behavior="@string/appbar_scrolling_view_behavior"
    tools:context="com.frogtag.bef.twoactivities.FirstActivity"
    tools:showIn="@layout/activity_first">

    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Hello World!" />
</RelativeLayout>

In this code there is already a TextView defined. This TextView is created automatically by Android Studio. We will delete this TextView.

After we deleted the TextView we add this code to the file before the tag </RelativeLayout>

<TextView
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:text="New Text"
    android:id="@+id/textViewIntent1"
    android:layout_alignParentTop="true"
    android:layout_alignParentStart="true" />

<Button
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:text="New Button"
    android:id="@+id/buttonIntent1"
    android:layout_below="@+id/textViewIntent1"
    android:layout_alignParentStart="true"
    android:layout_marginTop="30dp"
    android:onClick="onSendText" />

At this stage our button has no function. To add a function to the button we add this line of code to the button:

android:onClick="onSendText"

In a later stage we will create the method onSendText() in the activity. But before we will do this first we create our second activity. Also for this Android Studio will help us with a wizard. To create a new activity, choose File -> New -> Activity. In the wizard choose Blank Activity. Fill in all the neccessary data and click on Finish. I named the Activity SecondActivity. In the backgound Android Studio not only created the new Activity it also makes some changes in the App. The new Activity was also added in the AndroidManifest file. In this file every Activity has to be declared.

SecondActivity

Now we make some changes to our code. Open the file FirstActivity.java. Before we make any changes to the file it should look like following:

package com.frogtag.bef.twoactivities;

import android.content.Intent;
import android.os.Bundle;
import android.support.design.widget.FloatingActionButton;
import android.support.design.widget.Snackbar;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.view.View;
import android.view.Menu;
import android.view.MenuItem;

public class FirstActivity extends AppCompatActivity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_first);
        Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
        setSupportActionBar(toolbar);

        FloatingActionButton fab = (FloatingActionButton) findViewById(R.id.fab);
        fab.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                Snackbar.make(view, "Replace with your own action", Snackbar.LENGTH_LONG)
                        .setAction("Action", null).show();
            }
        });
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(R.menu.menu_first, menu);
        return true;
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        // Handle action bar item clicks here. The action bar will
        // automatically handle clicks on the Home/Up button, so long
        // as you specify a parent activity in AndroidManifest.xml.
        int id = item.getItemId();

        //noinspection SimplifiableIfStatement
        if (id == R.id.action_settings) {
            return true;
        }

        return super.onOptionsItemSelected(item);
    }
}

In the xml-File we declared a method onSendText. This method we implement at the end from FirstActivity.java. Add this code to your file:

// This method will be called after you clicked the button
public void onSendText(View view) {
    Intent intent = new Intent(this, SecondActivity.class);
    startActivity(intent);
}

At the end your file should look like this one:

package com.frogtag.bef.twoactivities;

import android.content.Intent;
import android.os.Bundle;
import android.support.design.widget.FloatingActionButton;
import android.support.design.widget.Snackbar;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.view.View;
import android.view.Menu;
import android.view.MenuItem;

public class FirstActivity extends AppCompatActivity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_first);
        Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
        setSupportActionBar(toolbar);

        FloatingActionButton fab = (FloatingActionButton) findViewById(R.id.fab);
        fab.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                Snackbar.make(view, "Replace with your own action", Snackbar.LENGTH_LONG)
                        .setAction("Action", null).show();
            }
        });
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(R.menu.menu_first, menu);
        return true;
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        // Handle action bar item clicks here. The action bar will
        // automatically handle clicks on the Home/Up button, so long
        // as you specify a parent activity in AndroidManifest.xml.
        int id = item.getItemId();

        //noinspection SimplifiableIfStatement
        if (id == R.id.action_settings) {
            return true;
        }

        return super.onOptionsItemSelected(item);
    }

    // This method will be called after you clicked the button
    public void onSendText(View view) {
        Intent intent = new Intent(this, SecondActivity.class);
        startActivity(intent);
    }
}

Now run your app. Add some text to the TextView and click the Button.

In case you get a build error. Check your import for:

import android.content.Intent;

Normally Android Studio will add this line automatic to your import lines.

Facebooktwittergoogle_plusredditpinterestlinkedinmail

Raspberry PI: Installing Node.js

Today we will install Node.js v4 on a Raspberry PI running Raspbian. Since version 4 Node.js supports natively ARM processors, this makes the installation of Node.js on a Raspberry PI simple and fast.

The installation is done in a few steps.

Download Node.js source

Open a terminal on your Raspberry PI and download the source.

For Raspberry PI Model A, B, B+ use:

wget https://nodejs.org/dist/v4.2.4/node-v4.2.4-linux-armv6l.tar.gz

For Raspberry PI 2 Model B use:

wget https://nodejs.org/dist/v4.2.4/node-v4.2.4-linux-armv7l.tar.gz

Extract the .tar – file

tar -xvf node-v4.2.4-linux-armv61.tar.gz

Copy to /usr/local/

Change the directory to your extracted Node.js folder and copy to /usr/local/:

cd node-v4.2.4-linux-armv61
sudo cp -R * /usr/local/

Check your installation

To check your installation open a terminal and run the command:

node -v

You will get an output like this:

v4.2.4

That’s it! 🙂

Facebooktwittergoogle_plusredditpinterestlinkedinmail

Raspberry PI: Installing a LAMP (LINUX APACHE MYSQL PHP) Webserver

In this blog post we will set up a fresh new NOOBS installation on your Raspberry PI as an Apache 2 Webserver.

How to install your OS on the Raspberry PI SD card have a look at this NOOBS Setup Guide.

Install Apache 2 on Raspberry PI

Apache 2 can be installed with the following command:

sudo apt-get install apache2

To test the successful installation open a browser window and put in your’s Raspberry PI IP-Address and you will hopefully see a page like this:

Apache 2 installation

The document root folder is under /var/www/

Install PHP 5 on Raspberry PI

In the next step we will install PHP.

PHP 5 will be installed with following command:

sudo apt-get install php5

To test the installation open a terminal and put in following:

php -v

You will get an output like this one:

PHP 5.6.14-0+deb8u1 (cli) (built: Oct 28 2015 00:02:05)
Copyright (c) 1997-2015 The PHP Group
Zend Engine v2.6.0, Copyright (c) 1998-2015 Zend Technologies
     with Zend 0Pcache v7.0.6-dev, Copyright (c) 1999-2015, by Zend Technologies

Install MySQL on Raspberry PI

To install a MySQL server put following commands into your terminal:

sudo apt-get install mysql-server mysql-client php5-mysql

Follow the instructions in your terminal to install the MySQL server and create a password for the root account.

After the installation we restart our Raspberry PI

sudo shutdown -r 0

Install an FTP Server on Raspberry PI

We will install the VSFTPD FTP Server on our Raspberry PI system. To do so we need following command:

sudo apt-get install vsftpd

After the installation of the FTP server we need to configure the server. By default VSFTPD will deny access tries by local users. In this tutorial we will use only local users to access the FTP server.

We have to edit the /etc/vsftpd.conf file. To do so we open the file with a editor in the terminal.

sudo nano /etc/vsftpd.conf

You will see a file like this (this is not the whole file it is a part of it):

# Example config file /etc/vsftpd.conf
#
# The default compiled in settings are fairly paranoid. This sample file
# loosens things up a bit, to make the ftp daemon more usable.
# Please see vsftpd.conf.5 for all compiled in defaults.
#
# READ THIS: This example file is NOT an exhaustive list of vsftpd options.
# Please read the vsftpd.conf.5 manual page to get a full idea of vsftpd's
# capabilities.
#
#
# Run standalone? vsftpd can run either from an inetd or as a standalone
# daemon started from an initscript.
listen=NO
#
# This directive enables listening on IPv6 sockets. By default, listening
# on the IPv6 "any" address (::) will accept connections from both IPv6
# and IPv4 clients. It is not necessary to listen on *both* IPv4 and IPv6
# sockets. If you want that (perhaps because you want to listen on specific
# addresses) then you must run two copies of vsftpd with two configuartion
# files.
listen_ipv6=YES
#
# Allow anonymous FTP? (Disabled by default).
anonymous_enable=NO
#
# Uncomment this to allow local users to log in.
local_enable=YES
#
# Uncomment this to enable any form of FTP write command.
#write_enable=YES
#
# Default umask for local users is 077. You may wish to change this to 022,
# if your users expect that (022 is used by most other ftpd's)
#local_umask=022
#
# Uncomment this to allow the anonymous FTP user to upload files. This only
# has an effect if the above global write enable is activated. Also, you will
# obviously need to create a directory writable by the FTP user.
#anon_upload_enable=YES
#

To allow local users access to the FTP server find the line and uncomment ‘local_enable=YES’:

# Uncomment this to allow local users to log in.
local_enable=YES

Install phpMyAdmin on Raspberry PI

In the last step we will install phpMyAdmin. This is optional you can also use every other SQL – Client on your locale machine.

Put following into your terminal session:

sudo apt-get install phpmyadmin

Follow the instructions in you terminal. Configure apache2 as your webserver in the dialog.

Let the system create the DB automatically by clicking ‘YES’:

PHPMyAdmin_DB_Create

Create a password for the login:

PHPMyAdmin_PW

To test the installation of phpMyAdmin open a browser window and put in the IP Address of you Raspberry PI and add /phpmyadmin to it:

PHPMyAdmin_Login

That’s it! You have installed your own LAMP Webserver on your Raspberry PI system.

Facebooktwittergoogle_plusredditpinterestlinkedinmail

Make your MySQL Server public in your network

In this tutorial we make a new MySQL server installation accessible from your network. Per default a new MySQL server installation is only reachable by a localhost.

In our scenario we want to access the MySQL server from other IP addresses then from our localhost. To make this happen we must to edit our my.cnf file. In case you used like me a Ubuntu Server operating system and installed the MySQL server from the default repository, the my.cnf file is located under following path:

/etc/mysql/my.cnf

To edit this file open it with root rights in a text editor, I use for this Nano:

sudo nano /etc/mysql/my.cnf

You will see a mostly empty file like the following:

# The MySQL database server configuration file.
#
# You can copy this to one of:
# - "/etc/mysql/my.cnf" to set global options,
# - "~.my.cnf" to set user-specific options.
#
# One can use all long options that the program supports. 
# Run program with --help to get a list of available options and with
# --print-defaults to see which it would actually understand and use.
#
# For explanations see
# http://dev.mysql.com/doc/mysql/en/server-system-variables.html
# * IMPORTANT: Additional settings that can override those from this file!
# The files must end with '.cnf', otherwise they'll be ignored.
#

!includedir /etc/mysql/conf.d/
!includedir /etc/mysql/mysql.conf.d/

To make your MySQL server now reachable over your network, add following lines at the end of this file:

[mysqld]
user=mysql
pid-file=/var/run/mysqld/mysqld.pid
socket=/var/run/mysqld/mysqld.sock
port=3306
basedir=/usr
datadir=/var/lib/mysql
tmpdir=/tmp
bind-address=0.0.0.0

The most important line is bind-address = 0.0.0.0. With the IP-address 0.0.0.0 your MySQL server can be reached from every IP-address. You can also switch this IP-address to your client IP-address. In this case your MySQL server will only accept connections from your client.

More detailed information you will find on the MySQL Reference Manual site.

Facebooktwittergoogle_plusredditpinterestlinkedinmail