Home Blog Page 33

Gridview in Android using Base Adopter

0
Gridview in Android using Base Adopter
Gridview in Android using Base Adopter

Base Adapter android is simple a base class that is used in implementation of any Adopter that can be used in variour activity in android like ListView  or GridView.

So In this Article we need Customize the GridView by creating our own Custom Adopter that extends BaseAdopter

Below is the example of GridView in Android, In which we show the Android Version logo’s in the form of Grids.

Gridview in Android using Base Adopter

Step1: Create a new Android project in Android Studio as usually and you need to fill all the required details.

In our case we have named GridView Using Base Adopter  and package protocoderspoint.com.griviewbaseadopter

GridView Using Base Adapter
GridView Using Base Adapter

Step 3 : Now, Just Open activity_main.xml  design and paste the below xml code in that file.

Here i have created a  GridView with have set with number of columns as 3.

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical">

    <GridView
        android:id="@+id/simpleGridView"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:footerDividersEnabled="false"
        android:padding="1dp"
        android:layout_margin="10dp"
        android:numColumns="3" /> <!-- GridView with 3 value for numColumns attribute -->
</LinearLayout>

Step 3: :  Ok then Create a new XML file  I have named the new file as gridview_image.xml. because we are just displaying a Image using ImageView and a Text with TextView.

Then the CustomAdopter to set the andorid version logo images.

You can just Copy paste below xml code

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:padding="1dp"
    android:orientation="vertical"
    android:layout_margin="10dp">
    <ImageView
        android:id="@+id/icon"
        android:layout_width="match_parent"
        android:layout_height="120dp"
        android:scaleType="fitXY"
        android:layout_gravity="center_horizontal"
        android:src="@drawable/logo1"
        />

    <TextView
        android:id="@+id/text1"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:text="logo1"/>
</LinearLayout>

Adding Images in to Drawable Folder

Then  Here you need to download come images and paste it into drawable folder of your android project.

Keep in mind that image size should not be more then 2 mb else the app might force stop.

Now, Name all the images as logo1,logo2 and so on.

Step 5: Create a new class CustomAdapter.java and paste the below code.

CustomAdopter.java

Then, Now We have to create a CustomAdopter.java class That is Extends BaseAdapter in it.

In CustomAdopter we will set image logo’s and set it’s text under the imageview logo.

package protocoderspoint.com.gridviewusingbaseadapter;

import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.ImageView;
import android.widget.TextView;

public class CustomAdapter extends BaseAdapter {
    Context context;
    int logos[];
    LayoutInflater inflter;
    String title[];
    public CustomAdapter(Context applicationContext, int[] logos,String[] text) {
        this.context = applicationContext;
        this.logos = logos;
        inflter = (LayoutInflater.from(applicationContext));
        this.title=text;
    }
    @Override
    public int getCount() {
        return logos.length;
    }
    @Override
    public Object getItem(int i) {
        return null;
    }
    @Override
    public long getItemId(int i) {
        return 0;
    }
    @Override
    public View getView(int i, View view, ViewGroup viewGroup) {
        view = inflter.inflate(R.layout.gridview_image, null); // inflate the layout
        ImageView icon = (ImageView) view.findViewById(R.id.icon); // get the reference of ImageView
        icon.setImageResource(logos[i]); // set logo images

        TextView textView = (TextView)view.findViewById(R.id.text1);
        textView.setText(title[i]);
        return view;
    }
}

Step 6 : Copy below code in Main_Activity.java

package protocoderspoint.com.gridviewusingbaseadapter;

import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.AdapterView;
import android.widget.GridView;

import androidx.appcompat.app.AppCompatActivity;

public class MainActivity extends AppCompatActivity {
    GridView simpleGrid;

    int logos[] = {R.drawable.logo1, R.drawable.logo2, R.drawable.logo3,R.drawable.logo4,R.drawable.logo5,R.drawable.logo6,R.drawable.logo7,R.drawable.logo8};

    String title[]={"Cup Cake","Donut","Eclair","Froya","Gingerbread","Kitkat","Lollipop","And Much More"};
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        simpleGrid = (GridView) findViewById(R.id.simpleGridView); // init GridView

        // Create an object of CustomAdapter and set Adapter to GirdView
        CustomAdapter customAdapter = new CustomAdapter(getApplicationContext(), logos,title);

        simpleGrid.setAdapter(customAdapter);

        // implement setOnItemClickListener event on GridView
        simpleGrid.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                // set an Intent to Another Activity
                Intent intent = new Intent(MainActivity.this, activity_second.class);
                intent.putExtra("image", logos[position]); // put image data in Intent
                startActivity(intent); // start Intent
            }
        });
    }
}

 

All is set and app is ready that display girdview with images in 3 columns but when its is clicked i need to open second activity to open which simply shows the image with the gridview image is been clicked

Step 7: Now Create a new Activity with name activity_second.class.

To create new Activity just follow this steps :

Right click of Project  > New >Activity > Empty Activity

And name it as activity_second, this will create both java file as well as xml file

Step 8: Open Second Actvity xml file and copy paste below code, Our Second Activity to display the android version logo image in full size, by which gridView imageis been clicked.

activity_second.xml

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"

    android:background="#fff"
    tools:context=".activity_second">
    <ImageView
        android:id="@+id/selectedImage"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_centerInParent="true"
        android:scaleType="fitXY" />
</RelativeLayout>

Step 9: Now Open a new Activity that we have created just with name activity_second.java and add below code in it.

package protocoderspoint.com.gridviewusingbaseadapter;

import android.content.Intent;
import android.os.Bundle;

import android.widget.ImageView;

import androidx.appcompat.app.AppCompatActivity;

public class activity_second extends AppCompatActivity {
    ImageView selectedImage;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_second);
        selectedImage = (ImageView) findViewById(R.id.selectedImage); // init a ImageView
        Intent intent = getIntent(); // get Intent which we set from Previous Activity
        selectedImage.setImageResource(intent.getIntExtra("image", 0)); // get image from Intent and set it in ImageView
    }
}

Android Registration Tutorial PHP MySQL using HttpURLConnection class

8
Android Registration Tutorial PHP MySQL using HttpURLConnection class
Android Registration Tutorial PHP MySQL using HttpURLConnection class

As you may know that Google Android has deprecated it support for Apache module i.e (HttpPost and HttpGet and HttpClient and many more class that has Apache module) since API level 22, Now the alternate way is to use JAVA’s HttpURLConnection Class.

This tutorial depicts the Android Registration form to deal with GET and POST data using HttpURLConnection class.

So then lets us start implementing a Registration form in android that stores data into MySQL phpmyadmin database using HttpURLConnection class.

Step 1: Creating a database in Phpmyadmin dashboard

if i say, I am making use of localhost to work with phpmyadmin MySQL service. you can use any of your hosting either webhosting which has phpmyadmin installed or your localhost that has WampServer installed.

how to create database in phpmyadmin
how to create database in phpmyadmin

then, login into your phpmyadmin dashboard and and create a new Database,

I have created a database name Coders (just for this tutorial)  you can specific any name for that database.

CREATE DATABASE databasename;

now, database is ready it time to create table names as register.

There are 2 ways for creating table in phpmyadmin

1st way

CREATE TABLE Coders (
    id int NOT NULL AUTO_INCREMENT,
    name varchar(20) NOT NULL,
    city varchar(20) NOT NULL,
    phone varchar(12) NOT NULL,
    CONSTRAINT Coders PRIMARY KEY (id)
);

2nd way

the second way for creating table is using phpmyadmin dashborad

creating table is using phpmyadmin dashborad

In Registration table i have for data entries where i can store data values

id: which is simple a integer value that simple store numbers that i have defined a auto increment and primary key value.

name: which stored name of the user.

city: holds place of the user.

phone: holds mobile number of the user.

All set on server side work.

Step 2 : Php code that handle storing data that if recieved from android app

conn.php

<?php
$db_name="Coders"; // database name
$mysql_username="replace with your login id";
$mysql_password="replace with your password";
$server_name="localhost";
$conn = mysqli_connect($server_name,$mysql_username,$mysql_password,$db_name);
if($conn)
{
  //echo "Connection Success";
}
else
{
  //echo "Connection Failed";

}
?>

Connection php page is user to get connected to phpmyadmin database

$db_name=”Coders”; // database name

$mysql_username=”replace with your login id”;  username that you use to login in to phpmyadmin server

$mysql_password=”replace with your password”; password that you use to sign in.

$server_name=”localhost”;  use localhost if you have phpmyadmin installed in you system or else use you doman name or IP address.

registration.php

<?php
    include('conn.php');
    if($_SERVER['REQUEST_METHOD'] == 'POST')
  {		

   
  $fname=$_POST['name']; //data recieved from android app
  $city=$_POST['city'];
  $phone=$_POST['phone'];
  
  $query="select * from registration where phone='$phone'";
  
        $result=mysqli_query($conn,$query);
    if(mysqli_num_rows($result)>0)
    {	
           while($row=mysqli_fetch_array($result))
          {
            echo trim("false");
          }
    }
        else
        {
          $query="insert into registration (name,city,phone) values ('$fname','$city','$phone');";
          mysqli_query($conn,$query);
          echo trim("true");
        }
  }   
?>	

registration php code page is use to get data from android code and send it to phpmyadmin to store that data  recieved into database.

EG: $fname=$_POST[‘name’];  :  data will be recieved from android application  to php code

insert query : insertion query will be run to store the recieved data in database.

Step 3 : android studio implementing httpURLConnection class

This Android Php project contains two android activities, MainActivity.java and SuccessActivity.java.

MainActivity is actual Registration form where you can register himself using name,city and phone number and a submit button when clicked the user get registered

SuccessActivity is a plain activity form which simple show a success message of the user screen when the registration is been successfully done.

Designing app UI using XML code

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:orientation="vertical"
    android:layout_gravity="center_horizontal"
    android:gravity="center_horizontal"
    android:layout_margin="10dp">

    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Proto Coders Point"
        android:textSize="25sp"
        android:textColor="#0057FF"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintLeft_toLeftOf="parent"
        app:layout_constraintRight_toRightOf="parent"
        app:layout_constraintTop_toTopOf="parent" />

    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Registration Form" />

    <EditText
        android:id="@+id/name"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:ems="10"
        android:layout_marginTop="10dp"
        android:inputType="textPersonName"
        android:hint="NAME" />

    <EditText
        android:id="@+id/city"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:ems="10"
        android:layout_marginTop="10dp"

        android:inputType="textPersonName"
        android:hint="CITY" />

    <EditText
        android:id="@+id/phone"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:ems="10"
        android:layout_marginTop="10dp"
        android:inputType="textPersonName"
        android:hint="PHONE" />

    <Button
        android:id="@+id/submit"
        android:background="#6F9AF8"
        android:textColor="#FFF"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_marginTop="10dp"
        android:text="SUBMIT" />


</LinearLayout>

Java Code to Run the data transfer process

Snippet code of how to use HttpURLConnection class in andoid

try {
                // Setup HttpURLConnection class to send and receive data from php and mysql
                conn = (HttpURLConnection)url.openConnection();
                conn.setReadTimeout(READ_TIMEOUT);
                conn.setConnectTimeout(CONNECTION_TIMEOUT);
                conn.setRequestMethod("POST");

                // setDoInput and setDoOutput method depict handling of both send and receive
                conn.setDoInput(true);
                conn.setDoOutput(true);

                // Append parameters to URL
                Uri.Builder builder = new Uri.Builder()
                        .appendQueryParameter("username", params[0])
                        .appendQueryParameter("password", params[1]);
                String query = builder.build().getEncodedQuery();

                // Open connection for sending data
                OutputStream os = conn.getOutputStream();
                BufferedWriter writer = new BufferedWriter(
                        new OutputStreamWriter(os, "UTF-8"));
                writer.write(query);
                writer.flush();
                writer.close();
                os.close();
                conn.connect();

            } catch (IOException e1) {
                // TODO Auto-generated catch block
                e1.printStackTrace();
                return "exception";
            }

MainActivity.java

The complete java code is below

package protocoderspoint.com.localhostphpmyadmin;

import androidx.appcompat.app.AppCompatActivity;

import android.app.ProgressDialog;
import android.content.Intent;
import android.net.Uri;
import android.os.AsyncTask;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;

import org.apache.http.client.ClientProtocolException;

import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.net.HttpURLConnection;
import java.net.URL;

public class MainActivity extends AppCompatActivity {

    Button Submit;
    EditText name,city,phone;
    ProgressDialog pdDialog;
    String URL_REGISTER="http://192.168.0.10/protocoderspoint/register.php";
    String sname,scity,sphone;
    String URL_RESPONSE="";

    HttpURLConnection conn;
    URL url = null;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        name=(EditText)findViewById(R.id.name);
        city=(EditText)findViewById(R.id.city);
        phone=(EditText)findViewById(R.id.phone);

        Submit=(Button)findViewById(R.id.submit);

        Submit.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                 sname = name.getText().toString();
                 scity = city.getText().toString();
                 sphone=phone.getText().toString();

                Log.d("text",sname+scity+sphone);

               new user_register().execute();
            }
        });
    }

    public class user_register extends AsyncTask<Void, Void, String> {

        @Override
        protected  void onPreExecute() {
           
            super.onPreExecute();
            pdDialog = new ProgressDialog(MainActivity.this);
            pdDialog.setMessage("Registering user Please Wait..");
            pdDialog.setCancelable(false);
            pdDialog.show();

        }

        @Override
        protected String doInBackground(Void... arg0) {
           try {
                URL url = new URL(URL_REGISTER);
                
                conn = (HttpURLConnection)url.openConnection();
                conn.setReadTimeout(15000);
                conn.setConnectTimeout(10000);
                conn.setRequestMethod("POST");

                conn.setDoInput(true);
                conn.setDoOutput(true);


                System.out.println("name:"+sname);
                System.out.println("city:"+scity);
                System.out.println("phone:"+sphone);

                // Append parameters to URL
                Uri.Builder builder = new Uri.Builder()
                        .appendQueryParameter("name", sname)
                        .appendQueryParameter("city", scity)
                        .appendQueryParameter("phone",sphone);
                String query = builder.build().getEncodedQuery();

               // Open connection for sending data
                OutputStream os = conn.getOutputStream();
                BufferedWriter writer = new BufferedWriter(
                        new OutputStreamWriter(os, "UTF-8"));
                writer.write(query);
                writer.flush();
                writer.close();
                os.close();
                conn.connect();

                int response_code = conn.getResponseCode();

                // Check if successful connection made
                if (response_code == HttpURLConnection.HTTP_OK) {

                    // Read data sent from server
                    InputStream input = conn.getInputStream();
                    BufferedReader reader = new BufferedReader(new InputStreamReader(input));
                    StringBuilder result = new StringBuilder();
                    String line;

                    while ((line = reader.readLine()) != null) {
                        result.append(line);
                    }

                    // Pass data to onPostExecute method
                    return(result.toString());

                }else{

                    return("unsuccessful");
                }


            }
            catch (ClientProtocolException e)
            {

                Log.d("BLOOD","IOE response " + e.toString());
                // TODO Auto-generated catch block
                URL_RESPONSE="ERROR";
            }
            catch (IOException e)
            {

                Log.d("BLOOD","IOE response " + e.toString());
                // TODO Aut return 0
                URL_RESPONSE="ERROR";
            }

            return null;
        }

        @Override
        protected void onPostExecute(String result) {
            super.onPostExecute(result);
            if (pdDialog.isShowing())
                pdDialog.dismiss();

            String trim_result=result.trim();


            Toast.makeText(MainActivity.this, result.trim(), Toast.LENGTH_LONG).show();

            if(trim_result.equalsIgnoreCase("true"))
            {
                /* Here launching another activity when login successful. If you persist login state
                use sharedPreferences of Android. and logout button to clear sharedPreferences.
                 */

                Intent intent = new Intent(MainActivity.this,SuccessActivity.class);
                startActivity(intent);
                MainActivity.this.finish();

            }else if (result.equalsIgnoreCase("false")){

                // If username and password does not match display a error message
                Toast.makeText(MainActivity.this, "Invalid email or password", Toast.LENGTH_LONG).show();

            } else if (result.equalsIgnoreCase("exception") || result.equalsIgnoreCase("unsuccessful")) {

                Toast.makeText(MainActivity.this, "OOPs! Something went wrong. Connection Problem.", Toast.LENGTH_LONG).show();

            }
        }

        }

    }


  • On Submit Button pressed user_register function trigged.
  • user_register that extends AsyncTask, Asynctask is very useful when it comes to handing any process that runs of background.
  • onPreExecute(): used to show progressDialog on the screen.
  • doInBackground(): The sending and recieving data from android registration app and to php file using HttpURLConnection class.
  • onPostExecute(): this will get execute as soon as doInBackground() task gets completed, here we just disable progressDialog box and and get response from server in teams of true or false, which means registration is successful or unsuccessful.

Then,now the App will successfully run on android 7 and below but when it comes to run on android 8 and above you may face error like:

Error 1 : D/NetworkSecurityConfig: No Network Security Config specified, using platform default

Error 2 : IOE response java.io.IOException: Cleartext HTTP traffic to 192.168.0.10 not permitted

Then to solve this problem you need to do this

Create file res/xml/network_security_config.xml –

<?xml version="1.0" encoding="utf-8"?>
<network-security-config>
    <domain-config cleartextTrafficPermitted="true">
        <domain includeSubdomains="true">192.168.0.10</domain>
    </domain-config>
</network-security-config>

if you are using localhost replace domain IP with your IP address or your domain name

AndroidManifest.xml –

<application
        ...
        android:networkSecurityConfig="@xml/network_security_config"
        ...>
        ...

</application>

Don’t forget Internet Permission in androidmanifest.xml file.

Then, all set  your app is ready to execute

that Store data in to Phpmyadmin database server.

Flutter Slider – How to Implement Flutter Slider with show value?

1
Flutter Slider
Flutter Slider

Hi Guys, welcome to Proto Coders Point  in this Tutorial will we Learn How to Implement Flutter Slider with show Value.

What is Flutter Slider?

A Slider in flutter app development is a Material Design , that is basically used in selecting a range of values.

A slider can be used to select from either a continuous or a discrete set of values. The default is to use a continuous range of values from min to max. To use discrete values, use a non-null value for divisions, which indicates the number of discrete intervals. For example, if min is 0.0 and max is 50.0 and divisions is 5, then the slider can take on the discrete values 0.0, 10.0, 20.0, 30.0, 40.0, and 50.0.

Here are the terms for the parts of a Flutter slider are:

  • A “thumb”,  is a Round shape that help the user to slide horizontally when user what to change in some values.
  • “track”, is a  horizontal line where the user can easily slide the thumb.
  • The “value indicator”, which is a shape that pops up when the user is dragging the thumb to indicate the value being selected.
  • The “active” side of the slider is the side between the thumb and the minimum value.
  • The “inactive” side of the slider is the side between the thumb and the maximum value.

So Let’s Begin the Implementation of Flutter Code with show values.

Flutter slider show value

Implement Flutter Slider with show value

First of all with is very much common, your need to create a new Project or Open an existing project  where you want to implement Flutter slider. So i am using android-stdio as my Development Toolkit.

New > New Flutter Project > Give a Name to the project and finish

Then, as soon as new Flutter project is been created, Flutter team have already set a default  code that simple counts the number of time the floatingbutton is been pressed.

So, I recommend remove all the code persent in  lib > main.dart file  and copy paste the below code in it.

main.dart 

import 'package:flutter/material.dart';

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

class MyApp extends StatelessWidget {
  // This widget is the root of your application.
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'Flutter  Slider',
      home: MyHomePage(title: 'Flutter Slider Demo'),
    );
  }
}

class MyHomePage extends StatefulWidget {
  MyHomePage({Key key, this.title}) : super(key: key);
  final String title;
  @override
  _MyHomePageState createState() => _MyHomePageState();
}

class _MyHomePageState extends State<MyHomePage> {
  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text(widget.title),
      ),
      body: Center(
        child: Column(
          mainAxisAlignment: MainAxisAlignment.center,
          children: <Widget>[
            Text(
              'Demo on Flutter Slider',
              style: TextStyle(fontSize: 20.0, fontWeight: FontWeight.w500),
            ),
          ],
        ),
      ),
    );
  }
}

Note: The above code is not the complete working of Flutter project, it’s a way to clean all the default code.

The Final Code of complete working Flutter Slider is at the bottom on this Tutorial, you can just copy paste it in main.dart.

Slider comes with Various Properties

As i said Flutter Slider comes with Various Properties that help Flutter Developer to Customize the slider.

You can learn more about slider class properties navigating to official flutter page.

  • activeColor → Color The color to use for the portion of the slider track that is active.
  • max → double – The maximum value the user can select.
  • min → double – The minimum value the user can select.
  • onChanged → ValueChanged<doubleCalled during a drag when the user is selecting a new value for the slider by dragging.
  • value → double – The currently selected value for this slider.

Flutter Slider Not Moving

My Flutter app developer who are beginner in flutter are facing some problem while working with flutter slider that’s because :

Flutter Slider will not move if you not used setState method in OnChanged to change value.

onChanged: (double value) {
                setState(() {
                  height = value.round();
                });
              },

so, you need to update value as user slide the slider. as shown in above snippet code.

Complete Code of Flutter Slider with show value change

main.dart

So, just copy paste the below complete lines of source code in to main.dart file to make Flutter slider work.

import 'package:flutter/material.dart';

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

class MyApp extends StatelessWidget {
  // This widget is the root of your application.
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'Flutter  Slider',
      home: MyHomePage(title: 'Flutter Slider Demo'),
    );
  }
}

class MyHomePage extends StatefulWidget {
  MyHomePage({Key key, this.title}) : super(key: key);
  final String title;
  @override
  _MyHomePageState createState() => _MyHomePageState();
}

class _MyHomePageState extends State<MyHomePage> {
  int height = 180;
  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text(widget.title),
      ),
      body: Center(
        child: Column(
          mainAxisAlignment: MainAxisAlignment.center,
          children: <Widget>[
            Text(
              'Proto Coders Point Demo on Flutter Slider',
              style: TextStyle(fontSize: 20.0, fontWeight: FontWeight.w500),
            ),
            SizedBox(
              height: 50.0,
            ),
            Text(
              "SET HEIGHT",
              style: TextStyle(fontWeight: FontWeight.w900, fontSize: 30.0),
            ),
            SizedBox(
              height: 50.0,
            ),
            Row(
              mainAxisAlignment: MainAxisAlignment.center,
              crossAxisAlignment: CrossAxisAlignment.baseline,
              textBaseline: TextBaseline.alphabetic,
              children: <Widget>[
                Text(
                  height.toString(),
                  style: TextStyle(fontSize: 40.0, fontWeight: FontWeight.w900),
                ),
                Text("cm")
              ],
            ),
            Slider(
              value: height.toDouble(),
              min: 80,
              max: 220,
              activeColor: Colors.pink,
              onChanged: (double value) {
                setState(() {
                  height = value.round();
                });
              },
            ),
            Text("Just slide the Flutter Slider to change value")
          ],
        ),
      ),
    );
  }
}
flutter slider show value

Recommended Articles on flutter

Image slider in flutter using Carousel Pro Flutter Library

flutter swiper – image slider/swiper in flutter

Flutter provider for beginners tutorial with app example

Firebase In-App Messaging Integration Android Project without any code

0
firebase in app messa1ging Integration Android Project without any code
firebase in app messa1ging Integration Android Project without any code

Hi Guys, Welcome to Proto Coders Point in this post we are going to Implement Firebase In-app Messaging services.

What is Firebase In-app Messaging Service?

Firebase In-App Messaging is a service that helps you to engage your apps active users i.e by sending In-app messages to your targeted users.

You can customize messages as cards, banners, modals, or images, and set up triggers so that they appear exactly when they’d benefit your users most.

So, Now Let’s Start Implementing Firebase In-App Messaging in android Studio

Follow Video Tutorial

Follow the Steps to Integrate Firebase Messaging Services

Step 1: Create a new Project

Create a new android Project
Create a new android Project

Open your android studio and Create a new Project.

if you already have Project and want to integrate Firebase In-App Messaging then jump to Step no 3.

Give name to the android project
Give name to the android project

Then, Click on Finish, your new Android Project will get created, and BUILD the Project  SUCCESSFUL  any take some time depending on you system speed.

Step 2 : Sign-In with Gmail account in android-studio

Then, Navigate towords top right corner of android studio window, you will see a small login profile icon.

how to sign in google account in android studio
how to sign in google account in android studio

Android Studio wants to access your google account.

Allow the Access permission from android studio to get sign-in.

google sign-in android studio
google sign-in android studio

Now, you are done with sign-in process.

Step 3 : Connecting Firebase to your android Project with In-App Messaging

Then, you need to Connect Firebase into your android project

So, Go to the toolbar on the top of android studio window

ToolBar > Tools > Firebase

you will now get this Window opened by android studio Assistant

adding firebase to android studio project
adding firebase to android studio project

Connect to Firebase

connect to firebase
connect to firebase

Add In-app Firebase dependencies in your android project

Add Firebase In-App Messaging to your app
Add Firebase dependencies to your app.

Then, it’s all set app is now ready to run and display Firebase In – App messaging.

Step 4: Add Internet Uses permission under android_manifest.xml

Don’t Forget to Add user-permission ( internet ) in manifest file

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

Step 5 : Create Firebase In-App Messaging Campaign in the Firebase Console

Now, Go to Your Firebase Console and create a Campaign to show Free In-app Messages.

Firebase Console > Right sidebar GROW > Select In-app Messaging > Create your first Campaign

firebase in app messaging services campaign
firebase in app messaging services campaign

Here you will find a option to Test on Device where you can easily run on your test device for testing purpose

Test on device firebase
Test on device firebase

Then, To get Instance Id you need to run the project in physical device or emulater device so that firebase can generate a Instance ID for testing purpose.

Now, your app is been build successfully and is running on the device.

Navigate to Logcat at the bottom of Android Studio and search for ” Instance “, you will get the instance ID generated by firebase for texting, The instanse ID will look something like this :

I/FIAM.Headless: Starting InAppMessaging runtime with Instance ID " esfS9Au1vYw "

Then, Copy the Instance ID and paste it into Firebase console test on device.

test on device instance id Firebase
test on device instance id Firebase

and then , Hit the Test button.

after that close the app if running and re-open the app.

Now, you will be able to see Firebase In-app Message been poped up as below.

In-app firebase messaging
In-app firebase messaging

Learn how to send Push notification using Firebase Cloud Messaging

 

 

 

How to make a CountDownTimer – android timer example

0
count down timer android Library
count down timer android Library

Hi Guys, Welcome to Proto Coders Point, In the Android Tutorial, we are implementing the GitHub android circular countdown timer library, TICKER by using which we can build an android studio countdown timer app.

Ticker Library countdowntimer android

Ticker a android library which can be used for different count down timer activities, and Progress Loaders.

DEMO

ticker count down timer library

Let’s begin implementing count down timer in android.

Adding CountDown Timer android in your android Project

I assume that you already have created a new project in android studio(IDE).

Android Studio > Files > New  > New Project > give a name to project

SetUp the ticker library

Add it in your root build.gradle at the end of repositories:

allprojects {
    repositories {
      maven { url 'https://jitpack.io' } // add this line
    }
  }

You should add the Maven url in build.gradle( project level).

Add the dependency:

Then, add the ticker count down dependencies in build.gradle( module : app ).

dependencies {
    implementation 'com.github.rehmanmuradali:ticker:1.0.0' // add this line 
  }

and then its done with adding library into the android project.

UI of Ticker Circular countdown timer view – XML android timer

<ticker.views.com.ticker.widgets.circular.timer.view.CircularView
       android:id="@+id/circular_view"
       android:layout_width="wrap_content"
       android:layout_height="wrap_content"
       app:m_circle_radius="25"
       app:m_cicle_stroke_width="14"
       app:m_arc_stroke_color="@android:color/white"
       app:m_circle_stroke_color="@color/colorPrimary"
       />

Basic Explaination of above ticker xml UI code

Available Attributes Properties

  • m_circle_radius: circle radius of Circular View
  • m_cicle_stroke_width: stroke width of Circular View in dp
  • m_circle_stroke_color: stroke color of outer Circular View
  • m_arc_stroke_color: color of inner rotating arc
  • m_arc_margin: Inner arc margin from cicle in dp

circle radius is for defining the size of the ticker circle.

eg : app:m_circle_radius=”70″.

circle stroke width : is for giving stroke width size of the ticker circle.

eg : app:m_cicle_stroke_width=”16″

arc stroke color is for giving circle inside arc stroke color

eg: app:m_arc_stroke_color=”@android:color/white”

circle stroke color to set back ground color

eg : app:m_circle_stroke_color=”@color/colorPrimary”.

Functionality of circular View Ticker count down Timer

CirculerView CircularView  = (CircularView) rootView.findViewById(R.id.circular_view);

Create a circularView object that point the UI of the View.

CircularView.OptionsBuilder builderWithTimer = 
          new CircularView.OptionsBuilder()
                .shouldDisplayText(true)
                .setCounterInSeconds(30)
                .setCircularViewCallback(new CircularViewCallback() {
                    @Override
                    public void onTimerFinish() {
                    
                        // Will be called if times up of countdown timer
                        Toast.makeText(MainActivity.this, "CircularCallback: Timer Finished ", Toast.LENGTH_SHORT).show();
                    }

                    @Override
                    public void onTimerCancelled() {
                    
                        // Will be called if stopTimer is called
                        Toast.makeText(MainActivity.this, "CircularCallback: Timer Cancelled ", Toast.LENGTH_SHORT).show();
                    }
                });

circularView.setOptions(builderWithTimer);

Create a builder for the circularView Timer

.shouldDisplayText(true) is used to Display a text inside the Ticker Circular View timer

.setCounterInSeconds(30) set the timer for 30 sec or more as per your requirement but it should be in seconds.

onTimerFinish() : This will get called when timer will get finished.

onTimerCancelled() :  When user stops the timer.

How to start, stop, pause, resume the count down timer?

 //start circular view to rotate
  circularView.startTimer();
  
 // pause circular view and timer
  circularView.pauseTimer()
  
 // resume circular view and timer
  circularView.resumeTimer();
  
// stop circular view and timer
  circularView.stopTimer();

Complete Code of Count Down Timer android Library

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">

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:orientation="vertical"
        android:gravity="center_horizontal"
        android:layout_gravity="center_horizontal">

        <TextView
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="Count Down Timer"
            android:textSize="25sp"
            android:textStyle="bold|italic"
            android:layout_margin="15dp"
            android:textColor="#000EFF"/>

        <ticker.views.com.ticker.widgets.circular.timer.view.CircularView
            android:id="@+id/circular_view"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_margin="20dp"
            app:m_circle_radius="100"
            app:m_cicle_stroke_width="15"
            app:m_arc_stroke_color="@android:color/white"
            app:m_circle_stroke_color="@color/colorPrimary"
            />

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

            <Button
                android:id="@+id/start_timer"
                android:layout_width="160dp"
                android:layout_marginTop="10dp"
                android:layout_height="wrap_content"
                android:background="#FF6F00"
                android:textSize="25sp"
                android:textColor="#FFF"
                android:text="Start"
                android:onClick="time_start"/>
            <Button
                android:id="@+id/stop_timer"
                android:layout_width="160dp"
                android:layout_marginTop="10dp"
                android:layout_height="wrap_content"
                android:background="#FA2929"
                android:textSize="25sp"
                android:textColor="#FFF"
                android:text="Stop"
                android:onClick="time_stop"/>
            <Button
                android:id="@+id/pause_timer"
                android:layout_width="160dp"
                android:layout_marginTop="10dp"
                android:layout_height="wrap_content"
                android:background="#364057"
                android:textSize="25sp"
                android:textColor="#FFF"
                android:text="Pause"
                android:onClick="time_pause"/>

            <Button
                android:id="@+id/resume_timer"
                android:layout_width="160dp"
                android:layout_marginTop="10dp"
                android:layout_height="wrap_content"
                android:background="#FFAA00"
                android:textSize="25sp"
                android:textColor="#FFF"
                android:text="Resume"
                android:onClick="time_resume"/>

            <Button
                android:id="@+id/reset_timer"
                android:layout_width="160dp"
                android:layout_marginTop="10dp"
                android:layout_height="wrap_content"
                android:background="#FF6F00"
                android:textSize="25sp"
                android:textColor="#FFF"
                android:text="Reset"
                android:onClick="time_reset"/>



        </LinearLayout>
    </LinearLayout>



</ScrollView>

This code is for layout Designing

count down timer layout design
Layout design of ticker library

MainActivity.java

package protocoderspoint.com.countdowntimertickerlibrary;

import androidx.appcompat.app.AppCompatActivity;

import android.content.Context;
import android.content.Intent;
import android.media.MediaPlayer;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.Toast;


import ticker.views.com.ticker.widgets.circular.timer.callbacks.CircularViewCallback;
import ticker.views.com.ticker.widgets.circular.timer.view.CircularView;

import static android.view.View.GONE;

public class MainActivity extends AppCompatActivity {

    CircularView circularViewWithTimer;
    Context context;
    int countBeep = 0;
    int tempBeep = 0;
    Button start,stop,pause,resume,reset;

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

        start=(Button)findViewById(R.id.start_timer);
        stop=(Button)findViewById(R.id.stop_timer);
        pause=(Button)findViewById(R.id.pause_timer);
        resume=(Button)findViewById(R.id.resume_timer);
        reset=(Button)findViewById(R.id.reset_timer);

        stop.setVisibility(GONE);
        pause.setVisibility(GONE);
        resume.setVisibility(GONE);



        circularViewWithTimer = findViewById(R.id.circular_view);
        CircularView.OptionsBuilder builderWithTimer =
                new CircularView.OptionsBuilder()
                        .shouldDisplayText(true)
                        .setCounterInSeconds(30)
                        .setCircularViewCallback(new CircularViewCallback() {
                            @Override
                            public void onTimerFinish() {

                                // Will be called if times up of countdown timer
                                Toast.makeText(MainActivity.this, "Timer Finished ", Toast.LENGTH_SHORT).show();
                                if(countBeep==30)
                                {
                                    stop.setVisibility(GONE);
                                    pause.setVisibility(GONE);
                                    resume.setVisibility(GONE);
                                }

                            }

                            @Override
                            public void onTimerCancelled() {

                                // Will be called if stopTimer is called
                                Toast.makeText(MainActivity.this, " Timer Stopped ", Toast.LENGTH_SHORT).show();

                            }

                        });

        circularViewWithTimer.setOptions(builderWithTimer);


    }

    public void time_start(View view) {
        circularViewWithTimer.startTimer();
        playAlertTone(getApplicationContext());
        start.setVisibility(GONE);
        stop.setVisibility(View.VISIBLE);
        pause.setVisibility(View.VISIBLE);

    }

    public void time_stop(View view) {
        circularViewWithTimer.stopTimer();
        countBeep=30;
        stop.setVisibility(GONE);
        pause.setVisibility(GONE);
        resume.setVisibility(GONE);

    }

    public void time_pause(View view) {
        circularViewWithTimer.pauseTimer();
        tempBeep=countBeep;
        countBeep=30;
        pause.setVisibility(GONE);
        resume.setVisibility(View.VISIBLE);
    }

    public void time_reset(View view) {
        Intent i = new Intent(MainActivity.this,MainActivity.class);
        startActivity(i);
        countBeep=30;
        finish();
    }
    public void time_resume(View view) {
        circularViewWithTimer.resumeTimer();
        countBeep=tempBeep;
        pause.setVisibility(View.VISIBLE);
        resume.setVisibility(GONE);
        playAlertTone(getApplicationContext());

    }

    public void playAlertTone(final  Context context){
        Thread t = new Thread(){
            public void run(){
                MediaPlayer player = null;

                while(countBeep<30){
                    player = MediaPlayer.create(context,R.raw.beep);
                    player.start();
                    countBeep+=1;
                    try {


                        Thread.sleep(player.getDuration()+500);
                    } catch (InterruptedException e) {
                        // TODO Auto-generated catch block
                        e.printStackTrace();
                    }
                }
            }
        };
        t.start();

    }

    @Override
    public void onBackPressed() {
        super.onBackPressed();
        countBeep=30;
    }


}

MainActivity.java is used to give functionality to the project.

Recommended Article

model progress hud flutter – Flutter Circular progress indicator

Flutter Count Down Timer

Alert Dialog Box in Flutter App Development

0
Alert Dialog Box in Flutter App development
Alert Dialog Box in Flutter App development

Hi Guys, Welcome to ‘Proto Coders Point’ in this Post we will learn how to Create a  Alert Dialog in Flutter app development using RFlutter_Alert Library Package.

What is Alert Dialog box?

Alert Dialog Box is basically a Box pop up which display some kind of Message or any action.It is normally used to ask the app user whether he want to continue to next process or discontinue.

Introduction to RFlutter Alert

RFlutter Alert is super customizable and easy to use alert/popup dialog for flutter app development. You may create reusuable alert styles or add buttons.

DEMO GIF

Flutter Alert Dialog
Flutter Alert Dialog

 

Feature of RFlutter Alert

  • Can be implement Single line basic alert
  • Adding buttons dynamically (as much as you want)
  • Predefined beautiful alert styles (success, error, warning, info)
  • Reusable alert styles
  • Super customizable
    • Change animation (fromTop, fromBottom, fromRight, fromLeft, grow, shrink)
    • Set animation duration
    • Show/hide close button
    • Set overlay tap to dismiss
    • Assign Title and desc styles
    • Change dialog border style

Use RFlutter Alert package as a library

Step1:

Add this to your package’s pubspec.yaml file:

dependencies:
  rflutter_alert: ^1.0.3

Step 2 :

Now in your main.dart Dart code, you can use this code to import RFlutter_alert packages:

import 'package:rflutter_alert/rflutter_alert.dart';

Now you are done with importing the RFlutter Alert Library package into your Flutter Application.

Implementation of Flutter Alert dialog box

There are many ways to show a alert dialog box, but in the post will we see 4 customized way to implement Flutter Alert dialog box pop up.

1. easiest way to create RFlutter Alert

The easiest way for creating RFlutter Alert.

This is a snippet code, Complete code for this project will be at the bottom.

Alert(
            context: context,
            title: "RFLUTTER ALERT",
            desc: "Proto Coders Point, Flutter alert dialog box is more awesome with RFlutter Alert.")
        .show();

The easiest way to display a alert dialog box in flutter is that just to display a title with some text in it and a description with some information of message.

easiest way to create RFlutter Alert
easiest way to create RFlutter Alert

This default alert dialog will come up a default cancel button with it to just close the dialog box.

2. Alert with a button in RFlutter Alert

Alert(
      context: context,
      type: AlertType.error,
      title: "RFLUTTER ALERT",
      desc: "Here we are creating a button inside alert box.",
      buttons: [
        DialogButton(
          child: Text(
            "Button",
            style: TextStyle(color: Colors.white, fontSize: 20),
          ),
          onPressed: () => Navigator.pop(context),
          width: 120,
        )
      ],
    ).show();

Alert with a button in RFlutter Alert
Alert with a button in RFlutter Alert

Here we are creating a button inside the alert dialog box, the button can be given some action to be performed when onclicked/onPressed.

type: AlertType.error : this will show a cross image.

3. Alert dialog with 2 Button in RFlutter Alert

Alert(
      context: context,
      type: AlertType.warning,
      title: "RFLUTTER ALERT",
      desc: "Alert Dialog with 2 Buttons.",
      buttons: [
        DialogButton(
          child: Text(
            "OK",
            style: TextStyle(color: Colors.white, fontSize: 20),
          ),
          onPressed: () => Navigator.pop(context),
          color: Color.fromRGBO(0, 179, 134, 1.0),
        ),
        DialogButton(
          child: Text(
            "Cancel",
            style: TextStyle(color: Colors.white, fontSize: 20),
          ),
          onPressed: () => Navigator.pop(context),
          gradient: LinearGradient(colors: [
            Color.fromRGBO(116, 116, 191, 1.0),
            Color.fromRGBO(52, 138, 199, 1.0)
          ]),
        )
      ],
    ).show();

Alert Dialog with 2 Buttons, Here i have created a dialog with 2 button in it. One button is to accept the alert and second button is to decline the alert message.

Alert dialog with 2 Button in RFlutter Alert
Alert dialog with 2 Button in RFlutter Alert

Then, i have also customized the button with gradient color feature.

3. Alert dialog with Login Content in RFlutter Alert

Alert(
        context: context,
        title: "LOGIN",
        content: Column(
          children: <Widget>[
            TextField(
              decoration: InputDecoration(
                icon: Icon(Icons.account_circle),
                labelText: 'Username',
              ),
            ),
            TextField(
              obscureText: true,
              decoration: InputDecoration(
                icon: Icon(Icons.lock),
                labelText: 'Password',
              ),
            ),
          ],
        ),
        buttons: [
          DialogButton(
            onPressed: () => Navigator.pop(context),
            child: Text(
              "LOGIN",
              style: TextStyle(color: Colors.white, fontSize: 20),
            ),
          )
        ]).show();

Alert dialog with Login Content in RFlutter Alert
Alert dialog with Login Content in RFlutter Alert

Here i have 2 TextField with a Login Button, so that we can show a login required alert dialog box

Complete Flutter Alert Dialog source code

import 'package:flutter/material.dart';
import 'package:rflutter_alert/rflutter_alert.dart';

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

class RatelApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      debugShowCheckedModeBanner: false,
      home: Scaffold(
        appBar: AppBar(
          title: Text('RFlutter Alert by Ratel'),
        ),
        body: PopupDialog(),
      ),
    );
  }
}

class PopupDialog extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return Container(
      child: Center(
        child: Column(
          mainAxisAlignment: MainAxisAlignment.center,
          children: <Widget>[
            RaisedButton(
              child: Text('Basic Alert'),
              onPressed: () => _onBasicAlertPressed(context),
              color: Colors.blue,
              textColor: Colors.white,
            ),
            RaisedButton(
              child: Text('Alert with Button'),
              onPressed: () => _onAlertButtonPressed(context),
              color: Colors.green,
              textColor: Colors.white,
            ),
            RaisedButton(
              child: Text('Alert with Buttons'),
              onPressed: () => _onAlertButtonsPressed(context),
              color: Colors.red,
              textColor: Colors.white,
            ),
            RaisedButton(
              child: Text('Alert with Custom Content'),
              onPressed: () => _onAlertWithCustomContentPressed(context),
              color: Colors.yellow,
              textColor: Colors.black,
            ),
          ],
        ),
      ),
    );
  }

// The easiest way for creating RFlutter Alert
  _onBasicAlertPressed(context) {
    Alert(
            context: context,
            title: "RFLUTTER ALERT",
            desc: "Flutter is more awesome with RFlutter Alert.")
        .show();
  }

// Alert with single button.
  _onAlertButtonPressed(context) {
    Alert(
      context: context,
      type: AlertType.error,
      title: "RFLUTTER ALERT",
      desc: "Flutter is more awesome with RFlutter Alert.",
      buttons: [
        DialogButton(
          child: Text(
            "Button",
            style: TextStyle(color: Colors.white, fontSize: 20),
          ),
          onPressed: () => Navigator.pop(context),
          width: 120,
        )
      ],
    ).show();
  }

// Alert with multiple and custom buttons
  _onAlertButtonsPressed(context) {
    Alert(
      context: context,
      type: AlertType.warning,
      title: "RFLUTTER ALERT",
      desc: "Flutter is more awesome with RFlutter Alert.",
      buttons: [
        DialogButton(
          child: Text(
            "Button_1",
            style: TextStyle(color: Colors.white, fontSize: 20),
          ),
          onPressed: () => Navigator.pop(context),
          color: Color.fromRGBO(0, 179, 134, 1.0),
        ),
        DialogButton(
          child: Text(
            "Button_2",
            style: TextStyle(color: Colors.white, fontSize: 20),
          ),
          onPressed: () => Navigator.pop(context),
          gradient: LinearGradient(colors: [
            Color.fromRGBO(116, 116, 191, 1.0),
            Color.fromRGBO(52, 138, 199, 1.0)
          ]),
        )
      ],
    ).show();
  }

// Alert custom content
  _onAlertWithCustomContentPressed(context) {
    Alert(
        context: context,
        title: "LOGIN",
        content: Column(
          children: <Widget>[
            TextField(
              decoration: InputDecoration(
                icon: Icon(Icons.account_circle),
                labelText: 'Username',
              ),
            ),
            TextField(
              obscureText: true,
              decoration: InputDecoration(
                icon: Icon(Icons.lock),
                labelText: 'Password',
              ),
            ),
          ],
        ),
        buttons: [
          DialogButton(
            onPressed: () => Navigator.pop(context),
            child: Text(
              "LOGIN",
              style: TextStyle(color: Colors.white, fontSize: 20),
            ),
          )
        ]).show();
  }
}