Thursday, October 8, 2020

Easiest Way to implement the Bottom Navigation Bar using fragments in Android Studio



What is bottom bar?

Bottom bar is used as an alternative to the top toolbar or tabs activity. It allows movement between the primary screens of the application. It generally has three to five destinations each associated with different layout or content. In this article I am going to help you achieve the goal of implementing the bottom bar with the help of fragments.

How to use bottom bar in Andoid studio?


Step 1: Create a new Android Studio project and complete all the further steps.

Step2: Create a new menu resource file by going to res -> new -> Android Resource file name the file and select the resource type as Menu.





Step 3: Make number of menus according to your needs and assign them the icon and the text as shown below

 <?xml version="1.0" encoding="utf-8"?>  
 <menu xmlns:android="http://schemas.android.com/apk/res/android"  
   xmlns:app="http://schemas.android.com/apk/res-auto">  
   <item  
     android:id="@+id/id1"  
     android:icon="@drawable/home"  
     android:title="@string/home" />  
   <item  
     android:id="@+id/id2"  
     android:icon="@drawable/authentication"  
     android:title="@string/authentication" />  
   <item  
     android:id="@+id/id3"  
     android:icon="@drawable/discover"  
     android:title="@string/discover"/>  
   <item  
     android:id="@+id/id4"  
     android:icon="@drawable/me"  
     android:title="@string/me" />  
 </menu>  

Step 4: Now in your activity_main.xml file add a bottom navigation view and a frame layout and constraint them as shown below.

 <?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">  
   <FrameLayout  
     android:id="@+id/parentLayout"  
     android:layout_width="match_parent"  
     android:layout_height="0dp"  
     app:layout_constraintBottom_toTopOf="@+id/bottomNavigationView"  
     app:layout_constraintEnd_toEndOf="parent"  
     app:layout_constraintStart_toStartOf="parent"  
     app:layout_constraintTop_toTopOf="parent"></FrameLayout>  
   <com.google.android.material.bottomnavigation.BottomNavigationView  
     android:id="@+id/bottomNavigationView"  
     android:layout_width="match_parent"  
     android:layout_height="wrap_content"  
     android:animateLayoutChanges="false"  
     android:background="@drawable/botton_menu_bg"  
     android:paddingBottom="20dp"  
     app:layout_constraintBottom_toBottomOf="parent"  
     app:layout_constraintEnd_toEndOf="parent"  
     app:layout_constraintHorizontal_bias="1.0"  
     app:layout_constraintStart_toStartOf="parent"  
     app:menu="@menu/bottom_nav_menu" />  
 </androidx.constraintlayout.widget.ConstraintLayout>  

Result till now



Step 5: Now Its the time to declare all the four fragments. Go to new -> Fragment -> Blank Fragment and name them as Home, Authentication, Discover, Me. Don't forget to change the text in the xml files of all the four fragments. Otherwise how will we differentiate them?...

Step 6: Navigate to MainActivity.java file and declare all the four fragments there. As shown in the code below.

 public class MainActivity extends AppCompatActivity {  
   private Home home = new Home();  
   private Authentication authentication = new Authentication();  
   private Discover discover = new Discover();  
   private Me me = new Me();  
   @Override  
   protected void onCreate(Bundle savedInstanceState) {  
     super.onCreate(savedInstanceState);  
     setContentView(R.layout.activity_main);  
   }  
 }  

Step 7: Now we can move towards the declaration and initialization of a  Fragment object, fragment manager and bottom navigation view. The code after performing the tasks looks like this.
Also don't forget to implement BottomNavigationView.OnNavigationItemSelectedListener.

 public class MainActivity extends AppCompatActivity implements BottomNavigationView.OnNavigationItemSelectedListener {  
   
   private Home home = new Home();  
   private Authentication authentication = new Authentication();  
   private Discover discover = new Discover();  
   private Me me = new Me();  
   
   
   
   private Fragment activeFragment = null;  //step 7
   private FragmentManager manager;  //step 7
   BottomNavigationView bottomNavigationView;  //step 7
   
   
   @Override  
   protected void onCreate(Bundle savedInstanceState) {  
     super.onCreate(savedInstanceState);  
     setContentView(R.layout.activity_main);  
   
     bottomNavigationView = findViewById(R.id.bottomNavigationView); //step 7 
       
     setUpBottomNavigation();  //step 7
   
   }  
   
   //bottom navigatio view setup  //step 7
   private void setUpBottomNavigation() {  
     bottomNavigationView.setOnNavigationItemSelectedListener(this);  
     manager = getSupportFragmentManager();  
     activeFragment = home;  
   }  
   
     
   
   @Override  
   public boolean onNavigationItemSelected(@NonNull MenuItem item) {  
     return false;  
   }  
 }  


Step 8: Now add the rest of code to the original code file.


 public class MainActivity extends AppCompatActivity implements BottomNavigationView.OnNavigationItemSelectedListener {  
   
   private Home home = new Home();  
   private Authentication authentication = new Authentication();  
   private Discover discover = new Discover();  
   private Me me = new Me();  
   
   
   
   private Fragment activeFragment = null;  
   private FragmentManager manager;  
   BottomNavigationView bottomNavigationView;  
   
   
   @Override  
   protected void onCreate(Bundle savedInstanceState) {  
     super.onCreate(savedInstanceState);  
     setContentView(R.layout.activity_main);  
   
     bottomNavigationView = findViewById(R.id.bottomNavigationView);  
   
     addAllFragmentOnce();  
     setUpBottomNavigation();  
   }  
   
   
   //bottom navigatio view setup  
   private void setUpBottomNavigation() {  
     bottomNavigationView.setOnNavigationItemSelectedListener(this);  
     manager = getSupportFragmentManager();  
     activeFragment = me;  
   }  
   
   private void addAllFragmentOnce() {  
   
     manager.beginTransaction()  
         .add(R.id.parentLayout, activeFragment)  
         .commit();  
   
     manager.beginTransaction()  
         .add(R.id.parentLayout, authentication)  
         .hide(authentication)  
         .commit();  
   
     manager.beginTransaction()  
         .add(R.id.parentLayout, discover)  
         .hide(discover)  
         .commit();  
   
     manager.beginTransaction()  
         .add(R.id.parentLayout, me)  
         .hide(me)  
         .commit();  
   
   }  
   
   //-------show fragment based on selection item id---------------  
   private void showHideFragment(Fragment fragment) {  
     manager.beginTransaction()  
         .hide(activeFragment)  
         .show(fragment)  
         .commit();  
   }  
   
   @Override  
   public boolean onNavigationItemSelected(@NonNull MenuItem menuItem) {  
     switch (menuItem.getItemId()) {  
   
       case R.id.id1:  
         clearBackStack();  
         showHideFragment(home);  
         activeFragment = home;  
         break;  
   
       case R.id.id2:  
         clearBackStack();  
         showHideFragment(authentication);  
         activeFragment = authentication;  
         break;  
   
       case R.id.id3:  
         clearBackStack();  
         showHideFragment(discover);  
         activeFragment = discover;  
         break;  
   
       case R.id.id4:  
         clearBackStack();  
         showHideFragment(me);  
         activeFragment = me;  
         break;  
     }  
     return true;  
   }  
   
   //  --------------clear the fragments from the stack-------------------  
   private void clearBackStack() {  
     FragmentManager fm = this.getSupportFragmentManager();  
     for (int i = 0; i < fm.getBackStackEntryCount(); ++i) {  
       fm.popBackStack();  
     }  
   }  

  Don't know what's happeing ?No worries,First have a look at this and try to understand then I will explain what's happening here.

Okay Let me explain now.
After initialising and declaration I added all the fragments to the transition list in the method addAllFragmentAtOnce() and displayed only first one i.e active fragment, all others transition are hidden.

In the method setUpBottomNavigation() I set up a onItemClick listener and initially set home as the active fragment.

onNavigationItemSelected() method is called when the navigation item is clicked and based on the id of the items it displays and hide the fragments using the method clearBackStack() and showHideFragment();

Cheers! You successfully implemented the bottom navigation with the help of fragments.


Conclusion 

You just learned how you can use fragments and implement bottom navigation bar in an android application using Android Studio. However, if you think you need this at any later time consider bookmarking this.

If you have any questions you can ask me in the comment section.

Wednesday, October 7, 2020

One out of four people learned to code this lockdown research says



Not everyone wasted their precious time. There are Some people those chose to use their free time in learning the new stuff.

A survey done by Boxboat on more than 1000 people delved into what skills they were improving and how they went about learning them.

These are some of the top languages learned by people during the lockdown.

The python language as expected topped the list followed by java and C++. 

People surveyed were asked the question "What areas of technology did you learn or improve during covid-19 ?"
The result came out as follows

 It has been observed that greatest motivation for the people setting out to improve their skills were career development (55%), personal development (46%), and improving job search prospects (33%).

When the above data is broken then you'll get to know that 3 out of 4 millennials learned some tech skill .

Boosting your resume had been easier than ever now a days with this trend which is going on.

Free content provider like YouTube were source for up to 2/3 of the people to upskill while 1/3 of people choose to pave their upskilling path with the help of paid resources.

Despite the lockdown which halted the economy of all countries all around the world and was indeed very necessary the data shows there are more no of people who have upskilled them.

On average, people spent nearly about 7 hours per week in upskilling themselves in tech field. 
Those who lost their jobs were seen spending about 8 hours weekly. Millennials and students spent the most time learning coding and programming languages each week at about 10 hours, while improving telecommunication proficiency required the least study time at just over 6 hours.

Tuesday, October 6, 2020

How to open a custom dialog box in Android ?


What is a dialog box?

A dialog box is a small area of a screen generally termed as a popup screen which is used to provide information or select commands.

How to implement a custom dialog box in an android app using Java?


Through this example, you are going to learn how you can implement a dialog box easily.

Step 1: Create a new Android Studio project  

File -> new -> New Project and fill all the required details.

Step 2: Create a new layout file and name it custom_dialog.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="wrap_content"  
   android:background="@drawable/layout_bg">  
   <TextView  
     android:textAlignment="center"  
     android:id="@+id/textView49"  
     android:layout_width="0dp"  
     android:layout_height="wrap_content"  
     android:layout_marginStart="50dp"  
     android:layout_marginTop="20dp"  
     android:layout_marginEnd="50dp"  
     android:text="@string/we_gave_you_choice"  
     android:textColor="@color/black"  
     android:textSize="20sp"  
     android:textStyle="bold"  
     app:layout_constraintEnd_toEndOf="parent"  
     app:layout_constraintStart_toStartOf="parent"  
     app:layout_constraintTop_toTopOf="parent" />  
   <TextView  
     android:textAlignment="center"  
     android:id="@+id/textView51"  
     android:textColor="@color/black"  
     android:layout_margin="20dp"  
     android:layout_width="0dp"  
     android:layout_height="wrap_content"  
     android:layout_marginTop="20dp"  
     android:text="@string/edit_the_data_you_enterd"  
     app:layout_constraintEnd_toEndOf="parent"  
     app:layout_constraintStart_toStartOf="parent"  
     app:layout_constraintTop_toBottomOf="@+id/textView49" />  
   <LinearLayout  
     android:layout_marginTop="20dp"  
     android:layout_width="0dp"  
     android:layout_height="wrap_content"  
     android:gravity="center"  
     android:weightSum="2"  
     android:layout_marginBottom="20dp"  
     app:layout_constraintBottom_toBottomOf="parent"  
     app:layout_constraintEnd_toEndOf="parent"  
     app:layout_constraintStart_toStartOf="parent"  
     app:layout_constraintTop_toBottomOf="@+id/textView51">  
     <Button  
       android:layout_marginStart="20dp"  
       android:id="@+id/editButton"  
       android:layout_width="match_parent"  
       android:layout_height="wrap_content"  
       android:layout_weight="1"  
       android:background="@null"  
       android:padding="10dp"  
       android:text="@string/edit"  
       android:textColor="@color/orangeThemeBg"  
       android:textStyle="bold" />  
     <Button  
       android:id="@+id/cancelButton"  
       android:layout_width="match_parent"  
       android:layout_height="wrap_content"  
       android:layout_marginEnd="20dp"  
       android:layout_weight="1"  
       android:background="@drawable/button_orange_custom"  
       android:padding="10dp"  
       android:text="@string/cancel"  
       android:textColor="@color/white"  
       android:textStyle="bold" />  
   </LinearLayout>  
 </androidx.constraintlayout.widget.ConstraintLayout>  
(Design your layout according to your design)

Step 3: In your main screen XML file add a button to the layout.

 <?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/button"  
     android:layout_width="wrap_content"  
     android:layout_height="wrap_content"  
     android:text="Open Dialog"  
     app:layout_constraintBottom_toBottomOf="parent"  
     app:layout_constraintEnd_toEndOf="parent"  
     app:layout_constraintStart_toStartOf="parent"  
     app:layout_constraintTop_toTopOf="parent" />  
 </androidx.constraintlayout.widget.ConstraintLayout>  
Step 4: Initialize the button and set onClickListener on the button.

 public class MainActivity extends AppCompatActivity {  
   Button button;  
   @Override  
   protected void onCreate(Bundle savedInstanceState) {  
     super.onCreate(savedInstanceState);  
     setContentView(R.layout.activity_main);  
     button = findViewById(R.id.button);  
     button.setOnClickListener(new View.OnClickListener() {  
       @Override  
       public void onClick(View view) {  
       }  
     });  
   }  
 }  

Step 5: Now add the following code in your onClick method.

 public class MainActivity extends AppCompatActivity {  
   Button button;  
   @Override  
   protected void onCreate(Bundle savedInstanceState) {  
     super.onCreate(savedInstanceState);  
     setContentView(R.layout.activity_main);  
     button = findViewById(R.id.button);  
     button.setOnClickListener(new View.OnClickListener() {  
       @Override  
       public void onClick(View view) {  
         AlertDialog.Builder builder = new AlertDialog.Builder(MainActivity.this);  
         ViewGroup viewGroup = view.findViewById(android.R.id.content);  
         View dialogView = LayoutInflater.from(view.getContext()).inflate(R.layout.custom_dialog, viewGroup, false);  
         builder.setView(dialogView);  
         final AlertDialog alertDialog = builder.create();  
         alertDialog.getWindow().setBackgroundDrawable(new ColorDrawable(Color.TRANSPARENT));  
         alertDialog.show();  
       }  
     });  
   }  
 }  
In this above example, we are inflating a custom layout using the AlertDialog builder.

Conclusion - Custom dialog box

Time to look at what we learned. AlertDialog will come handy whenever required whenever we need to inflate the custom dialogs in our application. In fact, It is much easier and recommended to implement the custom dialog box by inflating through AlertDialog rather than making the whole activity behave as a dialog.

Comment your thoughts below.




Friday, June 26, 2020

ButtonBar Widget in Flutter : Say no to Row Widget

ButtonBar from its name, itself, suggests that it is a collection of Buttons arranged in the form of a bar or a Row. ButtonBar aims at providing much more stability over how the buttons are arranged.

The ButtonBar Widget in Flutter provides a lot of capability than just merely arranging buttons in a Row. It provides you the option of adding as many buttons as you want as children. We will talk about all of that in this article along with a sample application.

The sample code for ButtonBar is
 ButtonBar(  
    alignment: MainAxisAlignment.center,  
    children: <Widget>[  
     RaisedButton(  
      disabledColor: Colors.white,  
      child: Container(  
       padding: EdgeInsets.all(15),  
       child: Text(  
        'LOGIN HERE',  
        style: TextStyle(  
          color: Colors.black,  
          fontSize: 20,  
          fontWeight: FontWeight.w400),  
       ),  
      ),  
     ),  
     RaisedButton(  
      disabledColor: Colors.blue.shade300,  
      child: Container(  
       padding: EdgeInsets.all(15),  
       child: Text(  
        'CREATE ACCOUNT',  
        style: TextStyle(  
          color: Colors.white,  
          fontSize: 20,  
          fontWeight: FontWeight.w300),  
       ),  
      ),  
     ),  
    ],  
   )  
ButtonBar Widget has Mainly three properties
  1. Children- This is the most important attribute of the three. It takes any number of Buttons Widgets as possible and displays them on the UI easily. There are multiple options available to provide inside the widget , Two most common ones are FlatButton and RaisedButton.
  2. Alignment- The alignment property presents the aligning option to the entire collection of buttons in the ButtonBar Widget. With the help of this, the buttons can be aligned easily.
  3. MainAxisSize- How much space is Horizontal space is provided to the ButtonBar widget is decided by this Attribute.

Sample Application -ButtonBar


This sample application shows the usage of the ButtonBar widget in the Flutter app. I have used two RaisedButton Widgets. However, you can use as many as you want, but it is recommended to use a max of 3.



Conclusion - ButtonBar

Time to look at what we learned. ButtonBar widget will come handy whenever required owing to the types of group buttons provided. In fact, It is much easier to implement the ButtonBar Widget than using the Row widget.

Comment your thoughts below.

Thursday, June 25, 2020

Circular Image View -  Flutter


We have seen many applications transitioning from that traditional square profile previews to these modern and more cool circular ones. Really, we are now used to see them everywhere. 

I tried finding a proper code to achieve this but couldn't succeed, so I decided that I should make a simple one for you.

In this example code, I will show how you can make an image circular.

The code looks like this
 new Container(  
    width: 190.0,  
    height: 190.0,  
    decoration: new BoxDecoration(  
      shape: BoxShape.circle,  
      image: new DecorationImage(  
      fit: BoxFit.cover,  
      image: new NetworkImage(  
          "https://images.pexels.com/photos/1058194/pexels-photo-1058194.jpeg?auto=compress&cs=tinysrgb&dpr=2&h=650&w=940")  
          )  
 )),  
In the above code, I loaded a Network Image. You can choose between the Network image or Assetet image according to your use case.

Explanation

Widget Container is given an equal height and width. The decoration parameter contains a BoxDecoration image which is used to give custom shapes and here it is used to provide a circular shape to the container(BoxShape.circle).

The image parameter of the BoxDecoration Contains a DecorationImage widget which in turn populates the NetworkImage on the screen.

App Example



The full source code for the app is given below.


Conclusion 

You just learned how you can use make any image circular in Flutter using Box Decoration. However, if you think you need this at any later time consider bookmarking this.

If you have any questions you can ask me in the comment section.
Learn to upload files using Multer and Node.js in just 5 minutes

Did you reach a stage in your project where you require a feature to upload files to your database?, or You simply want to learn how uploading of files to the database is done? Don't worry, I got all your answers covered in this article.

Uploading files is one of the most common features these days, and the majority of websites tend to use it somewhere. File uploads in Node.js seem to be a tedious job, but luckily we have multer for the rescue.

Surely there are many options available such as Multiparty and Formidable, but after seeing the popularity, the number of downloads, and ratings. I would say Multer is one of the best-suited options right now.

What exactly is Multer?
Multer is a Node.js Middleware for handling multipart/form-data, which is primarily used for uploading files. It is written on top of the busboy for maximum efficiency. 
Multer adds a body object and a file or files object to the request object. The body object contains the values of the text fields of the form, the file or files object contains the files uploaded via the form.

Let's proceed towards the central part of this article .i.e, how to use multer in our application?. We'll go step by step.

Create the directory and initialize the project - STEP 1
This is, in fact, a very first step for every node.js project. Create the directory and use npm init to create the package.json file.
 mkdir file-upload-multer  
 cd file-upload-multer  
 npm init  

Install the dependencies - STEP 2
 npm install express multer --save  
If you are reading this article, then I am assuming that you must be aware of what express is. If not, you must go and study it.
Here's a simple explanation of express
Express is a minimal and flexible Node.js web application framework that provides a robust set of features for web and mobile applications.

Create server.js in the directory - STEP 3
Travel to the directory in the command prompt and then type
 touch server.js  
Create the server using Express - STEP 4
If you know what express is. Understanding this code will be like a breeze for you.

Open the server.js in your favorite text editor and type the following code.
 var express = require(‘express’);  
 const app = express();  
 const port = 3000;  
 app.get(‘/’, (req, res) => {  
   res.send(‘hello people’);  
 });  
 app.listen(port, () => {  
   console.log(‘listening to the port: ‘ + port);  
 });  
You must be aware of the fact that testing is one of the essential steps during the development of any application. So Let's now proceed towards the testing of the code used till now.
In your terminal type
 node server.js  
Now open this URL http://localhost:3000 in your browser. 


If you can see an exactly similar message on your screen. Congratulations! You are halfway through.

Easy? Now let's go a step ahead and add multer to our project.

Add multer in server.js - STEP 5
 var multer = require('multer');  
 var upload = multer({dest:'uploads/'});  
Hey, what is this dest? Can you explain to me the second line?
These questions must be arousing in your mind. Let me answer these.

Here dest is the path where the file will be stored .i.e, the file which we will upload will be saved in uploads/ directory.

Now,  create a post route which will upload the file.
 app.post('/single', upload.single('profile'), (req, res) => {  
  try {  
   res.send(req.file);  
  }catch(err) {  
   res.send(400);  
  }  
 });  

Also, let me tell you that multer is capable of handling multiple uploads as well. Upload.single argument is used to upload a single file. As mentioned earlier, Multer adds a file object to the request. This file object contains metadata related to the file.

Its time for the testing again :)
I am using Postman for checking this route.




After the upload is complete, you will notice, an uploads folder is created in your main directory, and it contains the uploaded file. But wait, why it doesn't have any extension. How can we get the extension?.

Surprisingly Multer also got a solution for this ;)

If you want more controls over the uploads, you have to use the storage option instead of dest. Multer by default ships with storage engines DiskStorage and MemoryStorage.

Implementing DiskStorage Engines - STEP 6
 var storage = multer.diskStorage({  
   destination: function(req, file, cb) {  
     cb(null, './upload');  
    },  
   filename: function (req, file, cb) {  
     cb(null , file.originalname);  
   }  
 });  
What is the use of diskStorage?
DiskStorage engine gives full control of storing files to disk. In the code above, I created a storage object using diskStorage.
The options destination and filename determine where the file should be stored.

Destination
the destination is used to determine the folder in which the uploaded file should be stored. The callback function contains a string to name the location (For, e.g., ./upload)
If no destination is provided, the default directory will be used to storing the uploaded file.

Filename
the filename is used to give a name to the uploaded file. If no filename directions are provided, each file will be given a random name that doesn't include any file extension. Also, Multer will not append any file extension for you, your function should return a filename complete with a file extension.

To reflect the storage changes, you have to modify the upload variable as
 var upload = multer({ storage: storage })  

Congratulations on your first successful single file upload using Multer. ;)

Should I proceed one step further?
Of course, why not, now I'll teach you how you can upload multiple files.

Uploading Multiple Files - Additional STEP
 app.post('/bulk', upload.array('profiles', 4) , (req, res) =>{  
   try {  
     res.send(req.files);  
   } catch(error) {  
      console.log(error);  
       res.send(400);  
   }  
 });  

You would have already noticed that there's only a single change in the code. 
Yes, I just changed upload.single to upload.array. upload.array is used when you need to upload multiple files at once.

We are going to test the application for the one last time;)


Got similar results?
Pat on your Back, You successfully learned and implemented the multer to upload single and multiple files.

Conclusion
Time to look at what we learned. Multer is a Node.js Middleware for handling multipart/form-data, which is primarily used for uploading files. And by following these simple steps, you can implement multer in your next project. However, if you think this is an important one, consider bookmarking this.

Should I write an article that differentiates between multer and its equivalent dependencies?

Wednesday, June 24, 2020

HTTP Error 403:Forbidden Response - What it means and How to fix it?

Receiving error while surfing the Internet is hugely frustrating, and it thwarts our primary purpose. We are acclimated to those impressive 404 Not Found Error pages, Even to the extent that it becomes common to see those amazingly designed pages to entertain us whenever we get lost. 

Other then the Error 404, there's one more popular error and the most confusing one too, i.e., Error 403:Forbidden Response.

What does this mean?

In Simple Words: The Web server forbids you from accessing the page you are trying to open in your browser.

Why would the server do that to me? Can you explain it clearly

The 403:Forbidden error happens when the web page (or other resources) that you're trying to open in your web browser is a resource that you're not allowed to access. It's called a 403 error because that's the HTTP status code that the webserver uses to describe that kind of error. You usually get this error for one of two reasons. The first is that the owners of the webserver have correctly set up access permissions and that you're really not allowed access to the resource. The second reason is that the owners of the webserver have improperly set up permissions, and you're getting denied access when you really shouldn't be.

Similar to Some widespread errors like Error 404 and Error 502, the developers can decide how these error pages look. The popular error messages which you must have seen before includes

  • 403 Forbidden
  • HTTP 403
  • Forbidden
  • HTTP Error 403 – Forbidden
  • HTTP Error 403.14 – Forbidden
  • Error 403
  • Forbidden: You don’t have permission to access [directory] on this server
  • Error 403 – Forbidden

What's the solution to this?

As a user, you can't do much about it. Either there's some error from the server-side or you are not allowed access to the database.

But still, there's something you can try at your end. Let's have a look at them

Authenticate your self with a more appropriate account

Sometimes users of the websites are granted multiple authentications. If access to a particular webpage is restricted from some account consider trying login with other accounts as well.

This process sometimes requires you to clear the cookies or disable the extensions that might be interfering with the website which is eventually leading to restriction to access.

If other ids are not working as well chances are you are logging in at the wrong place.

Refreshing the page

Refreshing the webpage is sometimes worth a shot and can sometimes remove the error easily. It doesn’t fix the problem very often, but it takes just a second to try.

Clear your browser cookies and cache

It is possible that page with the error is cached in your browser and the page URL has been changed. When you clear the cache it enables the webpage to reload the webpage from the scratch. In some cases, it may take a few seconds due to the redownloading of the previously cached data. Clearing cookies means you’ll have to sign in again to most websites.

Contact the website

This step needs to be taken when you feel that there's some fault at the backend only. You can contact the Website owner directly by finding their contact details on their contact page or directly connect with them on social media.

Try again later

If none of the above solutions worked for you. You are left with no option other than waiting. You can visit the website at a later point in time. Since most of the time, 403 Errors are caused by issues with the website in question, it’s likely someone is already working on the problem.

Give up

Nothing worked? Maybe you just aren't supposed to be able to access that resource. It happens. It's a big internet and it's reasonable to expect that there are some areas off-limits to you personally.

Conclusion

Time to look at what we learned. Error 403:Forbidden Response occurs when the Web server forbids you from accessing the page you are trying to open in your browser. There's nothing much you can do, but there's something you can try at your end i.e Authenticate your self with a more appropriate account, Refreshing the page, Clear your browser cookies and cache, Contact the website, and Try again later. If nothing worked for you Maybe you just aren't supposed to be able to access that resource.

If you have any further questions, the comment section has been enabled;)
Thanks for reading

Thursday, June 18, 2020

Login UI Concept- Flutter

Its been 6 months since I got my hands dirty in Flutter and I absolutely love it. Creating UI on Flutter is very simple when you get used to it.

At first, you may get confused, but then it's as simple as switching from geared car to automatic car (This might clear your confusion)...

With the intro that's entirely out of the way, let's dive into what we are going to create today.

For the sake of understanding, let's divide the screen into two parts.

  1. The Upper section- Consisting of Image
  2. The Lower part- Consisting of Text Fields and Buttons
The upper and lower section of the login screen is placed inside the StackWidget.

Upper Section


Let's dig into some code and see how it created.
 Container(  
      decoration: BoxDecoration(  
        image: DecorationImage(  
          image: AssetImage('assets/image.jpg'),  
          fit: BoxFit.fitWidth,  
          alignment: Alignment.topCenter)),  
     )  
It consists of a Container Widget with a BoxDecoration widget in it as a decoration parameter. The BoxDecoration further has DecorationImage widget to show the Image.


The Lower Section

Let's look at the code here.

 Container(  
      width: MediaQuery.of(context).size.width,  
      margin: EdgeInsets.only(top: 270),  
      decoration: BoxDecoration(  
       borderRadius: BorderRadius.circular(20),  
       color: Colors.white,  
      ),  
      child: Padding(  
       padding: EdgeInsets.all(23),  
       child: ListView(  
        children: <Widget>[  
         Padding(  
          padding: EdgeInsets.fromLTRB(0, 20, 0, 20),  
          child: Container(  
           color: Color(0xfff5f5f5),  
           child: TextFormField(  
            style: GoogleFonts.robotoSlab(  
             textStyle: TextStyle(  
              color: Colors.black,  
             ),  
            ),  
 //  
            decoration: InputDecoration(  
              border: OutlineInputBorder(),  
              labelText: 'Username',  
              prefixIcon: Icon(Icons.person_outline),  
              labelStyle: TextStyle(fontSize: 15)),  
           ),  
          ),  
         ),  
         Container(  
          color: Color(0xfff5f5f5),  
          child: TextFormField(  
           obscureText: true,  
           style: GoogleFonts.robotoSlab(  
            textStyle: TextStyle(  
             color: Colors.black,  
            ),  
           ),  
           decoration: InputDecoration(  
             border: OutlineInputBorder(),  
             labelText: 'Password',  
             prefixIcon: Icon(Icons.lock_outline),  
             labelStyle: TextStyle(fontSize: 15)),  
          ),  
         ),  
         Padding(  
          padding: EdgeInsets.only(top: 20),  
          child: MaterialButton(  
           onPressed: () {},  
           //since this is only a UI app  
           child: Text(  
            'SIGN IN',  
            style: GoogleFonts.lato(  
             textStyle: TextStyle(  
              fontSize: 15,  
              color: Colors.white,  
              fontWeight: FontWeight.bold,  
             ),  
            ),  
           ),  
           color: Color(0xffff2d55),  
           elevation: 0,  
           minWidth: 400,  
           height: 50,  
           textColor: Colors.white,  
           shape: RoundedRectangleBorder(  
             borderRadius: BorderRadius.circular(10)),  
          ),  
         ),  
         Padding(  
          padding: EdgeInsets.only(top: 20),  
          child: Center(  
           child: Text(  
            'Forgot your password?',  
            style: GoogleFonts.robotoSlab(  
             textStyle: TextStyle(  
              fontSize: 15,  
              fontWeight: FontWeight.bold,  
              color: Colors.black,  
             ),  
            ),  
           ),  
          ),  
         ),  
         Padding(  
          padding: EdgeInsets.only(top: 30),  
          child: Center(  
           child: RichText(  
            text: TextSpan(children: [  
             TextSpan(  
              text: "Don't have an account?",  
              style: GoogleFonts.robotoSlab(  
               textStyle: TextStyle(  
                fontSize: 15,  
                fontWeight: FontWeight.bold,  
                color: Colors.black,  
               ),  
              ),  
             ),  
             TextSpan(  
              text: "sign up",  
              style: GoogleFonts.robotoSlab(  
               textStyle: TextStyle(  
                color: Color(0xffff2d55),  
                fontSize: 15,  
               ),  
              ),  
             )  
            ]),  
           ),  
          ),  
         )  
        ],  
       ),  
      ),  
     ),  


The lower section consists of a container with a decoration parameter in it to provide the round borders to the container, which in turn has a ListView widget in it. 

The List widget has the widgets arranged in a list with the order as follows.
  • TextView for showing "Sign" in text
  • TextFormField for taking username input
  • TextFormField for taking password input
  • MaterialButton for showing the "Sign In" button
  • TextView for showing the text "Forgot your password."
  • RichText for showing the text "Don't have an account? sign in"
For Text styling, I have used google fonts. You can have a look at it here.

The source code for the whole screen is as follows or you can visit my Github repo.

We have reached the end of this post, If you have any questions about any of the widgets use, ask me in the comment sections.