Home Blog Page 49

Installation of Flutter VelocityX Library – and How to use it in Text Widget.

2
Installation of Flutter VelocityX Library - and How to use it in Text Widget

Hi Guys, Welcome to Proto Coders Point, In this Flutter Tutorial we gonna introduce you with a latest product called VELOCITY XLibrary developed using Flutter SDK by Pawan Kumar.

What is Flutter Velocity X?

The Velocity X  library in flutter development is a minimalist flutter framework that helps you in building custom Application design Rapidly.

Velocity X comes with various properties that we can apply to our flutter widget such as Color, Padding, Text , Box, Card, SizedBox and many more.

Installation of Velocity X in Flutter Project

Step 1: Adding Dependencies

Add the following dependencies in your pubspec.yaml file.

dependencies:
  velocity_x: ^0.2.0  // add this line

Step 2: Importing the VelocityX package

Once you have added the velocityx dependencies, Now you can use them in your dart code (main.dart), just by importing the package / component that are required for application development.

Eg: In my case i have imported it in main.dart file

import 'package:velocity_x/velocity_x.dart' ;

Then, it’s all set your flutter project is ready to make use of velocityx librarys.

Tutorial on Applying VelocityX to Text / How to use Velocity X in Text Widget.

This Library gives super power to Text

Note : When are are done with applying velocityx properties to widget or string end it with .make() to make it back to flutter widget.

Converting String Variable to Text Widget

'Demo On Flutter Velocity X'
                      .text
                      .size(30)
                      .bold
                      .make(),

output

velocityx string to text make

the above code will change the normal String text into text widget, when you define it with .text and at the end convert it to Text widget using .make().

FontStyle

Applying font Style italic

Text('You have pushed the button this many times:',)
.text
.red600   //text color to red
.italic   //stlying italic
.make(),   // make it as widget

velocity x text to fontstyle italic

Font Scale / Font Size in flutter using velocityx

"Font Scale Size".text
                 .sm   //font size pre-defined
                 .make(),

velocity x fontsize

fontSize predefined properties

  • xs – Extra Small (scaleFactor 0.75)
  • sm – Small (scaleFactor 0.875)
  • base – Normal (scaleFactor 1)
  • lg – Large (scaleFactor 1.125)
  • xl – Extra Large (scaleFactor 1.25)
  • xl2 – 2 Extra Large (scaleFactor 1.5)
  • xl3 – 3 Extra Large (scaleFactor 1.875)
  • xl4 – 4 Extra Large (scaleFactor 2.25)
  • xl5 – 5 Extra Large (scaleFactor 3)
  • xl6 – 6 Extra Large (scaleFactor 4)

Font Weight 

Giving thickness to text font.

"Font Weight".text
             .extraBold
              .make(), // applying font weight with pre deined size

Output

Velocity x font weight

 

Text Font Weight properties

  • hairLine – Font Weight 100
  • thin – Font Weight 200
  • light – Font Weight 300
  • normal – Font Weight 400
  • medium – Font Weight 500
  • semiBold – Font Weight 600
  • bold – Font Weight 700
  • extraBold – Font Weight 800
  • extraBlack – Font Weight 900

Letter Spacing

You can give spacing between each letter on text by using velocityx properties.

"Letter Spacing ".text.widest.make(),

letter spacing in flutter velocity x

Spacing between text this are pre-defined parameters

  • tightest – Letter Spacing -3.0
  • tighter – Letter Spacing -2.0
  • tight – Letter Spacing -1.0
  • wide – Letter Spacing 1.0
  • wider – Letter Spacing 2.0
  • widest – Letter Spacing 3.0

Decoration to Text

Text can be decorated with underline, overline, lineThrough

"Text Decoration".text.underline.heightRelaxed.make().

Flutter text decoration with underline using velocityX

Decoration velocityX properties

  • underline – TextDecoration.underline
  • lineThrough – TextDecoration.lineThrough
  • overline – TextDecoration.overline

Text Utilities

Applying text utilities with UPPERCASE, lowercase, Capitalize and hidePartial

"Text Utilities".text.uppercase.make(), //change the font text to upper case

text to uppercase using velocity

  • uppercase – WELCOME TO PROTO CODERS POINT
  • lowercase – welcome to velocityx
  • capitalize – Welcome To Velocityx

Hiding Text

you can even hide some text from a long string, Hidden text will be shown in *****

"Text Utilities hidden".text.hidePartial.make(), //this will hide some text from start

hide partially

  • hidePartial – ***** To Velocityx

 

All properties Together

Text("Velocity_X text property all together")
                      .text
                      .orange400 // text color orange
                      .xl        // text font extra large
                      .bold      // make text bold
                      .center    //align to center
                      .heightLoose
                      .underline // under line to text
                      .wide    // space between text
                      .uppercase  //make text to UPPERCASE
                      .make(),   //convert it back to a widget

Output

velocity properties apply to text

 

 

Firebase Cloud Messaging (FCM) Send Push Notification using php script

0
Firebase Cloud Messaging (FCM) Send Push Notification using php script
Firebase Cloud Messaging (FCM) Send Push Notification using php script

Hi Guys, Welcome to Proto Coders Point, In this android tutorial we will send firebase push notification using php function/php script.

In other words, The FCM notification will be sent to particular user who are subscribed to a topic in Firebase Cloud Messaging Service.

DEMO

ui design example on how to send push notification to android app using php code

android php push notification screenshot

So let’s begin implementing this Android FCM project.

Step 1: Create a new Android Project

As usual create a new android project in your android studio

File > New > New Project

Give a name to your project say Firebase push notification service.

Step 2: Connect new Project to firebase using firebase android studio assistant

Step 1: Add Firebase Analytic

tools > firebase > select analytics

1. Connect to firebase

Hit that connect to firebase Button under assistant, This will open default browser with a firebase url to add your android project to your firebase console.

Just agree all the steps on your browser, if you face any problem to connect to firebase console check out the above video

2. Add Analytics to your app

just click on the button suggested by assistant “add analytic to your app”  this will add all the required dependencies & classes.

3. Add analytic code

open MainActivity.java basically you loading or first screen of your android app.

private FirebaseAnalytics mFirebaseAnalytics;

//inside of onCreate 
mFirebaseAnalytics = FirebaseAnalytics.getInstance(this);

Step 2: Add Cloud Messaging dependencies through assistant

under the android firebase assistant search for cloud messaging under that hit “Add FCM to your app”

This will add the FCM dependencies to your android project.

android project connected to firebase console

 

Step 3: Create a new Service class for FCM Services

Create a service java (Right Click) > New > Service > service  and name it a anything your wish in my case i have named it as FirebaseCloudMessagingService.java

creating FCM service in android studio

Then, Add the below links of notification service codes.

FirebaseCloudMessagingService.java

package com.protocoderspoint.sendingpushnotificationusingphpcode;

import android.annotation.SuppressLint;
import android.app.Notification;
import android.app.NotificationChannel;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.app.Service;
import android.content.Context;
import android.content.Intent;
import android.graphics.Color;
import android.os.Build;
import android.os.IBinder;

import androidx.annotation.NonNull;
import androidx.core.app.NotificationCompat;

import com.google.firebase.messaging.FirebaseMessagingService;
import com.google.firebase.messaging.RemoteMessage;

public class FirebaseCloudMessagingServices extends FirebaseMessagingService {
    public FirebaseCloudMessagingServices() {
    }

    @Override
    public void onMessageReceived(@NonNull RemoteMessage remoteMessage) {
        super.onMessageReceived(remoteMessage);

        if (remoteMessage.getNotification() != null) {
            String title = remoteMessage.getNotification().getTitle(); // will hold FCM Title
            String message = remoteMessage.getNotification().getBody(); //will hold FCM message body
            sendNotification(title,message);
        }
    }

    private void sendNotification(String title, String message) {

        NotificationManager notificationManager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
        String NOTIFICATION_CHANNEL_ID = "admin_channel_1";
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
            @SuppressLint("WrongConstant") NotificationChannel notificationChannel = new NotificationChannel(NOTIFICATION_CHANNEL_ID, "My Notifications", NotificationManager.IMPORTANCE_MAX);
            // Configure the notification channel.
            notificationChannel.setDescription("Sample Channel description");
            notificationChannel.enableLights(true);
            notificationChannel.setLightColor(Color.RED);
            notificationChannel.setVibrationPattern(new long[]{0, 1000, 500, 1000});
            notificationChannel.enableVibration(true);
            notificationManager.createNotificationChannel(notificationChannel);
        }
        NotificationCompat.Builder notificationBuilder = new NotificationCompat.Builder(this, NOTIFICATION_CHANNEL_ID);
        Intent intent = new Intent(this, MainActivity.class);
        intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
        PendingIntent pendingIntent = PendingIntent.getActivity(this, 0, intent, PendingIntent.FLAG_ONE_SHOT);
        
        notificationBuilder.setAutoCancel(true)
                .setContentIntent(pendingIntent)
                .setDefaults(Notification.DEFAULT_ALL)
                .setWhen(System.currentTimeMillis())
                .setSmallIcon(R.mipmap.ic_launcher)
                //.setPriority(Notification.PRIORITY_MAX)
                .setContentTitle(title)
                .setContentText(message);
        notificationManager.notify(1, notificationBuilder.build());
    }
}

Step 4: Add Volley Library

As we gonna make a call to our php script to send notification in am making use of Volley library to make a call to my service side php code

open build.gradle(app level)  and all the following volley dependencies.

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

Step 5: Register/ Subscribe to Topic in java code

This is how we make the user to register or subscribe to particular topic so that we can  send notification to selected topic or subscriber using the topic that user are registered too.

Snippet code to make user subscribe to a topic in FCM.

FirebaseMessaging.getInstance().subscribeToTopic("Gadgets");

 

Now, open strings.xml and add the following array strings

strings.xml

<resources>
    <string name="app_name">Sending PushNotification using php code</string>

    <string name="topic_selection">Choose a category: </string>

    <string-array name="product_topics">
        <item>PC</item>
        <item>Laptop</item>
        <item>Gadgets</item>
    </string-array>

</resources>

ok Then, Let’s design the UI of the app

acitivity_main.xml

<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context=".MainActivity">

    <Button
        android:id="@+id/subscribe"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Subscribe on Topic"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toTopOf="parent"
        app:layout_constraintVertical_bias="0.269" />

    <Spinner
        android:id="@+id/spinner"
        android:layout_width="409dp"
        android:layout_height="80dp"
        android:layout_marginTop="64dp"
        android:entries="@array/product_topics"
        android:gravity="center"
        android:prompt="@string/topic_selection"
        app:layout_constraintBottom_toTopOf="@+id/subscribe"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toTopOf="parent"
        app:layout_constraintVertical_bias="0.685" />

    <TextView
        android:id="@+id/textView"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginTop="22dp"
        android:text="You will get notified on selected topic only"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toBottomOf="@+id/subscribe" />

    <TextView
        android:id="@+id/textView2"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Select a Firebase topic to get subscribed on particular topic only"
        app:layout_constraintBottom_toTopOf="@+id/spinner"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toTopOf="parent" />

    <Button
        android:id="@+id/getnotified"
        android:layout_width="247dp"
        android:layout_height="51dp"
        android:layout_marginTop="276dp"
        android:text="Notify Me"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintHorizontal_bias="0.498"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toBottomOf="@+id/textView"
        app:layout_constraintVertical_bias="0.0" />

    <TextView
        android:id="@+id/textView3"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:gravity="center"
        android:text="Below button will call the php code that sends notification \n to Cloud messaging service topic you are subscribed to"
        app:layout_constraintBottom_toTopOf="@+id/getnotified"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toBottomOf="@+id/textView"
        app:layout_constraintVertical_bias="0.84" />
</androidx.constraintlayout.widget.ConstraintLayout>

MainActivity.java

package com.protocoderspoint.sendingpushnotificationusingphpcode;

import androidx.appcompat.app.AppCompatActivity;

import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.Spinner;
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 com.google.firebase.analytics.FirebaseAnalytics;
import com.google.firebase.messaging.FirebaseMessaging;

import java.util.HashMap;
import java.util.Map;
import java.util.Random;

public class MainActivity extends AppCompatActivity {

    private FirebaseAnalytics mFirebaseAnalytics;

    Spinner spinnerTopic;
    Button subscribe,send_Pushnotification;
    // this link is my server where my php script for push notification exist
    String  URL_NOTI="https://protocoderspoint.com/php/push_notification.php";
    String topic;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        mFirebaseAnalytics = FirebaseAnalytics.getInstance(this);
        spinnerTopic = (Spinner)findViewById(R.id.spinner);
        subscribe=(Button)findViewById(R.id.subscribe);
        send_Pushnotification=(Button)findViewById(R.id.getnotified);


        subscribe.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                topic = spinnerTopic.getSelectedItem().toString();
                System.out.println(topic);

                //subscribing yourself to topic you have selected from spinner

                FirebaseMessaging.getInstance().subscribeToTopic(topic);

                Toast.makeText(MainActivity.this,"Subscribed successfully to:  "+topic,Toast.LENGTH_SHORT).show();

                Toast.makeText(MainActivity.this,"Now just Hit Notify me Button "+topic,Toast.LENGTH_SHORT).show();
            }
        });

        send_Pushnotification.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Send_Notification(topic);
            }
        });
    }

    private void Send_Notification(final String topic)
    {


        StringRequest stringRequest = new StringRequest(Request.Method.POST, URL_NOTI,
                new Response.Listener<String>() {
                    @Override
                    public void onResponse(String response) {

                        Log.e("farmerorderdataresponse",response);
                        try{




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

                            Toast.makeText(getApplicationContext(),"Login Error !1"+e,Toast.LENGTH_LONG).show();
                        }
                    }
                }, new Response.ErrorListener() {
            @Override
            public void onErrorResponse(VolleyError error) {

                Toast.makeText(getApplicationContext(),"Login Error !2"+error,Toast.LENGTH_LONG).show();
            }
        })
        {
            @Override
            protected Map<String, String> getParams() {
                Map<String,String> params = new HashMap<>();

                params.put("title","Order Received");
                params.put("body","This is a notification");
                params.put("topic",topic);
                return params;
            }
        };

        RequestQueue requestQueue = Volley.newRequestQueue(getApplicationContext());
        requestQueue.add(stringRequest);

    }
}

Step 5: network configuration for android version 9

then you need to add a network configuration xml file where you define the network that you will be using…Usually the domain

res (right click) > New > Directory

give new diretory name as “xml”

Then, right click “xml directory” > New > xml resource file and name it as network_security_config.xml

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

        //replace the domain name with your server domain name
        <domain includeSubdomains="true">protocoderspoint.com</domain>

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

Step 6: PHP script to send FCM push notification

<?php
    $user= $_POST['topic'];
    $title = $_POST['title'];
    $body = $_POST['body'];
    $url = "https://fcm.googleapis.com/fcm/send";

    $topic = "/topics/$user";

    //replace serverkey with your firebase console project server key
    $serverKey = "AAAADmPIVdUXXXXXXEbfiR9c5LyXRKgq1LAWhT6a-byFe7lPXXXXXXXTjJfhHTTIo7Q997PL-89KrKagTQz26FUmyhRmhmsxQXXXXXXXWBmOuJ4-wtY_uL1-si8l3hyr5zJ-2P";

    //$body = '$_POST['body']';
  //  $intent_filter=$action;
    $notification = array('title' =>$title , 'body' => $body, 'sound' => 'default', 'badge' => '1');
    $arrayToSend = array('to' => $topic, 'notification' => $notification,'priority'=>'high');
    $json = json_encode($arrayToSend);
    $headers = array();
    $headers[] = 'Content-Type: application/json';
    $headers[] = 'Authorization: key='. $serverKey;
    $ch = curl_init();
    curl_setopt($ch, CURLOPT_URL, $url);
    curl_setopt($ch, CURLOPT_CUSTOMREQUEST,"POST");
    curl_setopt($ch, CURLOPT_POSTFIELDS, $json);
    curl_setopt($ch, CURLOPT_HTTPHEADER,$headers);
    //Send the request
    $response = curl_exec($ch);
    //Close request
    if ($response === FALSE) {
    die('FCM Send Error: ' . curl_error($ch));
    }
    curl_close($ch);
?>

How to get serverkey of FCM service ?

how to get server key of firebase cloud messaging

Then, where you go your app is ready to subscribe to selected topic using Spinner and will be able to recieve push notification on particular topic the app user is subscribed too firebase cloud messaging service.

 

How to display JSON data in listview in android – HttpRequest using OkHttp android

0
Http Request using OkHttp android library – Display data in ListView Part 2

Hi Guys, Welcome to Proto Coders Point, if you have seen our last post on how to make an android http request call using okhttp android library, where we have just fetched data from the API which is in JSON format, and just displayed the response.body() in text view.

In this Tutorial post we will show/display the data received by okhttp call a http response data in Simple Listview Adapter.

DEMO SCREENSHOT

demo example on okhttp android library

Please check out the part 1 of OkHttp android library

In part one all the required dependencies is add.

Then, Let’s start implement okhttp android response data to display in listview.

Step1: Create a layout file

res > layout (right click) >New > Layout Resource File

create a new layout file and name it as listview_layout.xml and then paste the below layout design xml UI code.

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="fill_parent"
    android:layout_height="wrap_content"
    android:orientation="horizontal">
    
    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="120dp"
        android:weightSum="2"
        android:padding="2dp"
        android:layout_margin="10dp"
        android:orientation="vertical">
        <TextView
            android:id="@+id/name"
            android:text="Name"
            android:layout_marginTop="5dp"
            android:layout_marginBottom="5dp"
            android:layout_weight="0.5"
            android:textSize="18sp"
            android:textStyle="bold"
            android:layout_width="fill_parent"
            android:layout_height="wrap_content"
            android:textColor="@color/colorPrimary" />

        <TextView
            android:id="@+id/power"
            android:text="Power"
            android:layout_weight="0.5"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:textColor="#5d5d5d"
             />
    </LinearLayout>

</LinearLayout>

The above XML layout has 2 views Both are TextView which holds the name of superhero and power of the superhero.

don’t get confused i have a API of Superheros list which is in JSON format.

This is the URL of my API

https://protocoderspoint.com/jsondata/superheros.json

Step 2: adding listview in activity_main.xml

activity_main.xml

<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context=".MainActivity">

    <ListView
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:id="@+id/listview"/>

</androidx.constraintlayout.widget.ConstraintLayout>

this is where the list of data will be shown using ListView

Step 3 : Final MainActivity.java

MainActivity.java

package com.protocoderspoint.androidokhttp;

import androidx.appcompat.app.AppCompatActivity;

import android.os.Bundle;
import android.widget.ListAdapter;
import android.widget.ListView;
import android.widget.SimpleAdapter;
import android.widget.TextView;

import com.squareup.picasso.Picasso;

import org.jetbrains.annotations.NotNull;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;

import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;

public class MainActivity extends AppCompatActivity {

    
    String myResponse;
    ListView lv;

    ArrayList<HashMap<String,String>> arrayList;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        setContentView(R.layout.activity_main);
        arrayList=new ArrayList<>();
        lv = (ListView)findViewById(R.id.listview);



        OkHttpClient client = new OkHttpClient();
        String url = "https://protocoderspoint.com/jsondata/superheros.json";

        Request request = new Request.Builder()
                .url(url)
                .build();

        client.newCall(request).enqueue(new Callback() {
            @Override
            public void onFailure(@NotNull Call call, @NotNull IOException e) {
                e.printStackTrace();
            }

            @Override
            public void onResponse(@NotNull Call call, @NotNull Response response) throws IOException {
                if(response.isSuccessful())
                {

                    myResponse = response.body().string();
                    MainActivity.this.runOnUiThread(new Runnable() {
                        @Override
                        public void run() {


                            try {
                                JSONObject reader = new JSONObject(myResponse);
                                JSONArray superheros = reader.getJSONArray("superheros"); // get the whole json array list

                                System.out.println("json size is : "+superheros.length());

                                for(int i = 0;i<superheros.length();i++)
                                {
                                    JSONObject hero = superheros.getJSONObject(i);
                                    String name = hero.getString("name");
                                    String power = hero.getString("power");


                                    System.out.println(i+" Name: "+name +" Power : "+power);

                                    HashMap<String,String> data = new HashMap<>();

                                    data.put("name",name);
                                    data.put("power",power);


                                    arrayList.add(data);


                                    ListAdapter adapter = new SimpleAdapter(MainActivity.this,arrayList,R.layout.listview_layout
                                    ,new String[]{"name","power"},new int[]{R.id.name,R.id.power});

                                    lv.setAdapter(adapter);
                                }

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

Brief detail about above source code

As we get Response using okHttp android library,

Then we are parsing  the data using JSON Parser

ArrayList HashMap as a String data

ArrayList<HashMap<String,String>> arrayList;

arrayList=new ArrayList<>();

arraylist will store all the data individually

String myResponse

myResponse = response.body().string();

Here is where we will hold the response.body() received from server API.

Get the JSONObject and JSONArray

JSONObject reader = new JSONObject(myResponse);
JSONArray superheros = reader.getJSONArray("superheros");

Then, Here we gonna trace the json data using JSONArray

looping through all the individual data

for(int i = 0;i<superheros.length();i++)
                                {
                                    JSONObject hero = superheros.getJSONObject(i);
                                    String name = hero.getString("name");
                                    String power = hero.getString("power");


                                    System.out.println(i+" Name: "+name +" Power : "+power);

                                    HashMap<String,String> data = new HashMap<>();

                                    data.put("name",name);
                                    data.put("power",power);


                                    arrayList.add(data);


                                    ListAdapter adapter = new SimpleAdapter(MainActivity.this,arrayList,R.layout.listview_layout
                                    ,new String[]{"name","power"},new int[]{R.id.name,R.id.power});

                                    lv.setAdapter(adapter);
                                }
Download from Google Drive

Guys, is you face any kind of problem, then feel free to contact_me

Http Request using OkHttp android library – Part 1

1

Hi Guys, Welcome to Proto Coders Point, In this Android Tutorial we gonna have a look on how to get response from server using OkHttp android library.

Note: This Android tutorial is kept simple for http request with okhttp library,

This is PART 1 – Here we will just fetch the data from server which is in json format and show data in Android TextView

Final Result of PART 1

okhttp android library screenshot example

What is OkHttp Library?

HTTP is the latest way to network in application. Now a days all data such as text,images or media are been exchange using HTTP CALLS.

Using OKHTTP will make our application stuff load content faster and saves lots of bandwidth.

Okhttp android library makes it simple to make any asynchronous HTTP request.

Using okhttp is quite very simple to get request/response API, It Supports both synchronous and asynchronous callls with callbacks.

Adding the library in our android project

implementation("com.squareup.okhttp3:okhttp:4.4.0")  // add this line in gradle.build(app level)

Check out the latest version of okhttp library in official website 

Internet permission

as we are making network called to fetch data from server we need to assign INTERNET permission

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

So to so open AndroidManifest.xml file and the <user-permissioon> Internet.

Snippet code to GET data from URL

OkHttpClient client = new OkHttpClient();  
        String url = "your api link here";

        Request request = new Request.Builder()
                .url(url)   //request for url by passing url
                .build();

        client.newCall(request).enqueue(new Callback() {
            @Override
            public void onFailure(@NotNull Call call, @NotNull IOException e) {
                e.printStackTrace();
            }

            @Override
            public void onResponse(@NotNull Call call, @NotNull Response response) throws IOException {
                if(response.isSuccessful())
                {
                   // task after data is received 
                }
            }
        });

OkHttp will perform best when simple OkHttpClient instance is been created and reused it  in program when every needed to make HTTP Calls, This is best each client is given to hold its own  connection so this makes the task smooth, fast and easy to load data from server side.

Complete Source Code to make Http Request using OkHttp android library – Part 1

activity_main.xml

<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context=".MainActivity">

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

</androidx.constraintlayout.widget.ConstraintLayout>

This have only one widget(textview) where are gonna show the date response for server

MainActivity.java

package com.protocoderspoint.androidokhttp;

import androidx.appcompat.app.AppCompatActivity;

import android.os.Bundle;
import android.widget.TextView;

import org.jetbrains.annotations.NotNull;

import java.io.IOException;

import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;

public class MainActivity extends AppCompatActivity {

    TextView textView;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        setContentView(R.layout.activity_main);

        textView = (TextView)findViewById(R.id.textview1);

        OkHttpClient client = new OkHttpClient();
        String url = "https://protocoderspoint.com/jsondata/superheros.json";

        Request request = new Request.Builder()
                .url(url)
                .build();

        client.newCall(request).enqueue(new Callback() {
            @Override
            public void onFailure(@NotNull Call call, @NotNull IOException e) {
                e.printStackTrace();
            }

            @Override
            public void onResponse(@NotNull Call call, @NotNull Response response) throws IOException {
                if(response.isSuccessful())
                {
                    final String myResponse = response.body().string();
                    MainActivity.this.runOnUiThread(new Runnable() {
                        @Override
                        public void run() {
                            textView.setText(myResponse);                // runOnUiThread is used because A Thread is current used by OkHttp Thread
                        }
                    });
                }
            }
        });
    }
}

 

 

 

Flutter http example – fetching data from internet json & display in listview

3
Flutter http example display dynamic data in listview

Hi Guys, Welcome to Proto Coders Point, In this Flutter Tutorial we gonna use the HTTP flutter library to Fetch data from the Internet which is in JSON format, and display the data in Flutter ListView builder with ListTile widget.

let’s begin by adding HTTP dart package into our project

Final Result of this Flutter Demo Application

flutter http example dynamic data in listview

Http Dart Package

Step 1 : Add http dependencies

Open pubspec.yaml file and add the below lines of code

dependencies:
  http: ^0.12.0+4   //add this line

Once you add the dependencie hit Packages Get , what this does is that get all the packages from interent and store them in you flutter project.

Step 2 : Import the http dart package

import 'package:http/http.dart';

You need to import the http.dart file under you project file where you want to make use of it.

All set now let’s check how to get data from server or any REST API

I have created a dummy JSON DATA on my server which we are using in this flutter http example to fetch json data.

Link of my JSON DATA or API : https://protocoderspoint.com/jsondata/superheros.json

my json API data for flutter http request get

How to use http library in flutter?

void getData() async {

    http.Response response =  await http.get("https://protocoderspoint.com/jsondata/superheros.json");

    //if response is 200 : success that store 
    if (response.statusCode == 200) {
      String  data = response.body; //store response as string

      setState(() {
        superheros_length = jsonDecode(data)['superheros']; //get all the data from json superheros

        print(superheros_length.length); // just printed length of data
      });


      var venam = jsonDecode(data)['superheros'][4]['power']; // get data from particular index

      print(venam);
    } else {
      print(response.statusCode);
    }
  }

How to Show/Display data from Server in Flutter listView?

To show Dynamic contents in flutter listview we make use of listview.builder() widget.

ListView.builder is commonly been used to construct a children’s widgets as much as required depending on the dynamic data you receive from server or API calls.

ListView.builder comes with parameters like

itemCount : describes how many itemBuilder ( widget ) must be created

ListView.builder(
        itemCount: superheros_length == null ? 0 : superheros_length.length,
        itemBuilder: (BuildContext context, int index) {
          return Card(
            child: ListTile(
              leading: Image.network(
                jsonDecode(data)['superheros'][index]['url'],
                fit: BoxFit.fill,
                width: 100,
                height: 500,
                alignment: Alignment.center,
              ),
              title: Text(jsonDecode(data)['superheros'][index]['name']),
              subtitle: Text(jsonDecode(data)['superheros'][index]['power']),
            ),
          );
        },
      ),

itemBuilder : will create as many as widgets specified in itemCount

For Example : itemCount : 5  then itemBuilder will simply create 5 widget on the screen

This above Snippet code will generate Card with child: as ListTile Widget.

Flutter http example – fetching data from internet json and display in listview

Complete Source code to fetch data from server using Flutter HTTP

import 'package:flutter/material.dart';
import 'package:http/http.dart' as http;
import 'dart:convert';

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 Demo',
      theme: ThemeData(
        primarySwatch: Colors.blue,
      ),
      home: MyHomePage(),
    );
  }
}

class MyHomePage extends StatefulWidget {
  @override
  _MyHomePageState createState() => _MyHomePageState();
}

class _MyHomePageState extends State<MyHomePage> {
  String data;
  var superheros_length;
  @override
  void initState() {
    // TODO: implement initState
    super.initState();
    getData();
  }

  void getData() async {
    http.Response response =
        await http.get("https://protocoderspoint.com/jsondata/superheros.json");

    if (response.statusCode == 200) {
      data = response.body; //store response as string

      setState(() {
        superheros_length = jsonDecode(
            data)['superheros']; //get all the data from json string superheros

        print(superheros_length.length); // just printed length of data
      });

      var venam = jsonDecode(data)['superheros'][4]['url'];

      print(venam);
    } else {
      print(response.statusCode);
    }
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text("Flutter Http Example"),
      ),
      body: ListView.builder(
        itemCount: superheros_length == null ? 0 : superheros_length.length,
        itemBuilder: (BuildContext context, int index) {
          return Card(
            child: ListTile(
              leading: Image.network(
                jsonDecode(data)['superheros'][index]['url'],
                fit: BoxFit.fill,
                width: 100,
                height: 500,
                alignment: Alignment.center,
              ),
              title: Text(jsonDecode(data)['superheros'][index]['name']),
              subtitle: Text(jsonDecode(data)['superheros'][index]['power']),
            ),
          );
        },
      ),
    );
  }
}

 

Recommended Articles

listwheelscrollview3D ListView in flutter

Integration of Google Maps in Flutter with Example using a plugin

1

Hi Guys, Welcome to Proto Coders Point, In this Flutter Tutorial we gonna integrate Flutter Google Maps in our Flutter Project using a Plugin.

So to add google maps in your flutter project, Google API is needed.

DEMO

google maps flutter example in gif

Step 1: How to get Google Map API key?

To get API key go to the link https://cloud.google.com/maps-platform/ Create a new Google Project under your console.

Follow the Screenshot Steps to get API

step 1 to get API key credentials

create new credential api key

how to get google api key

Then now you have API key with you, keep a note of it.

Step 2 : adding google maps flutter dependencies

Do Follow this link the official site to get latest version here

Open pubspec.yaml file and app the plugin library dependencies file.

dependencies:
  google_maps_flutter: ^0.5.25 // add this line

Step 3: Import the google map flutter library

After you have added the required dependencies now you need to import the library whereever  you need to implement google maps in flutter app.

import 'package:google_maps_flutter/google_maps_flutter.dart';

Step 4 : Specifying the Google API key in AndroidManifest.xml ( ANDROID )

open AndroidManifest.xml file and add the <meta-data> tag inside <application> tag

<manifest ...
  <application>

    <meta-data android:name="com.google.android.geo.API_KEY"
               android:value="YOUR KEY HERE"/>                  // add this line and replace with you API KEY

  </application>
</manifest>

Step 5: Specifying API key in AppDelegate.swift ( for iOS)

in iOS you need to Specify Application delegates  to make use of google maps services in  IOS

To do so navigate ios/Runner/AppDelegate.swift

import UIKit
import Flutter
import GoogleMaps   // add this line 

@UIApplicationMain
@objc class AppDelegate: FlutterAppDelegate {
  override func application(
    _ application: UIApplication,
    didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?
  ) -> Bool {
    GMSServices.provideAPIKey("YOUR KEY HERE")      // add this line replace  with your API KEY
    GeneratedPluginRegistrant.register(with: self)
    return super.application(application, didFinishLaunchingWithOptions: launchOptions)
  }
}

 

Snippet code of GoogleMaps widget in flutter

GoogleMap(
      mapType: MapType.normal,
      initialCameraPosition:
          CameraPosition(target: LatLng(15.841461, 74.512202), zoom: 18),
      onMapCreated: (GoogleMapController controller) {
        _controller.complete(controller);
      },
      markers: {belgaum},
    ),

mapType: Specify which kind of map interface do you want to load.

  • normal.
  • satellite.
  •  hybrid.
  • terrain.

MapType in flutter google maps widget

initialCameraPosition: This will load the map with initial camera position may be currect location of the users.

onMapCreated: this will create a map with complete controls to the map you can zoom in, zoom out, go to other location in the map and many things under your controls.

Google Marker

Marker belgaum = Marker(
  markerId: MarkerId("Belgaum"),
  position: LatLng(15.841461, 74.512202),
  infoWindow: InfoWindow(title: "Belgaum"),
  icon: BitmapDescriptor.defaultMarkerWithHue(BitmapDescriptor.hueRose),
);

The Marker will keep a marker on the position you have or any be the destination point you want to travel to.

Flutter google maps  Complete Source Code with example

Copy paste the below source code in main.dart file

NOTE: Don’t forget to specify the API KEY, else the google maps will not work/load.

import 'dart:async';

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

void main() => runApp(MyApp());
Completer<GoogleMapController> _controller = Completer();

class MyApp extends StatelessWidget {
  // This widget is the root of your application.

  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'Flutter Demo',
      theme: ThemeData(
        primarySwatch: Colors.blue,
      ),
      home: MyHomePage(),
    );
  }
}

class MyHomePage extends StatefulWidget {
  @override
  _MyHomePageState createState() => _MyHomePageState();
}

class _MyHomePageState extends State<MyHomePage> {
  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text("Google Maps in Flutter Example"),
      ),
      body: Stack(
        children: <Widget>[_googleMaps(context)],
      ),
      floatingActionButton: FloatingActionButton.extended(
        onPressed: _goToNextLocation,
        label: Text('To the Next Location'),
        icon: Icon(Icons.directions_boat),
      ),
    );
  }
}

Widget _googleMaps(BuildContext context) {
  return Container(
    height: MediaQuery.of(context).size.height,
    width: MediaQuery.of(context).size.width,
    child: GoogleMap(
      mapType: MapType.terrain,
      initialCameraPosition:
          CameraPosition(target: LatLng(15.841461, 74.512202), zoom: 18),
      onMapCreated: (GoogleMapController controller) {
        _controller.complete(controller);
      },
      markers: {belgaum},
    ),
  );
}

Marker belgaum = Marker(
  markerId: MarkerId("Belgaum"),
  position: LatLng(15.841461, 74.512202),
  infoWindow: InfoWindow(title: "Belgaum"),
  icon: BitmapDescriptor.defaultMarkerWithHue(BitmapDescriptor.hueRose),
);

Future<void> _goToNextLocation() async {
  final GoogleMapController controller = await _controller.future;
  controller.animateCamera(
    CameraUpdate.newCameraPosition(
      CameraPosition(
          target: LatLng(37.43296265331129, -122.08832357078792),
          zoom: 19.151926040649414,
          tilt: 59.440717697143555,
          bearing: 192.8334901395799),
    ),
  );
}