Home Blog Page 79

How to fetch data from database and store in CSV file format android

1
Fetch Data from Server and save it in csv file
Fetch Data from Server and save it in csv file

Hi Guys, Welcome to Proto Coders Point, In this android tutorial we will fetch data from our database (phpmyadmin) and store data in CSV file in android studio.

In other words we will learn store all the data recieved from server in to .csv file.

Final Output

android data in to csv file format

So let’s begin.

My Database structure

 This is my database with student table with some data in it

student table have data such as:

  • id
  • Firstname
  • Lastname
  • Phone

mydatabase

Creating of database and table in your phpmyadmin

just open phpmyadmin dashboard

Here create a new database named: mydatabase then in SQL tab query box copy paste below sql command/query, this command will create a new table by name “student”

database query import query

Query:

SET SQL_MODE = "NO_AUTO_VALUE_ON_ZERO";
SET time_zone = "+00:00";
-- Database: `mydatabase`
--

-- Table structure for table `student`
--
CREATE TABLE `student` (
  `id` int(11) NOT NULL,
  `firstname` varchar(20) NOT NULL,
  `lastname` varchar(20) NOT NULL,
  `phone` varchar(50) NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=latin1;

INSERT INTO `student` (`id`, `firstname`, `lastname`, `phone`) VALUES
(1, 'Rajat', 'Palankar', '875899XXX11'),
(2, 'Pavan', 'Raikar', '9585XXX454'),
(3, 'Suraj', 'Somnache', '875899XXX22'),
(4, 'Manoj', 'Raikar', '8758XX8754'),
(5, 'sahil', 'pinjar', '75848XX555');

ALTER TABLE `student`
  ADD PRIMARY KEY (`id`);

ALTER TABLE `student`
  MODIFY `id` int(11) NOT NULL AUTO_INCREMENT, AUTO_INCREMENT=7;

My Server php script to Fetch data from database

connect.php

<?php
//replace username,password with your phpmyadmin login credential
$conn = mysqli_connect("localhost", "username", "password", "mydatabase");

if($conn)
{
  //echo "Connection Success";
}
else
{
//  echo "Connection Failed";

}

//

?>

This connect.php code will help use in getting connected with our database server.

fetch_all_data.php

<?php

include 'connect.php';

$query="select * from student";

      $result=mysqli_query($conn,$query) or die('ERROR IN SELETION '.mysql_error());

      $list="";

    while($row=mysqli_fetch_array($result))
      {
          if($list=="")
            $list=$row['id']."#".$row['firstname']."#".$row['lastname']."#".$row['phone'];
          else
            $list.="@".$row['id']."#".$row['firstname']."#".$row['lastname']."#".$row['phone'];

      }

      if($list=="")
        echo "NONE";
      else
        echo $list;



?>

In above php code we are fetching all the data present in student table by using select * from student; sql command.

The above code will return data in a form of list.

each users data is been seperated using # and @. so that we can split using those symbols.

The above code response is as below:

Here @ symbol is been used to identify or split the data for individual student data.

Now, we are done with Server Side coding, let’s go to Android Studio

Android Studio Coding java

We are making use of StringBuilder that will hold all the data received from the php code(as above)

Snippit code

StringBuilder data =new StringBuilder();

data.append("id,firstname,lastname,phone"); // table row

data.append("\n"+ each_user[0]+","+ each_user[1]+","+ each_user[2]+","+ each_user[3]); // add data received from server

Step 1: Add Volley library dependencies

In your android studio project open Gradle.build(App Level) and add the below Volley library dependencies 

implementation 'com.android.volley:volley:1.1.0'

Then hit the sync now. this will download the volley library  package into your project as External library.

Step 2: Add Permission to your Project

As we need to fetch data from our server into our android application, we need to ANDROID INTERNET PERMISSION to be activated.

Internet Permission

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

The data we received from our server we gonna store it in csv format and then we need to store it in our local storage location to do so we need to add ANDROID WRITE PERMISSION

Read Write Permission

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

Then, Create a xml folder/directory under res folder and create a xml resource file by name “provider_path.xml”.  and paste the below path access code.

<?xml version="1.0" encoding="utf-8"?>
<paths xmlns:android="http://schemas.android.com/apk/res/android">
    <external-path name="external_files" path="."/>
    <files-path path="." name="name" />
</paths>

then add this file in android manifest between <application> tag

<provider
            android:name="androidx.core.content.FileProvider"
            android:authorities="com.example.dataintocsvformat"
            android:grantUriPermissions="true"
            android:exported="false">
            <meta-data
                android:name="android.support.FILE_PROVIDER_PATHS"
                android:resource="@xml/provider_path" />
</provider>

Step 3: Adding Network Configuration

Note that Andorid 7.0 Nouget (API Level 24) There is not support for unauthorized URL Request or response, So we need to provide the application with the server IP that we gonna use to fetch data from.

to do so you need to create a network_configuration.xml file in xml folder that you have created in step 2

right click on xml folder > new > xml resource file

network_security_config.xml

<?xml version="1.0" encoding="utf-8"?>
<network-security-config>
    <domain-config cleartextTrafficPermitted="true">
        <domain includeSubdomains="true">35.232.167.171</domain>   // replace with your IP address or website domain name

    </domain-config>
</network-security-config>

Then add this file in android_manifest.xml file in <application tag

<application

        android:requestLegacyExternalStorage="true"
        android:networkSecurityConfig="@xml/network_security_config"
        android:usesCleartextTraffic="true"

Step 4: Android XML

In xml file we just have a single view that is a BUTTON which on Click will fetch data from our php code and store the data in CSV file  on your android phone local device.

activity_main.xml

This only have a button for Demo purpose.

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout 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"
    android:orientation="vertical"
    android:gravity="center"
    tools:context=".MainActivity">
    <Button
        android:id="@+id/download"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Download CSV"/>
    
</LinearLayout>

Step 5: Android java code, to fetch data and store in csv file

This is the complete java code that you just need to add in MainActivity.java file

Code Explanation is given in below code as a Comment

package com.example.dataintocsvformat;

import androidx.appcompat.app.AppCompatActivity;
import androidx.core.app.ActivityCompat;
import androidx.core.content.ContextCompat;
import androidx.core.content.FileProvider;

import android.app.ProgressDialog;
import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.util.Log;
import android.view.View;
import android.widget.Button;
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.StringRequest;
import com.android.volley.toolbox.Volley;

import java.io.File;
import java.io.FileOutputStream;
import java.util.Calendar;
import java.util.HashMap;
import java.util.Map;

public class MainActivity extends AppCompatActivity {

    Button download ;
    ProgressDialog pdDialog;
    private static final int PERMISSION_REQUEST_CODE = 100;
    //php code URL path
    String URL = "http://35.232.167.171/fetch_all_data.php";
    StringBuilder data;


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

        download=(Button)findViewById(R.id.download);
        pdDialog = new ProgressDialog(MainActivity.this);
        pdDialog.setMessage("Fetching Date...");
        pdDialog.setCancelable(false);

        download.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                // to store csv file we need to write storage permission 
                // here we are checking is write permission is granted or no 
                if(checkPermission())
                {
                    FetchData(URL);

                }else{
                    // If permission is not granted we will request for the Permission
                    requestPermission();
                }
            }
        });
    }

    // fetch data from server
    private void FetchData(String url)
    {
        pdDialog.show();
        StringRequest stringRequest = new StringRequest(Request.Method.POST, url,
                new Response.Listener<String>() {
                    @Override
                    public void onResponse(String response) {

                        //we get the successful in String response 
                        Log.e("MY_DATA",response);
                        try{
                            pdDialog.dismiss();

                            if(response.equals("NONE"))
                            {
                                Toast.makeText(MainActivity.this,"NO Data Found",Toast.LENGTH_LONG).show();
                                pdDialog.dismiss();
                            }else{

                                pdDialog.dismiss();
                                // In String response we get full data in a form of list
                                splitdata(response);
                            }

                        } catch (Exception e) {
                            e.printStackTrace();

                            pdDialog.dismiss();
                        }
                    }
                }, new Response.ErrorListener() {
            @Override
            public void onErrorResponse(VolleyError error) {
                pdDialog.dismiss();

            }
        })
        {
            @Override
            protected Map<String, String> getParams() {
                Map<String,String> params = new HashMap<>();


                return params;
            }
        };

        RequestQueue requestQueue = Volley.newRequestQueue(MainActivity.this);
        requestQueue.add(stringRequest);
    }

    private void splitdata(String response) {

        System.out.println("GET DATA IS "+response);
        
       // response will have a @ symbol so that we can split individual user data
        String res_data[] = response.split("@");

        //StringBuilder  to store the data 
        data = new StringBuilder();
        
        //row heading to store in CSV file
        data.append("id,firstname,lastname,phone");
        
        for(int i = 0; i<res_data.length;i++){
            //then we split each user data using # symbol as we have in the response string
            final String[] each_user =res_data[i].split("#");


            System.out.println("Splited # ID: "+ each_user[0]);
            System.out.println("Splited # Firstname? : "+ each_user[1]);
            System.out.println("Splited # Lastname? : "+ each_user[2]);
            System.out.println("Splited # Phone ? : "+ each_user[3]);

            // then add each user data in data string builder
            data.append("\n"+ each_user[0]+","+ each_user[1]+","+ each_user[2]+","+ each_user[3]);



        }
        CreateCSV(data);
    }
    private void CreateCSV(StringBuilder data) {

        Calendar calendar = Calendar.getInstance();
        long time= calendar.getTimeInMillis();

        try {
            //
            FileOutputStream out = openFileOutput("CSV_Data_"+time+".csv", Context.MODE_PRIVATE);
            
            //store the data in CSV file by passing String Builder data
            out.write(data.toString().getBytes());
            out.close();

            Context context = getApplicationContext();
            final File newFile = new File(Environment.getExternalStorageDirectory(),"SimpleCVS");
            if(!newFile.exists())
            {
                newFile.mkdir();
            }

            File file = new File(context.getFilesDir(),"CSV_Data_"+time+".csv");


            Uri path = FileProvider.getUriForFile(context,"com.example.dataintocsvformat",file);

            //once the file is ready a share option will pop up using which you can share 
            // the same CSV from via Gmail or store in Google Drive
            Intent intent = new Intent(Intent.ACTION_SEND);
            intent.setType("text/csv");
            intent.putExtra(Intent.EXTRA_SUBJECT, "Data");
            intent.putExtra(Intent.EXTRA_STREAM, path);
            intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
            startActivity(Intent.createChooser(intent,"Excel Data"));

        } catch (Exception e) {
            e.printStackTrace();
        }

    }
    
    // checking permission To WRITE
    private boolean checkPermission() {
        int result = ContextCompat.checkSelfPermission(getApplicationContext(), android.Manifest.permission.WRITE_EXTERNAL_STORAGE);
        if (result == PackageManager.PERMISSION_GRANTED) {
            return true;
        } else {
            return false;
        }
    }

    // request permission for WRITE Access
    private void requestPermission() {
        if (ActivityCompat.shouldShowRequestPermissionRationale(MainActivity.this, android.Manifest.permission.WRITE_EXTERNAL_STORAGE)) {
            Toast.makeText(MainActivity.this, "Write External Storage permission allows us to save files. Please allow this permission in App Settings.", Toast.LENGTH_LONG).show();
        } else {
            ActivityCompat.requestPermissions(MainActivity.this, new String[]{android.Manifest.permission.WRITE_EXTERNAL_STORAGE}, PERMISSION_REQUEST_CODE);
        }
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, String permissions[], int[] grantResults) {
        switch (requestCode) {
            case PERMISSION_REQUEST_CODE:
                if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
                    Log.e("value", "Permission Granted, Now you can use local drive .");
                } else {
                    Log.e("value", "Permission Denied, You cannot use local drive .");
                }
                break;
        }
    }
}

My android_manifest.xml file 

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.example.dataintocsvformat">
    <uses-permission android:name="android.permission.INTERNET"/>
    <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>
    <uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE"/>


    <application

        android:requestLegacyExternalStorage="true"
        android:networkSecurityConfig="@xml/network_security_config"
        android:usesCleartextTraffic="true"
        android:allowBackup="true"
        android:icon="@mipmap/ic_launcher"
        android:label="@string/app_name"
        android:roundIcon="@mipmap/ic_launcher_round"
        android:supportsRtl="true"
        android:theme="@style/AppTheme">
        <activity android:name=".MainActivity">
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />

                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>

        <provider
            android:name="androidx.core.content.FileProvider"
            android:authorities="com.example.dataintocsvformat"
            android:grantUriPermissions="true"
            android:exported="false">
            <meta-data
                android:name="android.support.FILE_PROVIDER_PATHS"
                android:resource="@xml/provider_path" />
        </provider>
    </application>

</manifest>

 

Conclusion

In this Android Studio Tutorial on Proto Coders Point, we have learned how to fetch data from database using PHP code and then store the response data in .csv file format using android app.

 

Install gcloud & FileZilla, transfer files to Google Cloud Compute Engine

0
Connect FileZilla to Google Cloud

Hi Guys, Welcome to Proto Coders Point, In this Tutorial, we will Install gcloud windows 10 (Google Cloud SDK windows) and set up Google Compute Engine VM Instance, and connect FileZilla to google cloud to transfer files to your Google Cloud System.

How to download Google Cloud SDK Installer?

There are many ways by which you can install gcloud SDK on your OS, The best and easy way to install it is by using gcloud SDK installer

Download it from here, The Official gcloud website. google cloud sdk download

gcloud installer
gcloud installer

The Setup process is very simple, you just need to click next, next, next and Install.

Note: System must be connected with Internet as Installer need to download gcloud packages which may be about 450mb

Download and Install FileZilla

In this Tutorial, we are going to learn about How to use FileZilla to upload files to google cloud compute engine VM instance.

To do so, First we need to download FileZilla, So to download FileZilla please Visit  https://filezilla-project.org

Yes, After downloading Filezilla, just install it in your system by launching the setup and just hit next next, install.

Now FileZilla and Gcloud  is Successfully installed in your system

Connect FileZilla to Google cloud

Step 1: Launch gcloud SDK shell

gcloud sdk shell

Launch gcloud sdk shell run as Adminstration

gcloud auth login

now run ‘gloud auth login’ as shown in above screenshot, this command will open your default browser or ask you permission to select a browser.

Note: Keep your Google account signed in so that process will be must faster.

Then it will ask you some permission to allow access to google cloud SDK.

Just hit that Allow button

authenticated with the google cloud SDK

Now you have Successfully connect command shell with google cloud.

Step 2 : Generate filezilla ppk file

Then, you need to generate .ppk file so that you can add it to SFTP in your filezilla settings to connect to gcloud system.

To generate .ppk file you need to run gcloud command of your Compute Engine VM Instance

to get that command go to your Google Cloud Console > open Compute Engine → VM instance → Select VM Instance and Copy gcloud command line under SSH.

view gcloud command vm instance

NOTE: Below command is my gcloud computer engine number, so don’t run the below command as it is, to get your system command follow above steps properly.

Then Copy your system gcloud command and paste in your gcloud SDK shell.

gcloud command to generate ppk
genetated ppk file

This Command will generate .ppk file that need to add in filezilla SFTP settings.

Now we are done with generating google_compute_engine.ppk file now you need to add this file  in your Filezilla SFTP settings.

Step 3 : FileZilla SFTP setting add new key .ppk file

Now launch FilaZilla software and add the new key

go to Edit > setting and add the ppk file you have generated using gcloud command, as shown in below screenshot

setting sftp in filezilla setting

Step 4 : Add your Google Site to FileZilla

Go to File > Site Manager and add new site

filezilla google cloud site manager add

protocal : select SFTP

host : get the host ip address of you google cloud system in Compute Engine VM Instance. as shown below

how to get my google cloud ip address

username  and password will be same as your google account first name For example : my name is Rajat Palankar so my username and passwork will be rajat.

and then just hit the connect button, now filezilla will get connected to your google cloud system.

filezilla connected successfully to google cloud system

Step 5 : Change Owner of /var/www/html ( Optional )

By Default, the permission of file path /var/www/html will be  _rw_r__r__ and by this you can’t save or make changed or create a new file, to do so you need to change the Owner of that path. then now you can use Filezilla to transfer files

sudo chown username -R /var/www/html
change file owner

Conclusion

In this Tutorial article we learned how to install gcloud in windows, how to generate .ppk file using gcloud command and then use that .ppk file to connect to google cloud compute engine VM Instance using FileZilla

How to change whole app language in android programmatically

0

Hi Guys, Welcome to Proto Coders Point, In this Android Tutorial we will create an app that can support multiple languages, In other words, the user can select his desired language to change the whole app language in android.

This is a Simple Example of how to make an android multi language app with an example – locale in android.

how to change app language android
DEMO

Video Tutorial on change whole app language android programmatically

Step 1 − Create a new Android Project in Android Studio

Create a new project in Android Studio, go to File ⇒ New Project and fill all required details to create a new project. ( Name it as Change App language)

Step 2 – Create a new strings.xml with locale

In the values directory, you need to create a separate string.xml(hi) or any other language

Here is how to create a locale in android string with a language

right-click on values directory => New => Values Resource File

The below dialog will pop up in the android studio

Here you need to select your locale languages that your app will support.

how to create locale string in android
how to create locale string in android

After creating saperate strings.xml files for particular languages your string directory will look something like this.

strings xml to change app languages

Now in those strings.xml file add the translated strings

string.xml (hi) for hindi language in your android app.

<?xml version="1.0" encoding="utf-8"?>
<resources>
    <string name="app_name">ऐप भाषा बदलें</string>
    <string name="language">नमस्ते दुनिया</string>
</resources>

string.xml (kn) for Kannada language in your app.

<?xml version="1.0" encoding="utf-8"?>
<resources>
    <string name="app_name">ಅಪ್ಲಿಕೇಶನ್ ಭಾಷೆ</string>
    <string name="language">ಹಲೋ ವರ್ಲ್ಡ್</string>
</resources>

likewise you can add different language that you want to add into your android applicaton.

Step 3 – Create a LocaleHelper Class

Now create new java file and name it as Localehelper and add the below code

This class will help you in getting and storing language that a user has previously selected before he close the application, we will use SharedPreferences to store the locale selected by user in app.

package com.example.applanguagechange.Language;

import android.annotation.TargetApi;
import android.content.Context;
import android.content.SharedPreferences;
import android.content.res.Configuration;
import android.content.res.Resources;
import android.os.Build;
import android.preference.PreferenceManager;

import java.util.Locale;

/**
 * Created by abdalla on 10/2/17.
 */

public class LocaleHelper {

    private static final String SELECTED_LANGUAGE = "Locale.Helper.Selected.Language";

    public static Context onAttach(Context context) {
        String lang = getPersistedData(context, Locale.getDefault().getLanguage());
        return setLocale(context, lang);
    }

    public static Context onAttach(Context context, String defaultLanguage) {
        String lang = getPersistedData(context, defaultLanguage);
        return setLocale(context, lang);
    }

    public static String getLanguage(Context context) {
        return getPersistedData(context, Locale.getDefault().getLanguage());
    }

    public static Context setLocale(Context context, String language) {
        persist(context, language);

        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
            return updateResources(context, language);
        }

        return updateResourcesLegacy(context, language);
    }

    private static String getPersistedData(Context context, String defaultLanguage) {
        SharedPreferences preferences = PreferenceManager.getDefaultSharedPreferences(context);
        return preferences.getString(SELECTED_LANGUAGE, defaultLanguage);
    }

    private static void persist(Context context, String language) {
        SharedPreferences preferences = PreferenceManager.getDefaultSharedPreferences(context);
        SharedPreferences.Editor editor = preferences.edit();

        editor.putString(SELECTED_LANGUAGE, language);
        editor.apply();
    }

    @TargetApi(Build.VERSION_CODES.N)
    private static Context updateResources(Context context, String language) {
        Locale locale = new Locale(language);
        Locale.setDefault(locale);

        Configuration configuration = context.getResources().getConfiguration();
        configuration.setLocale(locale);
        configuration.setLayoutDirection(locale);

        return context.createConfigurationContext(configuration);
    }

    @SuppressWarnings("deprecation")
    private static Context updateResourcesLegacy(Context context, String language) {
        Locale locale = new Locale(language);
        Locale.setDefault(locale);

        Resources resources = context.getResources();

        Configuration configuration = resources.getConfiguration();
        configuration.locale = locale;
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN_MR1) {
            configuration.setLayoutDirection(locale);
        }

        resources.updateConfiguration(configuration, resources.getDisplayMetrics());

        return context;
    }
}

Step 4 –  UI Design

activity_main.xml 

Add the following code to res/layout/activity_main.xml.

<?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"
    tools:context=".MainActivity"
    android:layout_gravity="center"
    android:gravity="center"
    android:orientation="vertical">

    <TextView
        android:id="@+id/helloworld"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Hello World!"
        android:textSize="20sp"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintLeft_toLeftOf="parent"
        app:layout_constraintRight_toRightOf="parent"
        app:layout_constraintTop_toTopOf="parent" />

    <RelativeLayout
        android:id="@+id/showlangdialog"
        android:layout_width="200dp"
        android:layout_height="40dp"
        android:layout_marginTop="10dp"
        android:layout_marginEnd="3dp"
        android:layout_marginRight="3dp"
        android:background="@drawable/background_color"
        android:orientation="horizontal">

        <TextView
            android:id="@+id/dialog_language"
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            android:layout_alignParentBottom="true"
            android:layout_gravity="center"
            android:gravity="center"
            android:background="@android:color/transparent"
            android:dropDownVerticalOffset="35dp"
            android:popupBackground="@color/colorPrimary"
            android:textColor="@color/white"
            android:text="English"
             />

        <ImageView
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_alignParentRight="true"
            android:layout_centerVertical="true"
            android:layout_gravity="center"
            android:layout_marginRight="10dp"
            android:src="@drawable/drop" />

    </RelativeLayout>

</LinearLayout>

@drawable/spinner_background.xml

create a new drawable resource file under drawable folder and add the below code.

This code is just to give background to above relativelayout

<shape xmlns:android="http://schemas.android.com/apk/res/android">
    <solid android:color="@color/colorPrimary"
        />
    <corners android:radius="40dp" />
    <stroke
        android:width="1dp"
        android:color="#05AC21" />
</shape>

Create a vector drop image in drawable folder

Right Click(drawable) > New > Vector Image ( select a arrow down vector image )

Step 5 –  Java Code to switch between string.xml to use

Main_Activity.java

package com.example.applanguagechange;

import androidx.appcompat.app.AlertDialog;
import androidx.appcompat.app.AppCompatActivity;

import android.content.Context;
import android.content.DialogInterface;
import android.content.res.Resources;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.RelativeLayout;
import android.widget.TextView;

public class MainActivity extends AppCompatActivity {

    TextView helloworld,dialog_language;
    int lang_selected;
    RelativeLayout show_lan_dialog;


    Context context;
    Resources resources;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        dialog_language = (TextView)findViewById(R.id.dialog_language);
        helloworld =(TextView)findViewById(R.id.helloworld);
        show_lan_dialog = (RelativeLayout)findViewById(R.id.showlangdialog);

        if(LocaleHelper.getLanguage(MainActivity.this).equalsIgnoreCase("en"))
        {
            context = LocaleHelper.setLocale(MainActivity.this,"en");
            resources =context.getResources();
            dialog_language.setText("ENGLISH");
            helloworld.setText(resources.getString(R.string.hello_world));
            setTitle(resources.getString(R.string.app_name));
            lang_selected = 0;

        }else if(LocaleHelper.getLanguage(MainActivity.this).equalsIgnoreCase("hi")){
            context = LocaleHelper.setLocale(MainActivity.this,"hi");
            resources =context.getResources();
            dialog_language.setText("हिन्दी");
            helloworld.setText(resources.getString(R.string.hello_world));
            setTitle(resources.getString(R.string.app_name));
            lang_selected =1;
        }
        else if(LocaleHelper.getLanguage(MainActivity.this).equalsIgnoreCase("kn")){
            context = LocaleHelper.setLocale(MainActivity.this,"kn");
            resources =context.getResources();
            dialog_language.setText("ಕನ್ನಡ");
            helloworld.setText(resources.getString(R.string.hello_world));
            setTitle(resources.getString(R.string.app_name));
            lang_selected =2;
        }

        show_lan_dialog.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                final String[] Language = {"ENGLISH","हिन्दी","ಕನ್ನಡ"};
                final int checkItem;
                Log.d("Clicked","Clicked");


                final AlertDialog.Builder dialogBuilder = new AlertDialog.Builder(MainActivity.this);
                dialogBuilder.setTitle("Select a Language")
                              .setSingleChoiceItems(Language, lang_selected, new DialogInterface.OnClickListener() {
                                  @Override
                                  public void onClick(DialogInterface dialogInterface, int i) {
                                      dialog_language.setText(Language[i]);

                                      if(Language[i].equals("ENGLISH")){
                                           context = LocaleHelper.setLocale(MainActivity.this,"en");
                                           resources =context.getResources();
                                           lang_selected = 0;

                                           helloworld.setText(resources.getString(R.string.hello_world));
                                           setTitle(resources.getString(R.string.app_name));

                                      }
                                      if(Language[i].equals("हिन्दी"))
                                      {
                                          context = LocaleHelper.setLocale(MainActivity.this,"hi");
                                          resources =context.getResources();
                                          lang_selected = 1;
                                          helloworld.setText(resources.getString(R.string.hello_world));
                                          setTitle(resources.getString(R.string.app_name));
                                      }
                                      if(Language[i].equals("ಕನ್ನಡ"))
                                      {
                                          context = LocaleHelper.setLocale(MainActivity.this,"kn");
                                          resources =context.getResources();
                                          lang_selected = 2;
                                          helloworld.setText(resources.getString(R.string.hello_world));
                                          setTitle(resources.getString(R.string.app_name));
                                      }
                                  }
                              })
                        .setPositiveButton("OK", new DialogInterface.OnClickListener() {
                             @Override
                             public void onClick(DialogInterface dialogInterface, int i) {
                                   dialogInterface.dismiss();
                                }
                });
                dialogBuilder.create().show();
            }
        });

    }
}

Here in above code we have  a RelativeLayout with OnClickEvent, Then user will click the RelativeLayout a AlertDialog will popup asking for language selection, by using which user can change language of his application.

For Example: When user select language as Hindi, The strings.xml (hi) will get loaded and all the text in the application will turn it language string that come from strings.xml (hi), likewise if user select kannada as his app language then strings gets loaded from strings.xml(kn).

and if he select language as English all language will come back to default string.xml

Conclusion

In this tutorial we learnt how to change whole app language in android programmatically using strings.xml locale.

Android Whatsapp Intent | Sending Message from your app to whatsapp

0
android whatsapp api send message

Hi Guys, Welcome to Proto Coders Point, In this android tutorial we will integrate sending message from your android application to whatsapp using whatsapp send message api service.

Video Tutorial on Youtube on android whatsapp intent

Send Message android whatsapp intent

Step 1 : Create a new Android Project

Off-Course you need a android Project to be created in android studio or open any existing project

File > New > New Project  give a name to the project as “whatsapp intent send Message”   hit the finish button

Step 2 : Adding Country Code Picker library

Open build.gradle (app level) and in dependencies section add the below implementation code.

implementation 'com.hbb20:ccp:2.4.0'

then, After adding the dependencies hit the Sync Now button

country code picker android library

Official Site to learn more about Country Code Picker

Step 3 : Custom EditText Background Design

To create a custome EditText Background Design you need to create a new Drawable Resource File to do so Right Click on drawable folder under app > res > drawable

Then, Name the Drawbale Resource file as “rounded_edittext.xml” and paste the below code in it.

<?xml version="1.0" encoding="utf-8"?>
<!-- res/drawable/rounded_edittext.xml -->
<shape xmlns:android="http://schemas.android.com/apk/res/android"
    android:padding="10dp"
    android:shape="rectangle" >

    <solid android:color="#FFFFFF" />

    <corners
        android:bottomLeftRadius="10dp"
        android:bottomRightRadius="10dp"
        android:topLeftRadius="10dp"
        android:topRightRadius="10dp" />

</shape>

Step 4 : UI Design

For this project we have 2 editText, a Country Code Picker  and a Button to send the message through whatsapp intent.

whatsapp ui design

activity_main.xml

<?xml version="1.0" encoding="utf-8"?>
<ScrollView 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=".MainActivity"
    android:orientation="vertical"
    android:background="@drawable/whatsapp">

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:orientation="vertical">

    <TextView
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="WhatsApp Intent Send message Example"
        android:textColor="@android:color/white"
        android:gravity="center"
        android:textStyle="bold"
        android:layout_marginTop="10dp"
        android:textSize="20sp"/>

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:orientation="horizontal"
        android:padding="10dp"
        >

        <com.hbb20.CountryCodePicker

            app:ccp_arrowColor="#FFF"
            app:ccp_contentColor="#FFF"
            android:id="@+id/ccp"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content" />

        <EditText
            android:id="@+id/phonenumber"
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            android:hint="Enter Phone Number"
            android:paddingLeft="10dp"
            android:inputType="phone"
            android:background="@drawable/rounded_edittext"
            android:layout_marginLeft="5dp" />


    </LinearLayout>

        <EditText
            android:id="@+id/messages"
            android:layout_width="match_parent"
            android:layout_height="300dp"
            android:layout_marginTop="10dp"
            android:background="@drawable/rounded_edittext"
            android:gravity="start"
            android:hint="Enter Your Message"
            android:inputType="textMultiLine"
            android:paddingLeft="15dp"
            android:paddingTop="10dp" />

        <Button
        android:id="@+id/sendbutton"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:background="#4CAF50"
        android:drawableRight="@drawable/messageicon"
        android:paddingRight="20sp"
        android:textColor="#FFF"
        android:textSize="15sp"
        android:layout_margin="15dp"
        android:text="Send Message Through WhatsApp"
        />

    </LinearLayout>
</ScrollView>

Step 5 : JAVA code

MainActivity.java

package com.example.whatsappintentsendmsg;

import androidx.appcompat.app.AppCompatActivity;

import android.content.Intent;
import android.content.pm.PackageManager;
import android.net.Uri;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;

import com.hbb20.CountryCodePicker;

public class MainActivity extends AppCompatActivity {

    EditText phoneno,message;
    CountryCodePicker ccpp;
    Button sendButton;
    String messageStr,phoneStr ="";

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

        phoneno = ( EditText) findViewById(R.id.phonenumber);
        message =(EditText)findViewById(R.id.messages);
        ccpp=(CountryCodePicker)findViewById(R.id.ccp);
        sendButton=(Button)findViewById(R.id.sendbutton);

        sendButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {

                messageStr = message.getText().toString().trim();
                phoneStr = phoneno.getText().toString().trim();

                if(phoneStr.isEmpty())
                {
                    phoneno.setError("Please Enter Phone");
                } else if (messageStr.isEmpty())
                {
                    message.setError("Please Enter Message");
                }else{
                    ccpp.registerCarrierNumberEditText(phoneno);
                    phoneStr = ccpp.getFullNumber();

                    boolean isInstalled = WhatsappAvailable("com.whatsapp");

                    //if whatsapp is installed it will be true or else isInstalled will become false
                    if(isInstalled)
                    {
                        //Whatsapp send message using Instant
                        Intent whatsapp = new Intent(Intent.ACTION_VIEW,Uri.parse("https://api.whatsapp.com/send?phone="+phoneStr+"&text="+messageStr));

                        startActivity(whatsapp);
                        phoneno.setText("");
                        message.setText("");

                    }else
                    {
                        Toast.makeText(MainActivity.this,"Whatsapp is not Installed on your Device",Toast.LENGTH_SHORT).show();
                    }
                    
                }

            }
        });
    }

    //check is whatsapp is installed on the Device
    private  boolean WhatsappAvailable(String uri)
    {
        PackageManager packageManager = getPackageManager();
        boolean isInstalled;
        try{
            packageManager.getPackageInfo(uri,PackageManager.GET_ACTIVITIES);
            isInstalled = true;

        }catch (PackageManager.NameNotFoundException e){
           isInstalled = false;

        }
        return  isInstalled;
    }


}