Home Blog Page 75

Flutter vs React Native 2021 – What to learn for 2021?

1
Flutter vs reach native 2020 - which to choose in 2021

Hi Guys, Welcome to Proto Coders Point, In this Blog Post we will discuss on Flutter vs React Native 2020, year is almost at the end so, which is best flutter or react native in 2021 for your development career.

Introduction to Flutter and React Native

What is Flutter? Who created Flutter?

A Flutter is a development framework/Kit, which is created by Google and it’s team. By using flutter as a development kit you can develop applications for Android, iOS and Web that too from a single codebase (Code once and build installation setup for various platform)

Hello, World program in Flutter looks like this:

import 'package:flutter/material.dart';

void main() => runApp(HelloWorldApp());

class HelloWorldApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {

    //MaterialApp acts as a wrapper to the app and 
    //provides many features like title,home,theme etc   
    return MaterialApp(
      title: 'Hello World App',

      //Scaffold acts as a binder that binds the appBar,
      //bottom nav bar and other UI components at their places     
      home: Scaffold(

          //AppBar() widget automatically creates a material app bar
        appBar: AppBar(
          title: Text('Hello World App'),
        ),

        //Center widget aligns the child in center
        body: Center(
          child: Text('Hello World'),
        ),
      ),
    );
  }
}

Check out this tutorial how to install flutter and build your first Hello World app in flutter

What is React Native? Who created Flutter?

React Native is one for the famous framework used to develop applications for Android, iOS, web and more, React Native helps developer to use react along with native platform capabilities.

React Native also allows developers to write native code in languages such as Java for Android and Objective-C or Swift for iOS which make it even more flexible.

Hello, World program in React Native looks like this:

import React, { Component } from 'react';
import { Text, View } from 'react-native';

export default class HelloWorldApp extends Component {
  render() {
    return (
      <View style={{ flex: 1, justifyContent: "center", alignItems: "center" }}>
        <Text>Hello, world!</Text>
      </View>
    );
  }
}

Pros and Cons of Flutter

Pros :

  • Easy to Learn and user friendly to designs user interface
  • it has a number of “ready to use” widgets in which most of the widgets help in material design UI concepts.
  • since it supports Hot Reload it makes testing faster and it provides fast coding.

Cons:

  • The widgets used in flutter adaptive so they need to be configured manually so that they can adapt.
  • Packages are fewer as that compared with the react native.
  • It becomes a bit harder to pickup with dart.
  • community support is less as flutter dart is new in market.

If you are good in beginner in flutter and looking job to learn more and get experience then here are some Flutter Interview Question and Answer that may be asked to you in interview round

Pros and cons of React Native

Pros

  • In react native the widgets avaliable are  adaptive automatically.
  • It can be easily understandable if one is familiar with javascript.
  • there are more number of packages avaliable here.
  • Strong community support as it been 5 year being in market.

Cons:

  • Less smooth navigation.
  • Lack of custom modules.
  • Facebook have many team and condition while using react native.

Difference between Flutter and React Native

 FlutterReact Native
Brief aboutA portable UI toolkit for building natively-compiled apps across mobile, web, and desktop* from a single codebaseA framework for building native applications using React
Release DateDecember 2018March 2015
Created byGoogleFacebook
Programming language usedDartJavaScript
open source?YESYES
Hot Reload Support?YESYES
Tops App developed using this FrameworkXianyu app by Alibaba, Hamilton app for Hamilton Musical, Google Ads appInstagram, Facebook, Facebook Ads, Skype, Tesla
Competitive advantageLooks Great and Speed UI designing thanks to rich widgets.

 

Flutter is growing rapidly and the community is also growing faster.

The support team for Flutter is getting stronger and Flutter comes with Excellent documentation work, which makes development easily.

Difficult to beat time-to-market length

It’s been Stability in market from last 5 years. And is getting great success.

 

Easy to learn technology as plenty of online tutorial are available.

React Native come with plenty of libraries and will make development much faster and easy to develop.

Code can be easily be re-used frm both web app and desktop application.

Recommended Article

Different between react and angular

Learn Angular – Build first web app using angular

Flutter vs React native

7 best tools for react development

How to use bootstrap in React

How to create custom hooks in react

Invisible Cloak From Harry Potter using python opencv

0

Hi Guys , Welcome to proto coders point, In this python tutorial we will implement invisible cloak from harry potter using python opencv library.

what are python libraries to use invisible cloak?

What is numpy?

This is python libraries where we are using for arrays perpose in our project.

what is opencv?

In this library we are using opencv to capture the video.

What is Time?

so we are using time to capture the video in that time.

Step 1 :Create new python project 

First we have to create a new python project to work on this invisible cloak.

File > New Project

Step 2 :Create a new python file to handle invisible cloak harry poter.

You need to create a new python file where you can write python code.

 Right click on Project > New > Python File

i have created a new python file with name as ” invisibility cloakusing pycharm IDE.

Step 3 : Add library in your python project.

How to install the numpy , opencv-python , time  module ?

File > Setting > Project Interpretor > Click on ” + ” >  Search for “numpy,python-opencv” then select the package and then click on install package button.

step 4 : Open the python file “invisible”

import cv2
import numpy as np
import time
out_name = "output_shri.avi"
cap = cv2.VideoCapture(0)
fourcc = cv2.VideoWriter_fourcc(*'XVID')
out = cv2.VideoWriter('shri.mp4' , fourcc, 20.0, (640,480))
time.sleep(2)
background = 0#capturing background
for i in range(30):
    ret, background = cap.read()#capturing image
while(cap.isOpened()):
    ret, img = cap.read()
    
    if not ret:
        break
        
    hsv=cv2.cvtColor(img, cv2.COLOR_BGR2HSV)
    lower_red = np.array([0,120,70])
    upper_red = np.array([10,255,255])
    mask1 = cv2.inRange(hsv , lower_red , upper_red)
    
    lower_red = np.array([170,120,70])
    upper_red = np.array([180,255,255])
    mask2 = cv2.inRange(hsv , lower_red , upper_red)
    
    mask1 = mask1 + mask2 #OR
    mask1=cv2.morphologyEx(mask1, cv2.MORPH_OPEN ,np.ones((3,3) , np.uint8) , iterations=2)
        
    mask2=cv2.morphologyEx(mask1, cv2.MORPH_DILATE ,np.ones((3,3) , np.uint8) , iterations=1)
        
    mask2 = cv2.bitwise_not(mask1)
    
    res1 = cv2.bitwise_and(background, background, mask=mask1)
    res2 = cv2.bitwise_and(img, img, mask=mask2)
    
    final_output = cv2.addWeighted(res1 , 1, res2 , 1, 0)
    
    cv2.imshow('Harry' , final_output)
    k=cv2.waitKey(10)
    if k==27:
        break
        
cap.release()
cv2.destroyAllWindows()

As we have installed the numpy ,opencv-python model in our project now you can just import the which ever library we have installed then we write the farther code.then we have  to capturing the video.after capturing video we have to give the camera to warm up.

Capturing the background in range of 60 .you should have video that have some seconds to dedicated to background farm so that it cloud easily save the background  image.

Then we are reading from video.so we are convert the image -BGR to HSV as we focused on detection of red color. and then converting BGR to HSV for better detection or you can convert it to gray.

we have ranges should be carefully chosen the setting the lower and upper range for mask1.some setting the lower and upper range for mask2.then it replaced with some other code depending upon the color of your cloth.then refining the mask corresponding to the detected red color.then we are generating the final output  

1.5. Final Result

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.