Java Android App Development Course, Exploring Basic Views

The most basic yet crucial part of Android app development is the ‘View’. A view is the fundamental element that makes up the user interface of the app and includes all elements that interact with the user. In this course, we will explore the types of main views used in Android applications, how to use them, and how to utilize views through example code.

1. What is a View?

A view refers to elements displayed on the screen. Through this, elements such as buttons, text fields, images, and lists that can interact with the user can be implemented. The view structure in Android is hierarchical, and each view can contain another view. This complex structure allows developers to create flexible user interfaces.

2. Types of Basic Views Available in Android

  • TextView: Used to display text on the screen.
  • EditText: An input field where users can enter text.
  • Button: Provides a button that the user can click.
  • ImageView: Displays an image on the screen.
  • CheckBox: Provides a checkbox that can be selected.
  • RadioButton: Allows selection of one option among several.
  • Spinner: A selection box in a dropdown list format.
  • ListView: Displays a list of items.
  • RecyclerView: An improved version of ListView that efficiently displays lists of items, enhancing performance.

3. Detailed Explanation of Each View and Examples

3.1 TextView

TextView is a view that helps display textual information to the user. The properties that can be set include font, size, color, and line spacing. Here is an example of using TextView.

xml
<TextView
    android:id="@+id/textView"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:text="Hello, Android!"
    android:textSize="20sp"
    android:textColor="#000000" />
java
TextView textView = findViewById(R.id.textView);
textView.setText("Hello, Android!");

3.2 EditText

EditText is a field where users can input text. It is useful for receiving and processing data from users. Here is an example of using EditText.

xml
<EditText
    android:id="@+id/editText"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:hint="Enter here" />
java
EditText editText = findViewById(R.id.editText);
String inputText = editText.getText().toString();

3.3 Button

Button is a button that the user can click. You can set it to perform certain actions when clicked. Below is an example of using Button.

xml
<Button
    android:id="@+id/button"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:text="Click here" />
java
Button button = findViewById(R.id.button);
button.setOnClickListener(new View.OnClickListener() {
    @Override
    public void onClick(View v) {
        Toast.makeText(getApplicationContext(), "Button clicked!", Toast.LENGTH_SHORT).show();
    }
});

3.4 ImageView

ImageView is a view used to display images on the screen. Let’s look at how to use ImageView in the following example.

xml
<ImageView
    android:id="@+id/imageView"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:src="@drawable/sample_image" />
java
ImageView imageView = findViewById(R.id.imageView);
imageView.setImageResource(R.drawable.another_image);

3.5 CheckBox

CheckBox provides selectable checkbox items. It is useful when you want to choose among multiple items. Refer to the example below.

xml
<CheckBox
    android:id="@+id/checkBox"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:text="Select option" />
java
CheckBox checkBox = findViewById(R.id.checkBox);
checkBox.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
    @Override
    public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
        if (isChecked) {
            Toast.makeText(getApplicationContext(), "Checked", Toast.LENGTH_SHORT).show();
        } else {
            Toast.makeText(getApplicationContext(), "Unchecked", Toast.LENGTH_SHORT).show();
        }
    }
});

3.6 RadioButton

RadioButton is a view that allows selection of one option among several. The user can select only one from the radio buttons. The example is as follows.

xml
<RadioGroup
    android:id="@+id/radioGroup"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content">
    <RadioButton
        android:id="@+id/radioButton1"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Option 1" />
    <RadioButton
        android:id="@+id/radioButton2"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Option 2" />
</RadioGroup>
java
RadioGroup radioGroup = findViewById(R.id.radioGroup);
radioGroup.setOnCheckedChangeListener(new RadioGroup.OnCheckedChangeListener() {
    @Override
    public void onCheckedChanged(RadioGroup group, int checkedId) {
        switch (checkedId) {
            case R.id.radioButton1:
                Toast.makeText(getApplicationContext(), "Option 1 selected", Toast.LENGTH_SHORT).show();
                break;
            case R.id.radioButton2:
                Toast.makeText(getApplicationContext(), "Option 2 selected", Toast.LENGTH_SHORT).show();
                break;
        }
    }
});

3.7 Spinner

Spinner provides a dropdown list format for selectable items. Here is an example of using Spinner.

xml
<Spinner
    android:id="@+id/spinner"
    android:layout_width="match_parent"
    android:layout_height="wrap_content" />
java
Spinner spinner = findViewById(R.id.spinner);
ArrayAdapter adapter = ArrayAdapter.createFromResource(this,
        R.array.options_array, android.R.layout.simple_spinner_item);
adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
spinner.setAdapter(adapter);

3.8 ListView

ListView is used to display a list of items. It can show multiple items simply in list form. Below is an example of ListView.

xml
<ListView
    android:id="@+id/listView"
    android:layout_width="match_parent"
    android:layout_height="match_parent" />
java
ListView listView = findViewById(R.id.listView);
ArrayAdapter adapter = new ArrayAdapter(this,
        android.R.layout.simple_list_item_1, dataArray);
listView.setAdapter(adapter);

3.9 RecyclerView

RecyclerView is a view that creates lists that are more flexible and feature-rich than ListView. It can be considered an improved version in terms of performance. An example of using RecyclerView is as follows.

xml
<androidx.recyclerview.widget.RecyclerView
    android:id="@+id/recyclerView"
    android:layout_width="match_parent"
    android:layout_height="match_parent" />
java
RecyclerView recyclerView = findViewById(R.id.recyclerView);
recyclerView.setLayoutManager(new LinearLayoutManager(this));
MyAdapter adapter = new MyAdapter(myDataList);
recyclerView.setAdapter(adapter);

4. Relationship Between Layout and View

In Android, all views are placed within a layout. A layout is a container that defines how to arrange the views. Common types of layouts include LinearLayout, RelativeLayout, ConstraintLayout, and FrameLayout. The characteristics and usage of each layout are as follows.

4.1 LinearLayout

LinearLayout is a layout that can align child views either vertically or horizontally. The example below explains how to use LinearLayout.

xml
<LinearLayout
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical">
    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="First Text" />
    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Second Text" />
</LinearLayout>

4.2 RelativeLayout

RelativeLayout is a layout that allows arranging child views based on their relative positions to each other. An example can be where the title and description maintain their positional relationship.

xml
<RelativeLayout
    android:layout_width="match_parent"
    android:layout_height="match_parent">
    <TextView
        android:id="@+id/title"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Title" />
    <TextView
        android:id="@+id/description"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_below="@id/title"
        android:text="Description" />
</RelativeLayout>

4.3 ConstraintLayout

ConstraintLayout is a layout that helps create more complex user interfaces. You can determine the position of views using various constraints, enabling you to place more views more concisely.

xml
<androidx.constraintlayout.widget.ConstraintLayout
    android:layout_width="match_parent"
    android:layout_height="match_parent">
    <TextView
        android:id="@+id/textView1"
        android:layout_width="0dp"
        android:layout_height="wrap_content"
        android:text="Text arranged by constraints"
        app:layout_constraintTop_toTopOf="parent"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintEnd_toEndOf="parent" />
</androidx.constraintlayout.widget.ConstraintLayout>

5. View and Event Handling

One of the most important aspects when using views is event handling. Android can handle various types of user input events. Events are processed using listeners to handle click, touch, and other events for each view. Below is how to handle button click events.

java
button.setOnClickListener(new View.OnClickListener() {
    @Override
    public void onClick(View v) {
        // Actions to perform when button is clicked
    }
});

6. Conclusion

In this course, we have looked at the fundamental ‘View’ in Android app development. We learned about the types and usage of various views, the concept of layouts, and how to handle events. Understanding and utilizing these fundamental elements is an important first step toward developing more complex and diverse functionality apps. In the next course, we will return with more advanced content. Wishing you luck on your Android app development journey!

Java Android App Development Course, Utilizing Google Maps

Understanding the use of Google Maps in Android app development is of great value to many developers.
By utilizing the Google Maps API, various functions can be implemented, such as allowing users to view real-time map information, find specific locations, and provide navigation features. In this article, we will explain in detail how to implement Google Maps in an Android app using Java and provide some example codes.

1. What is Google Maps API?

Google Maps API is a service that allows developers to easily implement map features in websites or mobile applications using map information provided by Google. By using this API, users can access information such as maps, markers, and routes for their desired areas. To use Google Maps in an Android app, it is necessary to integrate the Google Maps API.

2. Creating a Google Maps API Key

To use Google Maps in the app, an API key is required. Here’s how to create an API key.

  1. Log in to Google Cloud Platform. (Google Cloud Console)
  2. Create a new project.
  3. Navigate to ‘API and Services’ > ‘Library’ from the dashboard.
  4. Search for ‘Maps SDK for Android’ and enable it.
  5. Navigate to ‘API and Services’ > ‘Credentials’ to generate the API key.

3. Setting Up the Android Project

Once the API key is ready, set up the Android project. Open Android Studio and create a new project.
Here, we will select ‘Empty Activity’.

3.1. Modifying the Gradle File

Open the `build.gradle` file and add the following dependency:


    dependencies {
        implementation 'com.google.android.gms:play-services-maps:17.0.1' // Google Maps dependency
    }
    

3.2. Modifying AndroidManifest.xml

Add the permissions and API key in the `AndroidManifest.xml` file as follows:


    <manifest xmlns:android="http://schemas.android.com/apk/res/android"
        package="com.example.mymapapp">

        <uses-permission android:name="android.permission.INTERNET"/>
        <uses-permission android:name="android.permission.ACCESS_FINE_LOCATION"/>

        <application
            ...
            android:meta-data
                android:name="com.google.android.geo.API_KEY"
                android:value="YOUR_API_KEY"/>
        </application>
    </manifest>
    

4. Implementing the Map Display

Now we will display the map on the screen. Modify the `activity_main.xml` file to add a map fragment.


    <LinearLayout 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:orientation="vertical"
        tools:context=".MainActivity">

        <fragment
            android:id="@+id/map"
            android:name="com.google.android.gms.maps.SupportMapFragment"
            android:layout_width="match_parent"
            android:layout_height="match_parent"/>

    </LinearLayout>
    

4.1. Implementing MainActivity.java

Modify the `MainActivity.java` file as follows to control the map.


    package com.example.mymapapp;

    import android.os.Bundle;
    import androidx.fragment.app.FragmentActivity;
    import com.google.android.gms.maps.CameraUpdateFactory;
    import com.google.android.gms.maps.GoogleMap;
    import com.google.android.gms.maps.OnMapReadyCallback;
    import com.google.android.gms.maps.SupportMapFragment;
    import com.google.android.gms.maps.model.LatLng;
    import com.google.android.gms.maps.model.MarkerOptions;

    public class MainActivity extends FragmentActivity implements OnMapReadyCallback {

        private GoogleMap mMap;

        @Override
        protected void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
            setContentView(R.layout.activity_main);
            SupportMapFragment mapFragment = (SupportMapFragment) getSupportFragmentManager().findFragmentById(R.id.map);
            mapFragment.getMapAsync(this);
        }

        @Override
        public void onMapReady(GoogleMap googleMap) {
            mMap = googleMap;

            // Example Location: Seoul
            LatLng seoul = new LatLng(37.5665, 126.978);
            mMap.addMarker(new MarkerOptions().position(seoul).title("Marker in Seoul"));
            mMap.moveCamera(CameraUpdateFactory.newLatLng(seoul));
        }
    }
    

5. Adding Markers

We will implement the function to add markers so that users can easily find various places. Although we have already added one marker in the example code, I will show you how to add multiple markers.


    @Override
    public void onMapReady(GoogleMap googleMap) {
        mMap = googleMap;

        // Seoul Marker
        LatLng seoul = new LatLng(37.5665, 126.978);
        mMap.addMarker(new MarkerOptions().position(seoul).title("Marker in Seoul"));

        // Busan Marker
        LatLng busan = new LatLng(35.1796, 129.0756);
        mMap.addMarker(new MarkerOptions().position(busan).title("Marker in Busan"));

        // Daegu Marker
        LatLng daegu = new LatLng(35.8714, 128.6014);
        mMap.addMarker(new MarkerOptions().position(daegu).title("Marker in Daegu"));

        // Change camera position
        mMap.moveCamera(CameraUpdateFactory.newLatLng(seoul));
    }
    

6. Requesting Location Access Permission

When implementing location-based services, it is necessary to request location access permission from the user. Here’s how to request location permission.


    import android.Manifest;
    import android.content.pm.PackageManager;
    import androidx.core.app.ActivityCompat;

    private static final int LOCATION_PERMISSION_REQUEST_CODE = 1;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        SupportMapFragment mapFragment = (SupportMapFragment) getSupportFragmentManager().findFragmentById(R.id.map);
        mapFragment.getMapAsync(this);

        // Request location permission
        if (ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
            ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.ACCESS_FINE_LOCATION}, LOCATION_PERMISSION_REQUEST_CODE);
        } else {
            mMap.setMyLocationEnabled(true);
        }
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, String[] permissions, int[] grantResults) {
        if (requestCode == LOCATION_PERMISSION_REQUEST_CODE) {
            if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
                if (ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) == PackageManager.PERMISSION_GRANTED) {
                    mMap.setMyLocationEnabled(true);
                }
            }
        }
    }
    

7. Displaying Current Location

Let’s implement how to display the user’s current location on the map. With the code just added, you can display the current location using the .setMyLocationEnabled(true) method. To move the camera to the current location, modify it as follows.


    @Override
    public void onMapReady(GoogleMap googleMap) {
        mMap = googleMap;

        // Display current location based on user's permission
        if (ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) == PackageManager.PERMISSION_GRANTED) {
            mMap.setMyLocationEnabled(true);
        }

        // Seoul Marker
        LatLng seoul = new LatLng(37.5665, 126.978);
        mMap.addMarker(new MarkerOptions().position(seoul).title("Marker in Seoul"));
        
        // Change camera position
        mMap.moveCamera(CameraUpdateFactory.newLatLngZoom(seoul, 10));
    }
    

8. Implementing Route Finding Functionality

The route finding function is used to find the path between the user and a specific destination. You can use the Google Directions API
to find routes, but additional work is required for this.

To call the Directions API, you can use an HTTP client such as Axios or Retrofit to send requests and analyze the returned route data
to display it on the map’s Polyline. This part will be briefly explained.


    // Calling Directions API using Retrofit
    public interface DirectionsService {
        @GET("directions/json")
        Call getDirections(@Query("origin") String origin,
                                          @Query("destination") String destination,
                                          @Query("key") String apiKey);
    }
    

Using the route data obtained from this API, you can add the Polyline to the map to display the route.

9. Conclusion

In this article, we explored the basic setup and functionality for utilizing Google Maps in Android app development.
By leveraging the Google Maps API, you can create powerful applications that provide various location-based services.
I recommend adding user-friendly features and implementing complex route finding functionality using the Directions API.

The path of app development is not easy, but the possibilities of providing a rich user experience using Google Maps are endless.
I hope this helps you bring your ideas to life.

© 2023 Blog Ideas

Java Android App Development Course, Creating a Google Maps App

Android app development is one of the most popular fields of mobile development today. With various libraries and frameworks, developers can create apps that provide excellent user experiences. In this course, we will explain how to create an Android app that utilizes Google Maps using Java. This course will proceed in the following steps:

  • 1. Project Setup
  • 2. Google Maps API Setup
  • 3. Displaying the Map in the App
  • 4. Adding Markers and Displaying User Location
  • 5. Adding Map Styles and Features

1. Project Setup

First, open Android Studio and create a new project. Follow the settings below to set up the project:

  • Name: GoogleMapsApp
  • Package Name: com.example.googlemapsapp
  • Language: Java
  • Minimum API Level: API 21: Android 5.0 (Lollipop)

Once the project is created, you need to add the Google Maps library to the app/build.gradle file. To do this, add the following code to the dependencies section:

implementation 'com.google.android.gms:play-services-maps:18.0.2'

Now sync the Gradle file to update the dependencies.

2. Google Maps API Setup

To use Google Maps, you need to obtain an API key from the Google Cloud Platform. Follow these steps to create a Google Maps API key:

  1. Log in to Google Cloud Platform and create a new project.
  2. In the dashboard, go to ‘APIs & Services’ -> ‘Library’.
  3. Search for ‘Google Maps Android API’ and enable it.
  4. In ‘APIs & Services’ -> ‘Credentials’, click the ‘Create Credentials’ button.
  5. Select ‘API Key’ and generate it, then copy the key you received.

You need to add the generated API key to the AndroidManifest.xml file:


<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.example.googlemapsapp">

    <application>
        <meta-data
            android:name="com.google.android.geo.API_KEY"
            android:value="YOUR_API_KEY"/>
        ...
    </application>

</manifest>

Now your Google Maps API is ready to use.

3. Displaying the Map in the App

To display Google Maps in the app, you need to add a map fragment to the layout. Open the res/layout/activity_main.xml file and add the following code:


<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context=".MainActivity">

    <fragment
        android:id="@+id/map"
        android:name="com.google.android.gms.maps.SupportMapFragment"
        android:layout_width="match_parent"
        android:layout_height="match_parent"/>

</RelativeLayout>

Next, we will add code to initialize and display the map in the MainActivity.java file:


import androidx.fragment.app.FragmentActivity;
import android.os.Bundle;
import com.google.android.gms.maps.CameraUpdateFactory;
import com.google.android.gms.maps.GoogleMap;
import com.google.android.gms.maps.OnMapReadyCallback;
import com.google.android.gms.maps.SupportMapFragment;
import com.google.android.gms.maps.model.LatLng;
import com.google.android.gms.maps.model.MarkerOptions;

public class MainActivity extends FragmentActivity implements OnMapReadyCallback {

    private GoogleMap mMap;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        SupportMapFragment mapFragment = (SupportMapFragment) getSupportFragmentManager()
                .findFragmentById(R.id.map);
        mapFragment.getMapAsync(this);
    }

    @Override
    public void onMapReady(GoogleMap googleMap) {
        mMap = googleMap;

        // Set the center position of the map
        LatLng seoul = new LatLng(37.56, 126.97);
        mMap.moveCamera(CameraUpdateFactory.newLatLng(seoul));
    }
}

In the code above, we set the camera to move to the location of Seoul when the map is ready.

4. Adding Markers and Displaying User Location

Now, let’s add a marker at a user-defined location. Add the following code in the onMapReady method to place the marker:


    @Override
    public void onMapReady(GoogleMap googleMap) {
        mMap = googleMap;

        // Set the center position of the map
        LatLng seoul = new LatLng(37.56, 126.97);
        mMap.moveCamera(CameraUpdateFactory.newLatLng(seoul));

        // Add marker
        mMap.addMarker(new MarkerOptions().position(seoul).title("Marker in Seoul"));

        // Allow displaying user location
        mMap.setMyLocationEnabled(true);
    }

The above code adds a marker at Seoul’s location and enables the functionality to show the user’s current location.

5. Adding Map Styles and Features

Finally, let’s add styles to the Google Map and expand some features. For example, we will have the marker update when the user’s location changes:


import com.google.android.gms.location.LocationCallback;
import com.google.android.gms.location.LocationRequest;
import com.google.android.gms.location.LocationResult;
import com.google.android.gms.location.LocationServices;

public class MainActivity extends FragmentActivity implements OnMapReadyCallback {

    private GoogleMap mMap;
    private FusedLocationProviderClient fusedLocationClient;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        fusedLocationClient = LocationServices.getFusedLocationProviderClient(this);
        SupportMapFragment mapFragment = (SupportMapFragment) getSupportFragmentManager()
                .findFragmentById(R.id.map);
        mapFragment.getMapAsync(this);
    }

    @Override
    public void onMapReady(GoogleMap googleMap) {
        mMap = googleMap;

        LatLng seoul = new LatLng(37.56, 126.97);
        mMap.moveCamera(CameraUpdateFactory.newLatLng(seoul));
        mMap.addMarker(new MarkerOptions().position(seoul).title("Marker in Seoul"));
        mMap.setMyLocationEnabled(true);
        
        // Set up user location updates
        startLocationUpdates();
    }

    private void startLocationUpdates() {
        LocationRequest locationRequest = LocationRequest.create();
        locationRequest.setInterval(10000);
        locationRequest.setFastestInterval(5000);
        locationRequest.setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY);

        LocationCallback locationCallback = new LocationCallback() {
            @Override
            public void onLocationResult(LocationResult locationResult) {
                if (locationResult == null) {
                    return;
                }
                for (Location location : locationResult.getLocations()) {
                    // Update user location
                    LatLng userLocation = new LatLng(location.getLatitude(), location.getLongitude());
                    mMap.addMarker(new MarkerOptions().position(userLocation).title("You are here"));
                    mMap.moveCamera(CameraUpdateFactory.newLatLng(userLocation));
                }
            }
        };
        
        fusedLocationClient.requestLocationUpdates(locationRequest, locationCallback, null);
    }
}

The above code updates the marker whenever the user’s location changes, reflecting the user’s location on the map.

Conclusion

We have now completed all steps to create a basic Google Maps app. This app can be extended for various purposes, such as business or personal projects. Additional features, such as various marker styles, route display, or multiple location searches, can be easily implemented. The Google Maps API is a very useful tool for Android app development. Furthermore, using this API, you can provide a rich experience for users. The next step is to enhance this app with additional features and styles.

We hope this course has been fun and helpful for your app development. Now, go ahead and create your own Google Maps app!

Java Android App Development Course, Save to Shared Preferences

When developing on Android, there are often cases where you need to store certain settings or user information of the application.
What is used at this time is SharedPreferences.
SharedPreferences is useful for saving data using simple key-value pairs and is suitable for storing small amounts of data.
In this tutorial, we will cover how to save and retrieve user information using SharedPreferences.

1. What is SharedPreferences?

SharedPreferences is a lightweight data storage mechanism in Android that makes it easy to save and recover application settings, user information, etc.
It is suitable for storing small data sets, and the data is stored in the XML file format in the app’s data directory.

2. Reasons to Use SharedPreferences

  • Simple data storage: It allows you to easily save simple information such as user settings and login information.
  • Shareable: You can easily access shared values across multiple activities.
  • Lightweight: It is useful when using a complex database is unnecessary.

3. Basic Usage of SharedPreferences

The process of using SharedPreferences can be broadly divided into three steps:
Creation, Data Saving, Data Retrieval.

3.1 Creating SharedPreferences

The method for creating SharedPreferences is as follows. The code below is an example of creating SharedPreferences in the `MainActivity` class.

SharedPreferences sharedPreferences = getSharedPreferences("MyPreferences", MODE_PRIVATE);

3.2 Data Saving

When saving data to SharedPreferences, you need to use the `Editor`. Below is an example of saving a username and age.


SharedPreferences.Editor editor = sharedPreferences.edit();
editor.putString("username", "John Doe");
editor.putInt("age", 25);
editor.apply();

3.3 Data Retrieval

To retrieve the saved data, use the `getString` or `getInt` method. The code below is an example of retrieving saved user information.


String username = sharedPreferences.getString("username", "default");
int age = sharedPreferences.getInt("age", 0);

4. Practical Example

Below is the example code utilizing SharedPreferences overall. We will create an app that saves information entered by the user and displays the saved information on the screen.

4.1 Layout File (activity_main.xml)

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical">

    <EditText
        android:id="@+id/editTextUsername"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:hint="Username"/>

    <EditText
        android:id="@+id/editTextAge"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:hint="Age"
        android:inputType="number"/>

    <Button
        android:id="@+id/buttonSave"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Save"/>

    <TextView
        android:id="@+id/textViewResult"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"/>

    </LinearLayout>

4.2 Main Activity (MainActivity.java)

import android.content.SharedPreferences;
    import android.os.Bundle;
    import android.view.View;
    import android.widget.Button;
    import android.widget.EditText;
    import android.widget.TextView;
    import androidx.appcompat.app.AppCompatActivity;

    public class MainActivity extends AppCompatActivity {

        private SharedPreferences sharedPreferences;
        private EditText editTextUsername, editTextAge;
        private TextView textViewResult;

        @Override
        protected void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
            setContentView(R.layout.activity_main);

            editTextUsername = findViewById(R.id.editTextUsername);
            editTextAge = findViewById(R.id.editTextAge);
            textViewResult = findViewById(R.id.textViewResult);
            Button buttonSave = findViewById(R.id.buttonSave);

            sharedPreferences = getSharedPreferences("MyPreferences", MODE_PRIVATE);
            loadStoredData();

            buttonSave.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    String username = editTextUsername.getText().toString();
                    int age = Integer.parseInt(editTextAge.getText().toString());
                    saveData(username, age);
                }
            });
        }

        private void saveData(String username, int age) {
            SharedPreferences.Editor editor = sharedPreferences.edit();
            editor.putString("username", username);
            editor.putInt("age", age);
            editor.apply();
            loadStoredData();
        }

        private void loadStoredData() {
            String username = sharedPreferences.getString("username", "default");
            int age = sharedPreferences.getInt("age", 0);
            textViewResult.setText("Username: " + username + "\nAge: " + age);
        }
    }

5. Precautions

SharedPreferences is suitable for storing small amounts of data.
If you need to store large amounts of data or complex data structures, it is recommended to use an SQLite database or the Room library.

6. Conclusion

In this tutorial, we learned how to save and retrieve simple user information using SharedPreferences.
By utilizing these features, you can develop various applications that enhance the user experience.
In the future, we will also cover how to use the Room library to efficiently manage more data.

Java Android App Development Course, Arranged in Hierarchical Structure – ConstraintLayout

There are several ways to structure a UI in Android app development, one of which is ConstraintLayout. ConstraintLayout is a powerful tool that helps to easily create complex UI layouts. In this tutorial, we will explain why to use ConstraintLayout, its basic concepts, and how to use it in practice through examples.

1. Introduction to ConstraintLayout

ConstraintLayout is a layout that allows for easy arrangement of various Views. In traditional layout methods, LinearLayout or RelativeLayout were used, but ConstraintLayout has structural advantages that overcome the limitations of these methods.

  • Flexibility: Automatically adjusts according to the size of the device using a percent-based layout.
  • Performance: Simplifies the View Hierarchy, reducing memory usage and improving performance.
  • Integration with design tools: The Layout Editor in Android Studio allows for easy placement of visual elements using ConstraintLayout.

2. Basic Concepts of ConstraintLayout

ConstraintLayout arranges views by defining constraints between them. You can set the position of your desired view relative to other views or the parent view. Thanks to this characteristic, developers can set views to reference each other for proper placement.

The most important concept in ConstraintLayout is Constraints. Constraints provide the necessary information to determine the position and size of a view. Generally, the following constraints can be set:

  • Top constraint: Fixes the top of the view to the top of the parent or another view.
  • Bottom constraint: Fixes the bottom of the view to the bottom of the parent or another view.
  • Start constraint: Fixes the start (left) of the view to the start of the parent or another view.
  • End constraint: Fixes the end (right) of the view to the end of the parent or another view.
  • Width and Height constraint: Sets constraints for the width and height of the view.

3. Using ConstraintLayout

Now let’s look at how to actually use ConstraintLayout through the example below. In this example, we will create a basic login screen.

3.1 Creating an XML Layout File

The following is the XML code to implement the login screen. This code will be saved as ‘activity_login.xml’ in the res/layout directory.

<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout 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"
    tools:context=".LoginActivity">

    <TextView
        android:id="@+id/textViewTitle"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Login"
        android:textSize="24sp"
        android:textStyle="bold"
        app:layout_constraintBottom_toTopOf="@+id/editTextUsername"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toTopOf="parent"/>

    <EditText
        android:id="@+id/editTextUsername"
        android:layout_width="0dp"
        android:layout_height="wrap_content"
        android:hint="Username"
        app:layout_constraintBottom_toTopOf="@+id/editTextPassword"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintWidth_percent="0.5"/>

    <EditText
        android:id="@+id/editTextPassword"
        android:layout_width="0dp"
        android:layout_height="wrap_content"
        android:hint="Password"
        app:layout_constraintBottom_toTopOf="@+id/buttonLogin"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintWidth_percent="0.5"/>

    <Button
        android:id="@+id/buttonLogin"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Login"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toStartOf="parent"/>

</androidx.constraintlayout.widget.ConstraintLayout>

3.2 Writing the MainActivity.java File

After creating the XML file, you now need to write the Activity that will use this layout. Create a ‘MainActivity.java’ file under the directory ‘src/main/java/com/example/app’.

package com.example.app;

import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;
import androidx.appcompat.app.AppCompatActivity;

public class MainActivity extends AppCompatActivity {

    private EditText editTextUsername;
    private EditText editTextPassword;
    private Button buttonLogin;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_login);

        editTextUsername = findViewById(R.id.editTextUsername);
        editTextPassword = findViewById(R.id.editTextPassword);
        buttonLogin = findViewById(R.id.buttonLogin);

        buttonLogin.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                String username = editTextUsername.getText().toString();
                String password = editTextPassword.getText().toString();

                if (username.isEmpty() || password.isEmpty()) {
                    Toast.makeText(MainActivity.this, "Please fill in all fields.", Toast.LENGTH_SHORT).show();
                } else {
                    // Logic to handle login
                    Toast.makeText(MainActivity.this, "Login successful!", Toast.LENGTH_SHORT).show();
                }
            }
        });
    }
}

4. Advanced Features of ConstraintLayout

In addition to basic constraints, ConstraintLayout supports various advanced features. Here we will introduce a few key features.

4.1 Guideline

A guideline provides a visual aid that helps align views. You can create horizontal or vertical guidelines to assist with view placement and size adjustments.

<androidx.constraintlayout.widget.Guideline
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:orientation="vertical"
    android:guidePercent="0.5"/>

4.2 Barrier

A barrier allows views to be dependent on each other, dynamically adjusting the position of other views based on the size of the primary view. For example, if one view is hidden, another view can take its place.

4.3 Group

Using a group allows you to bundle multiple views together to set constraints or visibility collectively.

<androidx.constraintlayout.widget.Group
    android:id="@+id/group"
    app:layout_constraintStart_toStartOf="parent"
    app:layout_constraintEnd_toEndOf="parent"/>

5. Conclusion

ConstraintLayout is a very useful tool in Android UI development, allowing you to easily set relationships between views. In this tutorial, we explored the basic concepts and usage of ConstraintLayout, as well as advanced features for creating complex layouts. When developing actual apps, utilize this information to implement efficient and responsive UIs.

Now you are ready to create your own unique UI using ConstraintLayout. Enjoy the pleasure of combining various elements to create amazing apps!