Home Blog Page 87

RecyclerView With GridLayoutManager Show Grid View in androidx

2

Hi Guys, welcome to Proto Coders Point,In this Android Tutorial we will implement RecyclerView with GridView basically using GridLayoutManager.

The RecyclerView is one of the advance and most flexiable version of ListView and GridView.

It is mostly used to show large number of data sets to the user when user scrolls the view.

it’s is available to use in Material Design of API leven 21 (i.e Android 5.0 Lollipop).

Demo of Final Result of this Tutorial

recycler View with Grid View layout manager

Gradle Dependency to use RecyclerView:

dependencies {
 ...
 implementation "com.android.support:recyclerview-v7:23.23.4.0"
 }

or

if you have latest version of android studio with androidx

you need to add material dependencies

dependencies
{
..............
implementation 'com.google.android.material:material:1.2.0-alpha04' // recycleView is inbuilt in this
}

The material package comes with RecycleView Components.

RecycleView XML code in older version of android studio

<?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"
    tools:context="protocoderspoint.com.recyclerviewexample.MainActivity">
    <android.support.v7.widget.RecyclerView
        android:id="@+id/recyclerView"
        android:layout_width="match_parent"
        android:layout_height="match_parent" />
</RelativeLayout>

RecycleView XML code for androidx

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

    <androidx.recyclerview.widget.RecyclerView
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:id="@+id/recycleview"/>
    
</LinearLayout>

RecyclerView With GridLayoutManager in androidx with Example

Let’s us now start implementing our android application with RecycleView with GridLayoutManager with example.

Step 1: Create a New Project And Name It RecyclerViewExample.

OfCouse, your need to create a new android project using android-studio, or else you can make use of your existing android project.

Step 2 : Add Required Dependencies

Once your project is ready you need to first add the recyclerView Dependencies in to your android project so that you can make user of recyclerView widget.

if you are using android-studio version that comes with migrating to androidx then better use material or else you can use recyclerView Dependencies.

The dependencies is been listed above.

Step 3 : Adding recyclerView in activity_main.xml

open > project > app > res > layout > activity_main.xml

And Copy and paste the below lines of xml code with recyclerView widget.

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

    <androidx.recyclerview.widget.RecyclerView
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:id="@+id/recycleview"/>

</LinearLayout>

 

Step 4 : Create a new XML File and name it as row_layout_view.xml

This XML View will be Displayed under RecyclerView in activity_main.xml in a form of GridView

Here we  Simple have an imageView and a textView that will show some date sets.

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:padding="5dp"
    android:layout_gravity="center"
    android:gravity="center"
    android:orientation="vertical"
    android:layout_margin="5dp"
    android:background="@drawable/recyclebackground"
    >
    <!--
    grid items for RecyclerView GridView Example
    -->
    <ImageView
        android:id="@+id/image"
        android:layout_width="200dp"
        android:layout_height="200dp"
        android:layout_gravity="center"
        android:scaleType="fitXY"
        android:src="@mipmap/ic_launcher" />

    <TextView
        android:id="@+id/name"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="....."
        android:gravity="center"
        android:background="#1E88E5"
        android:layout_gravity="center"
        android:textColor="#FAF5F5"
        android:textSize="15sp" />
</LinearLayout>

Step 5 : create a new xml file in drawable

Create a new drawable XML file in Drawable folder and name it recyclebackground.xml 

<?xml version="1.0" encoding="utf-8"?>
<shape xmlns:android="http://schemas.android.com/apk/res/android">
    <!--
       stroke with color and width for creating outer line
    -->
    <stroke
        android:width="1dp"
        android:color="#000" />
</shape>

 

Step 6: Create a new Adopter Class

Then, you will need a Adopter class that will help you in  handling all the data and display then in recyclerView.

Create a new Adopter Class and name it as CustomRecycleAdopter.java

App > java > your Package (Right click) > New > java class

This CustomRecycleAdopter class will extends RecyclerView.Adapter class which incluse Viewholder in it.

Then  we will implement some override methods and create a constructor to get the data from Main_Activity Class.

In CustomRecycleAdapter class we have 2 methods those are OnCreateViewHolder that helps use to inflate the row_layout_view.xml view Items and then pass it to ViewHolder and the other method is onBindViewHolder that is been used to set the data in the views by the help of ViewHolder.

Then Finally we implement the setOnClickListener on the itemview that show use which gridView in recyclerView was clicked by the user

Then you Just Copy paste the Below Code

package com.ui.recycleview.gridview.layoutmanager;

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

import androidx.annotation.NonNull;
import androidx.recyclerview.widget.RecyclerView;

import java.util.ArrayList;
public class CustomRecyclerViewAdopter extends RecyclerView.Adapter {
    ArrayList personNames;
    ArrayList personImages;
    Context context;
    public CustomRecyclerViewAdopter(Context context, ArrayList personNames, ArrayList personImages) {
        this.context = context;
        this.personNames = personNames;
        this.personImages = personImages;
    }
    @Override
    public MyViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
        // infalte the item Layout
        View v = LayoutInflater.from(parent.getContext()).inflate(R.layout.row_layout_view, parent, false);
        // set the view's size, margins, paddings and layout parameters
        MyViewHolder vh = new MyViewHolder(v); // pass the view to View Holder
        return vh;
    }

    @Override
    public void onBindViewHolder(@NonNull RecyclerView.ViewHolder holder, final int position) {
        // set the data in items
        MyViewHolder viewHolder= (MyViewHolder)holder;
        ((MyViewHolder) holder).name.setText( personNames.get(position).toString());
        ((MyViewHolder) holder).image.setImageResource((Integer) personImages.get(position));
        // implement setOnClickListener event on item view.
        holder.itemView.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                Toast.makeText(context,"Person : "+(position+1),Toast.LENGTH_SHORT).show();
            }
        });
    }


    @Override
    public int getItemCount() {
        return personNames.size();
    }
    public class MyViewHolder extends RecyclerView.ViewHolder {
        // init the item view's
        TextView name;
        ImageView image;
        public MyViewHolder(View itemView) {
            super(itemView);
            // get the reference of item view's
            name = (TextView) itemView.findViewById(R.id.name);
            image = (ImageView) itemView.findViewById(R.id.image);
        }
    }
}

Step 7 : Passing Data from Main_Activity.java to CustomRecyclerAdopter.java

Now, Firstly you need to get References to recycleView and then pass data to Adopter.

Then we are creating a list of data using java ArrayList name it as Person Name and likewise i have created a list of Images using ArrayList.

There after we set the recyclerView with GridLayoutManager and then we set the Adopter that show the Grid Items in out RecyclerView Widget.

Main_Activity.java

package com.ui.recycleview.gridview.layoutmanager;

import android.os.Bundle;

import androidx.appcompat.app.AppCompatActivity;
import androidx.recyclerview.widget.GridLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import java.util.ArrayList;
import java.util.Arrays;
public class MainActivity extends AppCompatActivity {
    // ArrayList for person names
    ArrayList personNames = new ArrayList<>(Arrays.asList("Person 1", "Person 2", "Person 3", "Person 4", "Person 5", "Person 6", "Person 7","Person 8", "Person 9", "Person 10", "Person 11", "Person 12", "Person 13", "Person 14"));
    ArrayList personImages = new ArrayList<>(Arrays.asList(R.drawable.ic_person_black_24dp, R.drawable.ic_person_black_24dp, R.drawable.ic_person_black_24dp, R.drawable.ic_person_black_24dp, R.drawable.ic_person_black_24dp, R.drawable.ic_person_black_24dp, R.drawable.ic_person_black_24dp,R.drawable.ic_person_black_24dp, R.drawable.ic_person_black_24dp, R.drawable.ic_person_black_24dp, R.drawable.ic_person_black_24dp, R.drawable.ic_person_black_24dp, R.drawable.ic_person_black_24dp, R.drawable.ic_person_black_24dp));
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        setContentView(R.layout.activity_main);

        // get the reference of RecyclerView
        RecyclerView recyclerView = (RecyclerView) findViewById(R.id.recycleview);

        // set a GridLayoutManager with default vertical orientation and 2 number of columns
        GridLayoutManager gridLayoutManager = new GridLayoutManager(getApplicationContext(),2); // you can change grid columns to 3 or more

        recyclerView.setLayoutManager(gridLayoutManager); // set LayoutManager to RecyclerView
        //  call the constructor of CustomAdapter to send the reference and data to Adapter
        CustomRecyclerViewAdopter customAdapter = new CustomRecyclerViewAdopter(MainActivity.this, personNames,personImages);
        recyclerView.setAdapter(customAdapter); // set the Adapter to RecyclerView
    }
}

 

And the last thing is that you need to add some images in drawable to show them into Recycle GridView

I have simple created a vector images assets under drawable folder.

Just Right Click on Drawable  folder > New > Vector Assets

person_blue.xml

<vector android:height="24dp" android:tint="#0324FA"
    android:viewportHeight="24.0" android:viewportWidth="24.0"
    android:width="24dp" xmlns:android="http://schemas.android.com/apk/res/android">
    <path android:fillColor="#FF000000" android:pathData="M12,12c2.21,0 4,-1.79 4,-4s-1.79,-4 -4,-4 -4,1.79 -4,4 1.79,4 4,4zM12,14c-2.67,0 -8,1.34 -8,4v2h16v-2c0,-2.66 -5.33,-4 -8,-4z"/>
</vector>

Flutter Toast Message Example – Show Toast in flutter

3
Flutter Toast Message
Flutter Toast Message

Hi Guys, Welcome to Proto Coders Point, In this Flutter Tutorial we will see how can we show toast message in Flutter app.

visit official Site to learn more https://pub.dev/packages/fluttertoast

What is Toast Message?

Some Times Toast Messages are also called as Toast Notification.

It’s a small message that pops up at the bottom of the device screen and immediately disappears on its own after a delay of few seconds,

This are mostly used to show a feedback on the operation that is preformed by the user.

So, Let’s Begin Implementing FlutterToast Message into your project

Result of the Tutorial

flutter toast message top
flutter toast message top

Step 1 : Adding Flutter Toast Dependencies in project

To get access to Futter Toast you need to add it’s Plugin into your Flutter Project

Open pubspec.yaml  and add the dependencies plugin

dependencies:
  flutter:
    sdk: flutter
  cupertino_icons: ^0.1.2
  fluttertoast: ^3.1.3    // add this line

Note :  This Plugin version might get updated so better be updated with latest version ( here )

Step 2 : Import the Fluttertoast dart package

Now, once you have added dependencies into you project now you can user the Flutter Toast plugin anywhere in your project to show the toast message

Open main.dart  and then at the top import the package

import 'package:fluttertoast/fluttertoast.dart';

Step 3 : How to use the Toast message widget in flutter

Fluttertoast.showToast(
        msg: "This is Bottom Short Toast",
        toastLength: Toast.LENGTH_SHORT,
        gravity: ToastGravity.BOTTOM,
        timeInSecForIos: 1,
        backgroundColor: Colors.red,
        textColor: Colors.white,
        fontSize: 16.0
    );

There are several properties that you can user to show the Toast message.

propertyDescription
msgString ( Required )
toastlengthToast.LENGTH_SHORT or Toast.LENGTH_LONG
gravityToastGravity.TOP or ToastGravity.CENTER or ToastGravity.BOTTOM
timeInSecforIosonly for Ios ( 1 sec or more )
backgroundColorColors.blue
textColorColors.red
fontSize16.0

And to Cancel all the Toast Calls then you can user

FlutterToast.cancel() : This will Immediately cancel all the request to show Message to user.

If you don’t want to user androidx then make user of older version of fluttertoast 2.211

How to Show Toast in Flutter App with Example  – Complete Code

Copy and paste the below lines of code in main.dart  file to make toast message work

import 'package:flutter/material.dart';
import 'package:fluttertoast/fluttertoast.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 Demo',
      theme: ThemeData(
        primarySwatch: Colors.blue,
      ),
      home: MyHomePage(),
    );
  }
}

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

class _MyHomePageState extends State<MyHomePage> {
  Function toast(
      String msg, Toast toast, ToastGravity toastGravity, Color colors) {
    Fluttertoast.showToast(
        msg: msg,
        toastLength: toast,
        gravity: toastGravity,
        timeInSecForIos: 1,
        backgroundColor: colors,
        textColor: Colors.white,
        fontSize: 16.0);
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text("Flutter Toast"),
      ),
      body: Center(
        child: Column(
          mainAxisAlignment: MainAxisAlignment.center,
          children: <Widget>[
            Text("Demo on Flutter Toast Message Plugin"),
            SizedBox(
              height: 20.0,
            ),
            MaterialButton(
              elevation: 5.0,
              height: 50.0,
              minWidth: 100,
              color: Colors.blueAccent,
              textColor: Colors.white,
              child: Text("Show Toast at Bottom"),
              onPressed: () {
                toast(
                    "This is Demo 1 Toast at BOTTOM",
                    Toast.LENGTH_LONG,
                    ToastGravity.BOTTOM,
                    Colors.green); // calling a function to show Toast message
              },
            ),
            SizedBox(
              height: 20.0,
            ),
            MaterialButton(
              elevation: 5.0,
              height: 50.0,
              minWidth: 100,
              color: Colors.redAccent,
              textColor: Colors.white,
              child: Text("Show Toast at TOP"),
              onPressed: () {
                toast(
                    "This is Demo 2 Toast at top",
                    Toast.LENGTH_SHORT,
                    ToastGravity.TOP,
                    Colors.red); // calling a function to show Toast message
              },
            ),
          ],
        ),
      ),
    );
  }
}

And there you go App is ready to show the toast message in flutter to the users.

Recommended Articles

Custom toast in android

Bot toast flutter

Toast Message using VelocityX

Connect flutter app to firebase Console – firebase integration – Android

2
firebase integration in flutter Application
firebase integration in flutter Application

Hi Guys, Welcome to Proto Coders Point , In this Tutorial we are going to add Firebase Integration in Flutter Project.

To make user of Firebase Services in our Flutter Application, We must add Firebase SDK and Required Dependencies in our Flutter Project.

Let’s Integrate Firebase with Flutter Application by Following below steps.

VIDEO TUTORIAL

 

Step1 : Create a new Flutter Project in android Studio

As usually you need to Create a new Flutter Project in your android-studio.

File > New > New Flutter Project

Step 2 : Create a new Firebase Project in firebase Console.

create add new project in firebase console
create add new project in firebase console

Go to Firebase console Sign-In with your Google Account, you will see and cardView to add new Firebase Project, Just Click on it

1. Give a name to your project in Firebase Console.

Giving name you firebase project in console
Giving name you firebase project in console

   2. Configure Google Analytic Give some name, Agree the Form and Continue.

Configure google analytic
Configure google analytic

Just Configure the Google Analytic and accept all the Agreement Form and Continue to next process.

creating Firebase project completed
creating Firebase project completed

Then,  Firebase Proejct for your flutter app is successfully been created now hit the continue button.

Step 3 : Get Started by adding Firebase to your app

Their are 4 platform where you are integrate your Flutter project with Firebase as backend.

iOS, Android, Web and Unity development. In this Tutorial we are integrating Firebase with Flutter Application Development ( Android )

So Just Click on Android Icon  if you want to integrate Firebase into your flutter android part.

get Started adding android firebase
get Started adding android firebase

Step 4: Add Firebase to your Android Project.

1. Android Package Name

Navigate / Open build.gradle > search for applicationId ” ………………..”  and Click next.

How to Find Application Id in flutter project
How to Find Application Id in flutter project

On the right side you will see your flutter project under the project extend android > app >build.gradle  scroll-down and search for applicationId and Copy the Id also knows as packageName

Then you have copyed your AppID, come back to firebase console and paste the AppID and hit Next button thus firebase can generate a json file for your application google_services.json.

adding register app and download google-servicesjson file
adding register app and download google-servicesjson file

 2. Adding Google_services.json file

Download Config File Genarated by Firebase copy the file and add it to your project under

Your Project Name > Android > app folder

google services file added
google services file added

Step 5 : Add Firebase SDK to your Project

 1. Project-Level build gradle

Add Google Service Dependencies

Open Project Level Build gradle your project > android > build.gradle  and add the classpath of google services in dependencies.

dependencies {
    ....................................
    classpath 'com.google.gms:google-services:4.3.2'

}

2. App-Level Build Gradle

Add Firebase Analytics dependencies.

Open App Level Build gradle your project > android > app > build.gradle  and add the implemention of google analytics in dependencies.

dependencies {
    ......
    ......
     .....
    implementation 'com.google.firebase:firebase-analytics:17.2.0'  // add this line
}

apply plugin: 'com.google.gms.google-services' // add this line at the botton

Here you go Firebase is added successfully been added in you android section of your flutter project.

Now Once we have added our Flutter project in firebase console, Now it’s time to incorporate the flutter Package that will allow us to work with firebase using dart programming

As you know there are whole bunch of firebase services out their.

Firebase Flutter Fire plugin
Firebase Flutter Fire plugin

Here firebase_core must be added into your project of you want to use any services of firebase.

Firebase Core its the core to start implementing firebase in our flutter project.

Just for the simple i make adding 3 FlutterFire plugin into my project.

Adding Flutter Fire plugin  depencencies  in pubspec.yaml  and then click on Packages get to get all the packaged flutter firebase classes.

adding dependencies in pubspec.yaml
adding dependencies in pubspec.yaml

To use any of this firebase services you just need to import the packages where you want to use then

For example :

import 'package:firebase_auth/firebase_auth.dart';
import 'package:cloud_firestore/cloud_firestore.dart';

 

That’s All your Project is now been added to Firebase console and ready to use firebase services.

 

Android AsyncTask Tutorial Handling JSON and parse JSON

1
Android AsyncTask Tutorial Handling JSON and parse JSON
Android AsyncTask Tutorial Handling JSON and parse JSON

Hi Guys, Welcome to Proto Coders Point  In this Android Tutorial we will Learn about Android  AsyncTask  and Learn How to Fetch JSON data using AsyncTask and Handle them.

Final Project Result

Android AsyncTask Tutorial Handling JSON

What is AsyncTask ?

In android, AsyncTask is been used to run any process that should be run in background and likewise update the UI(User Interface).

Mainly AsyncTask is used to fetch data from a server and this will not effect our main Thread that is handling UI.

AsyncTask ( Asynchronous Task) Help you n running the background Process which will create a seperate Thread to run in background and then Synchronize again with the main Thread, This process will not disturb the main Thread and UI process will run smoothly.

This class will override at least one method i.e doInBackground(Params) and most often will override second method onPostExecute(Result).

To Execute AsyncTask you need to called Execute() method.

The Flow of AsyncTask Process

Androi AsyncTask Flow Process
Androi AsyncTask Flow Process

When AsyncTask class is executed  onPreExecute() is called then doInBackground() is called to execute background processed and at last onPostExecute() method is called to update the data to UI.

Syntax of AsyncTask:

private class DownloadFilesTask extends AsyncTask<URL, Integer, Long> {

@Override
protected void onPreExecute() {
    super.onPreExecute();
    // mostly used to show progress dialog
    // display a progress dialog for good user experiance
   
}
@Override
protected Long doInBackground(URL... urls) {
// code that will run in the background
return ;
}

@Override
protected void onProgressUpdate(Integer... progress) {
// receive progress updates from doInBackground
}

@Oveerride
protected void onPostExecute(Long result) {
// update the UI after background processes completes
}
}

Here is How to execute AsyncTask class from main Thread

new DownloadFilesTask().execute();

Android AsyncTask Example Handling JSON and parse JSON

In the Below Example of AsyncTask We are performing a network operation, where we gonna fetch data from JSON File and Display them in our UI.

My JSON DATA URL : https://protocoderspoint.com/jsondata/superheros.json

Step 1 : As usual Create a new Android project in android studio.

File > New > New Project

Give relevent name to your project

Step 2 : Adding picasso library into our project Dependencies

Gradle Script > build.gradle(app level)

dependencies {
........
.......
implementation 'com.squareup.picasso:picasso:2.71828'
}

Step 3 : UI Design  Open res -> layout ->activity_main.xml add following code

Here we have 5 Views,

  • Button that Perform Click event.
  • Spinner used to select lists.
  • 2 TextViews to Display data fetched from server.
  • 1 ImageView to Display Image from server.
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical"
    android:padding="30dp"
    tools:context=".MainActivity">

    <Button
        android:id="@+id/displayData"
        android:layout_width="200dp"
        android:layout_height="wrap_content"
        android:layout_gravity="center"
        android:layout_marginTop="20dp"
        android:background="@color/colorPrimary"
        android:text="Display Hero Data"
        android:textColor="#fff"
        android:textSize="20sp" />

    <Spinner
        android:id="@+id/selectHero"
        android:layout_marginTop="20dp"
        android:layout_gravity="center"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        />

    <TextView
        android:id="@+id/titleTextView"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginTop="50dp"
        android:text="Hero Name: "
        android:visibility="gone"
        android:textColor="#000"
        android:textSize="18sp" />

    <TextView
        android:id="@+id/categoryTextView"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginTop="5dp"
        android:text="His Ability: "
        android:visibility="gone"
        android:textColor="#000"
        android:textSize="18sp" />

    <ImageView
        android:id="@+id/imageView"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:layout_gravity="center"
        android:visibility="gone"
        android:fitsSystemWindows="true"
        android:layout_marginTop="20dp"
        android:scaleType="centerCrop" />

</LinearLayout>

Step 4: Java Code Open src -> package -> MainActivity.java

In MainActivity.java code.

We first refer the views present in XML File like Buttons, TextView, Spinner and ImageView.

Their after we perform onClick event that execute AsyncTask Class “MyAsyncTasks”.

Then  In doInBackground() we fetch all the data from the server link mentioned above.

Then, In onPostExecute method we simply parse the JSON data fetched and Display then in the UI.

and We have used Picasso Library just to show the Fetch URL image in the ImageView.

package com.ui.asynctaskexample;

import android.app.ProgressDialog;
import android.content.Context;
import android.os.AsyncTask;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.Spinner;
import android.widget.TextView;
import android.widget.Toast;

import androidx.appcompat.app.AppCompatActivity;

import com.squareup.picasso.Picasso;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;

public class MainActivity extends AppCompatActivity {

    String apiUrl = "https://protocoderspoint.com/jsondata/superheros.json";
    String title, image, category;
    TextView titleTextView, categoryTextView;
    ProgressDialog progressDialog;
    Button displayData;
    ImageView imageView;

    int index_no;
    Spinner spinner;


    String[] HerosNameList = { "Flash", "SuperMan", "Thor", "Hulk", "Venom"};

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        // get the reference of View's
        titleTextView = (TextView) findViewById(R.id.titleTextView);
        categoryTextView = (TextView) findViewById(R.id.categoryTextView);
        displayData = (Button) findViewById(R.id.displayData);
        imageView = (ImageView) findViewById(R.id.imageView);


        spinner=(Spinner)findViewById(R.id.selectHero);

        //Creating the ArrayAdapter instance having the country list
        ArrayAdapter aa = new ArrayAdapter(this,android.R.layout.simple_spinner_item,HerosNameList);

        aa.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);

        //Setting the ArrayAdapter data on the Spinner
        spinner.setAdapter(aa);

        spinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
            @Override
            public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
               index_no=position;

            }

            @Override
            public void onNothingSelected(AdapterView<?> parent) {

            }
        });

        // implement setOnClickListener event on displayData button
        displayData.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                // create object of MyAsyncTasks class and execute it
                MyAsyncTasks myAsyncTasks = new MyAsyncTasks();
                myAsyncTasks.execute();
            }
        });
    }

    public class MyAsyncTasks extends AsyncTask<String, String, String> {


        @Override
        protected void onPreExecute() {
            super.onPreExecute();
            // display a progress dialog for good user experiance
            progressDialog = new ProgressDialog(MainActivity.this);
            progressDialog.setMessage("Please Wait");
            progressDialog.setCancelable(false);
            progressDialog.show();
        }

        @Override
        protected String doInBackground(String... params) {

            // implement API in background and store the response in current variable
            String current = "";
            try {
                URL url;
                HttpURLConnection urlConnection = null;
                try {
                    url = new URL(apiUrl);

                    urlConnection = (HttpURLConnection) url.openConnection();

                    InputStream in = urlConnection.getInputStream();

                    InputStreamReader isw = new InputStreamReader(in);

                    int data = isw.read();


                    while (data != -1) {
                        current += (char) data;
                        data = isw.read();
                        System.out.print(current);

                    }

                   Log.d("datalength",""+current.length());
                    // return the data to onPostExecute method
                    return current;

                } catch (Exception e) {
                    e.printStackTrace();
                } finally {
                    if (urlConnection != null) {
                        urlConnection.disconnect();
                    }
                }

            } catch (Exception e) {
                e.printStackTrace();
                return "Exception: " + e.getMessage();
            }
            return current;
        }

        @Override
        protected void onPostExecute(String s) {

            Log.d("data", s.toString());
            // dismiss the progress dialog after receiving data from API
            progressDialog.dismiss();
            try {

                JSONObject jsonObject = new JSONObject(s);

                JSONArray jsonArray1 = jsonObject.getJSONArray("superheros");

                JSONObject jsonObject1 =jsonArray1.getJSONObject(index_no);
                title = jsonObject1.getString("name");
                category = jsonObject1.getString("power");
                image=jsonObject1.getString("url");

                //make all the view Visible when data is ready to show
                titleTextView.setVisibility(View.VISIBLE);
                categoryTextView.setVisibility(View.VISIBLE);
                imageView.setVisibility(View.VISIBLE);

                titleTextView.setText("Hero Name : "+title);
                categoryTextView.setText("His Ability : "+category);
                Picasso.get().load(image).into(imageView);

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

    }
}

Step 5 : Adding a INTERNET PERMISSION in manifest.xml file

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

And their you go the app is ready to get Tested.

 

More on:  How to Parse JSON data in flutter app development

Flutter Profile Page UI :  Flutter Profile Page UI Design

 

 

 

Flutter Sliver App Bar – An Collapsing ScrollView App Bar

0
Flutter Sliver App Bar Example
Flutter Sliver App Bar Example

Hi Guys, Welcome to Proto Coders Point , In This Tutorial we gonna implement A Sliver App Bar in Flutter App.

What is Sliver AppBar Class?

A Sliver AppBar in Flutter is similar to any normal AppBar, The Different here is only that Sliver AppBar come with ScrollView effect.

The Sliver App bar should be the first child of a CustomScrollView, Using with we can integrate the appbar with a scroll view so that it can vary in height and other content of the scrollview.

Implementation with Sliver AppBar Widget

Below Examples will show you how appbars can we integrated with different configurations and act with different behaviour when any user Scrolls the View up or down.

Example 1:

When App bar with

  1. floating: false,
  2. pinned: false,
  3. snap: false

Sliver App bar flutter
Example 1

StateFull Class Code

class _NewPageState extends State<NewPage> {
  @override
  Widget build(BuildContext context) {
    return Scaffold(
      body: CustomScrollView(
        slivers: <Widget>[
          SliverAppBar(
            expandedHeight: 150.0,
            floating: false,
            pinned: false,
            snap: false,
            actions: <Widget>[
              IconButton(
                icon: const Icon(Icons.add_circle),
                onPressed: () {},
              ),
            ],
            flexibleSpace: FlexibleSpaceBar(
              title: Text(
                "Sliver App Bar Example",
                style: TextStyle(fontSize: 15),
              ),
              background: Image.asset(
                'images/images.jpeg',
                fit: BoxFit.cover,
              ),
            ),
          ),
          SliverFillRemaining(
            child: new Center(
              child: new Column(
                mainAxisAlignment: MainAxisAlignment.center,
                children: <Widget>[
                  Image.asset('images/protocoderspointlogo.png'),
                  SizedBox(
                    height: 20.0,
                  ),
                  Text(
                    "This is an Simple Sliver App Bar Flutter Example",
                    style:
                        TextStyle(fontSize: 15.0, fontWeight: FontWeight.w800),
                  ),
                ],
              ),
            ),
          )
        ],
      ),
    );
  }
}

 

Example 2 :

When Sliver App bar with

  1. floating: true,
  2. pinned: true,
  3. snap: false

sliver app bar example 2 scrollview

 

The Code base for this to work is very simply in the above lined of code you just need to change floating to true and pinned to true,  this Configuration will simple pin the app bar at the top of the screen when used scroll through the app and  other remaining widget will simple scroll to the end.

StateFull Class Code

class _NewPageState extends State<NewPage> {
  @override
  Widget build(BuildContext context) {
    return Scaffold(
      body: CustomScrollView(
        slivers: <Widget>[
          SliverAppBar(
            expandedHeight: 150.0,
            floating: true, //change is here 
            pinned: true, //change si
            snap: true,
            actions: <Widget>[
              IconButton(
                icon: const Icon(Icons.add_circle),
                onPressed: () {},
              ),
            ],
            flexibleSpace: FlexibleSpaceBar(
              title: Text(
                "Sliver App Bar Example",
                style: TextStyle(fontSize: 15),
              ),
              background: Image.asset(
                'images/images.jpeg',
                fit: BoxFit.cover,
              ),
            ),
          ),
          SliverFillRemaining(
            child: new Center(
              child: new Column(
                mainAxisAlignment: MainAxisAlignment.center,
                children: <Widget>[
                  Image.asset('images/protocoderspointlogo.png'),
                  SizedBox(
                    height: 20.0,
                  ),
                  Text(
                    "This is an Simple Sliver App Bar Flutter Example",
                    style:
                        TextStyle(fontSize: 15.0, fontWeight: FontWeight.w800),
                  ),
                ],
              ),
            ),
          )
        ],
      ),
    );
  }
}

Explaination of above code

1. As i said before that Sliver App bar must be the child of CustomScrollView to get Scrolling effect, The CustomScrollView will make  the SliverAppBar into Scrolling.

2. Here i have Used an IconButton just to Show that you can even add IconButton Widget into the Appbar. i’e IconButton, which is used with actions to show buttons on the app bar.

Snippet

actions: <Widget>[
              IconButton(
                icon: const Icon(Icons.add_circle),
                onPressed: () {},
              ),
            ],

Flexible SpaceBar  is used so that we can easily set and maximum expandable size to it when user scroll the app Down-words,

And Even we can set many other properties like background,title etc

SliverFillRemaining that fills the remaining space in the viewport. In Other words The Remaining  body should not be null, is the Remaininig body is null then the app bar scrollview will not work as accepted, this value cannot be null.

So i have just Defined some widget in the remaining part in Sliver Fill Remaining

which has a child which is set to center , in turn has a child Column, then This Column have 3 children widget Image,SixedBox,and a Text.

Snippet Code

SliverFillRemaining(
            child: new Center(
              child: new Column(
                mainAxisAlignment: MainAxisAlignment.center,
                children: <Widget>[
                  Image.asset('images/protocoderspointlogo.png'),
                  SizedBox(
                    height: 20.0,
                  ),
                  Text(
                    "This is an Simple Sliver App Bar Flutter Example",
                    style:
                        TextStyle(fontSize: 15.0, fontWeight: FontWeight.w800),
                  ),
                ],
              ),
            ),
          )

 

Complete Source code of Flutter Sliver App Bar – An Collapsing ScrollView App Bar 

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 Demo',
      theme: ThemeData(
        // This is the theme of your application.
        //
        // Try running your application with "flutter run". You'll see the
        // application has a blue toolbar. Then, without quitting the app, try
        // changing the primarySwatch below to Colors.green and then invoke
        // "hot reload" (press "r" in the console where you ran "flutter run",
        // or simply save your changes to "hot reload" in a Flutter IDE).
        // Notice that the counter didn't reset back to zero; the application
        // is not restarted.
        primarySwatch: Colors.blue,
      ),
      home: NewPage(),
    );
  }
}

class NewPage extends StatefulWidget {
  @override
  _NewPageState createState() => _NewPageState();
}

class _NewPageState extends State<NewPage> {
  @override
  Widget build(BuildContext context) {
    return Scaffold(
      body: CustomScrollView(
        slivers: <Widget>[
          SliverAppBar(
            expandedHeight: 150.0,
            floating: true,
            pinned: true,
            snap: true,
            actions: <Widget>[
              IconButton(
                icon: const Icon(Icons.add_circle),
                onPressed: () {},
              ),
            ],
            flexibleSpace: FlexibleSpaceBar(
              title: Text(
                "Sliver App Bar Example",
                style: TextStyle(fontSize: 15),
              ),
              background: Image.asset(
                'images/images.jpeg',
                fit: BoxFit.cover,
              ),
            ),
          ),
          SliverFillRemaining(
            child: new Center(
              child: new Column(
                mainAxisAlignment: MainAxisAlignment.center,
                children: <Widget>[
                  Image.asset('images/protocoderspointlogo.png'),
                  SizedBox(
                    height: 20.0,
                  ),
                  Text(
                    "This is an Simple Sliver App Bar Flutter Example",
                    style:
                        TextStyle(fontSize: 15.0, fontWeight: FontWeight.w800),
                  ),
                ],
              ),
            ),
          )
        ],
      ),
    );
  }
}