Android Tutorial Day 4

Learning Objective: Let’s start exploring more fundamentals of Android. How to store some user logged-in value to track the user and its profile. We can use  Shared Preferences.

How to Create  Shared Preferences in Android Programming.

Sample Code to Write Data into Android using Shared Preferences.

FirstFragment Java Code

package com.at.mytestapplication.myapplication;

import android.content.Context;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;

import androidx.annotation.NonNull;
import androidx.fragment.app.Fragment;
import androidx.navigation.fragment.NavHostFragment;

import com.at.mytestapplication.myapplication.databinding.FragmentFirstBinding;

public class FirstFragment extends Fragment {

    private FragmentFirstBinding binding;


    public static final String MyPREFERENCES = "MyPrefs" ;


    @Override
    public View onCreateView(
            LayoutInflater inflater, ViewGroup container,
            Bundle savedInstanceState
    ) {

        binding = FragmentFirstBinding.inflate(inflater, container, false);
        return binding.getRoot();

    }

    public void onViewCreated(@NonNull View view, Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);

        binding.buttonFirst.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {

                SharedPreferences prefs = getContext().getSharedPreferences(MyPREFERENCES, Context.MODE_PRIVATE);
                String mobile = prefs.getString("phoneKey", "-1");

                if(mobile.equals("-1"))
                {
                    Log.e("cs","New User is trying to access");

                    //this is for new users
                    NavHostFragment.findNavController(FirstFragment.this)
                            .navigate(R.id.action_FirstFragment_to_SecondFragment);


                }
                else
                {
                    Log.e("cs","Previously Logged in User");

                    //this is for logged in users
                    NavHostFragment.findNavController(FirstFragment.this)
                            .navigate(R.id.action_FirstFragment_to_SecondFragment);
                }




            }
        });
    }

    @Override
    public void onDestroyView() {
        super.onDestroyView();
        binding = null;
    }

}

SecondFragment Java Code

package com.at.mytestapplication.myapplication;

import static android.content.Context.TELEPHONY_SERVICE;

import android.Manifest;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.pm.PackageManager;
import android.net.Uri;
import android.os.Bundle;
import android.telephony.TelephonyManager;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;

import androidx.annotation.NonNull;
import androidx.core.app.ActivityCompat;
import androidx.core.content.ContextCompat;
import androidx.fragment.app.Fragment;
import androidx.navigation.fragment.NavHostFragment;

import com.at.mytestapplication.myapplication.databinding.FragmentSecondBinding;

public class SecondFragment extends Fragment {

    private FragmentSecondBinding binding;
    public static final String MyPREFERENCES = "MyPrefs" ;


    @Override
    public View onCreateView(
            LayoutInflater inflater, ViewGroup container,
            Bundle savedInstanceState
    ) {

        View view = inflater.inflate(R.layout.fragment_second,
                container, false);

        Button btnlogin = (Button) view.findViewById(R.id.btnlogin);
        Button btnlogout = (Button) view.findViewById(R.id.btnlogout);

        EditText etmobile = (EditText) view.findViewById(R.id.etmobile);


        btnlogin.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {

                SharedPreferences sharedpreferences = getContext().getSharedPreferences(MyPREFERENCES, Context.MODE_PRIVATE);


                String mobile =  etmobile.getText().toString();

                SharedPreferences.Editor editor = sharedpreferences.edit();
                editor.putString("phoneKey", mobile);
                editor.commit();

                Toast.makeText(getContext(), "Login Done", Toast.LENGTH_SHORT).show();

            }
        });

        btnlogout.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {

                //Logout
                SharedPreferences sharedpreferences = getContext().getSharedPreferences(MyPREFERENCES, Context.MODE_PRIVATE);
                sharedpreferences.edit().remove("phoneKey").commit();

                Toast.makeText(getContext(), "Logout Done", Toast.LENGTH_SHORT).show();

            }
        });

        return view;

    }

    public void onViewCreated(@NonNull View view, Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);
    }

    @Override
    public void onDestroyView() {
        super.onDestroyView();
        binding = null;
    }

}

SecondFragment Layout Code

<?xml version="1.0" encoding="utf-8"?>
<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=".SecondFragment">

    <EditText
        android:id="@+id/etmobile"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"/>

    <Button
        android:id="@+id/btnlogin"
        android:text="Login"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"/>


    <Button
        android:id="@+id/btnlogout"
        android:text="Logout"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"/>


</LinearLayout>

Android Tutorial Day 5

Learning Objective: Let’s start exploring more fundamentals of Android.

Android Click to Dial Example

String phone = "+919876543210";
Intent intent = new Intent(Intent.ACTION_DIAL, Uri.fromParts("tel", phone, null));
startActivity(intent);

Android Click to Call Example

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


Intent intent = new Intent(Intent.ACTION_CALL, Uri.parse("tel:" + "Your Phone_number"));
startActivity(intent);

Open URL in Browser

Intent browserIntent = new Intent(Intent.ACTION_VIEW, Uri.parse("http://www.google.com"));
startActivity(browserIntent);

Android Tutorial Day 6

Learning Objective: Let’s learn how to call online API and get data from the server to our Android App. We will explore it using volley.

To add Volley Library to your Android Project, Add the following code to Gradle. Reference

dependencies {
    implementation 'com.android.volley:volley:1.2.1'
}

Now I would like to check out some live JSON API with sample data and I found the following URL:

https://jsonplaceholder.typicode.com/todos/1

Now Let’s add Volley code to fetch data from above URL

 @Override
    public View onCreateView(
            LayoutInflater inflater, ViewGroup container,
            Bundle savedInstanceState
    ) {

        callAPI();

        binding = FragmentFirstBinding.inflate(inflater, container, false);
        return binding.getRoot();

    }


    void callAPI()
    {
        
        // Instantiate the RequestQueue.
        RequestQueue queue = Volley.newRequestQueue(getContext());
        String url = "https://jsonplaceholder.typicode.com/todos/1";


        // Request a string response from the provided URL.
        StringRequest stringRequest = new StringRequest(Request.Method.GET, url,
                new Response.Listener<String>() {
                    @Override
                    public void onResponse(String response) {

                        Log.e("cs",response.toString());

                        try {

                            JSONObject obj = new JSONObject(response.toString());

                            Log.e("cs", obj.getString("userId"));
                            Log.e("cs", obj.getString("id"));
                            Log.e("cs", obj.getString("title"));
                            Log.e("cs", obj.getString("completed"));

                        } catch (Throwable t) {
                            Log.e("cs", "Could not parse malformed JSON: \"" + "" + "\"");
                        }


                    }
                }, new Response.ErrorListener() {
            @Override
            public void onErrorResponse(VolleyError error) {
                Log.e("cs",error.toString());
            }
        });

        // Add the request to the RequestQueue.
        queue.add(stringRequest);


    }

output you will get it on Log Cat. Dont forget to add internet permission into your Android Manifests

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