Hey folks, heres another Android Volley Tutorial. If you remember one of remember one of the previous tutorial which was about creating a Login and Registration system for Android. You can check the post from below.
In the above mentioned tutorial we learnt how to send http request to our web services to make login and registration system. In this post we will do exactly the same thing but with Volley Library. Using volley library will simplify our task, and it is fast and it manages everything so you don’t need to worry. So lets start this Android Volley Tutorial.
Table of Contents
Android Volley Tutorial – Video
- You can also follow this video tutorial series to learn the same.
Android Volley Tutorial – User Registration and Login
Creating Web Services
- So first we need the Web Services for User Registration and Login. We also need MySQL Database. Now you can use other technologies for your server side as well. It is obvious not mandatory to use PHP and MySQL only. But here I am using PHP and MySQL.
- And the best thing here is I will not be doing this thing in this post hahaha 😛 (LOL). Because in the last post which you can see from the below link, we already built web services for the User Registration and Login. And here I will be using the same thing. So go through the link given below first then move further in this post.
Learn Creating Web Services Here
Android Login and Registration
Creating a new Project
- As always we need a new Android Studio project. So create a project named SimplifiedCoding (You can actually name it whatever you want) with an EmptyActivity.
- Once your project is loaded create two more activities here named LoginActivity and ProfileActivity.
- Now lets design the screens first.
User Interface Design
Registration Screen
- So come inside activity_main.xml and write the following xml code.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 |
<?xml version="1.0" encoding="utf-8"?> <RelativeLayout 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="net.simplifiedlearning.simplifiedcoding.MainActivity"> <LinearLayout android:layout_width="match_parent" android:layout_height="wrap_content" android:layout_centerVertical="true" android:orientation="vertical" android:padding="10dp"> <EditText android:id="@+id/editTextUsername" android:layout_width="match_parent" android:layout_height="wrap_content" android:layout_marginBottom="8dp" android:layout_marginTop="8dp" android:hint="Username" android:inputType="text" /> <EditText android:id="@+id/editTextEmail" android:layout_width="match_parent" android:layout_height="wrap_content" android:layout_marginBottom="8dp" android:layout_marginTop="8dp" android:hint="Email" android:inputType="textEmailAddress" /> <EditText android:id="@+id/editTextPassword" android:layout_width="match_parent" android:layout_height="wrap_content" android:layout_marginBottom="8dp" android:layout_marginTop="8dp" android:fontFamily="sans-serif" android:hint="Password" android:inputType="textPassword" /> <RadioGroup android:id="@+id/radioGender" android:layout_width="match_parent" android:layout_height="wrap_content" android:layout_marginBottom="8dp" android:layout_marginTop="8dp" android:orientation="horizontal"> <RadioButton android:id="@+id/radioButtonMale" android:layout_width="wrap_content" android:layout_height="wrap_content" android:checked="true" android:text="Male" /> <RadioButton android:id="@+id/radioButtonFemale" android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="Female" /> </RadioGroup> <Button android:id="@+id/buttonRegister" android:layout_width="match_parent" android:layout_height="wrap_content" android:layout_marginBottom="8dp" android:layout_marginTop="8dp" android:text="Register" /> <TextView android:id="@+id/textViewLogin" android:layout_width="match_parent" android:layout_height="wrap_content" android:layout_marginBottom="8dp" android:layout_marginTop="8dp" android:text="Already Registered?\nLogin Here" android:textAlignment="center" android:textAppearance="@style/Base.TextAppearance.AppCompat.Medium" /> </LinearLayout> <ProgressBar android:visibility="gone" android:id="@+id/progressBar" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_centerHorizontal="true" android:layout_centerVertical="true" /> </RelativeLayout> |
- You will see the following design with the above given xml code.
Login Screen
- For the login screen come inside activity_login.xml and write the following xml code.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 |
<?xml version="1.0" encoding="utf-8"?> <RelativeLayout 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="net.simplifiedlearning.simplifiedcoding.LoginActivity"> <LinearLayout android:layout_width="match_parent" android:layout_height="wrap_content" android:layout_centerVertical="true" android:orientation="vertical" android:padding="10dp"> <EditText android:id="@+id/editTextUsername" android:layout_width="match_parent" android:layout_height="wrap_content" android:layout_marginBottom="8dp" android:layout_marginTop="8dp" android:hint="Username" android:inputType="text" /> <EditText android:id="@+id/editTextPassword" android:layout_width="match_parent" android:layout_height="wrap_content" android:layout_marginBottom="8dp" android:layout_marginTop="8dp" android:fontFamily="sans-serif" android:hint="Password" android:inputType="textPassword" /> <Button android:id="@+id/buttonLogin" android:layout_width="match_parent" android:layout_height="wrap_content" android:layout_marginBottom="8dp" android:layout_marginTop="8dp" android:text="Login" /> <TextView android:id="@+id/textViewRegister" android:layout_width="match_parent" android:layout_height="wrap_content" android:layout_marginBottom="8dp" android:layout_marginTop="8dp" android:text="Dont' have an account?\nRegister Here" android:textAlignment="center" android:textAppearance="@style/Base.TextAppearance.AppCompat.Medium" /> </LinearLayout> <ProgressBar android:visibility="gone" android:id="@+id/progressBar" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_centerHorizontal="true" android:layout_centerVertical="true" /> </RelativeLayout> |
- The above code will generate the output as shown below.
Profile Screen
- Lastly we will design the profile screen using the following xml code.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 |
<?xml version="1.0" encoding="utf-8"?> <RelativeLayout 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="net.simplifiedlearning.simplifiedcoding.ProfileActivity"> <LinearLayout android:layout_width="match_parent" android:layout_height="wrap_content" android:orientation="vertical"> <TableLayout android:layout_width="match_parent" android:layout_height="wrap_content"> <TableRow> <TextView android:layout_width="wrap_content" android:layout_height="wrap_content" android:padding="10dp" android:text="Id" android:textAppearance="@style/Base.TextAppearance.AppCompat.Large" /> <TextView android:id="@+id/textViewId" android:layout_width="wrap_content" android:layout_height="wrap_content" android:padding="10dp" android:text="1" android:textAppearance="@style/Base.TextAppearance.AppCompat.Large" /> </TableRow> <TableRow> <TextView android:layout_width="wrap_content" android:layout_height="wrap_content" android:padding="10dp" android:text="Username" android:textAppearance="@style/Base.TextAppearance.AppCompat.Large" /> <TextView android:id="@+id/textViewUsername" android:layout_width="wrap_content" android:layout_height="wrap_content" android:padding="10dp" android:text="probelalkhan" android:textAppearance="@style/Base.TextAppearance.AppCompat.Large" /> </TableRow> <TableRow> <TextView android:layout_width="wrap_content" android:layout_height="wrap_content" android:padding="10dp" android:text="Email" android:textAppearance="@style/Base.TextAppearance.AppCompat.Large" /> <TextView android:id="@+id/textViewEmail" android:layout_width="wrap_content" android:layout_height="wrap_content" android:padding="10dp" android:text="probelalkhan@gmail.com" android:textAppearance="@style/Base.TextAppearance.AppCompat.Large" /> </TableRow> <TableRow> <TextView android:layout_width="wrap_content" android:layout_height="wrap_content" android:padding="10dp" android:text="Gender" android:textAppearance="@style/Base.TextAppearance.AppCompat.Large" /> <TextView android:id="@+id/textViewGender" android:layout_width="wrap_content" android:layout_height="wrap_content" android:padding="10dp" android:text="Male" android:textAppearance="@style/Base.TextAppearance.AppCompat.Large" /> </TableRow> </TableLayout> <Button android:id="@+id/buttonLogout" android:layout_width="match_parent" android:layout_height="wrap_content" android:text="Logout" /> </LinearLayout> </RelativeLayout> |
- You will see the profile screen looking as shown below.
Creating Helper Classes
- It is very important that we organize our code well so that it can be reused. That is why here we are creating different classes for different task. Though we are doing exactly the same we did in the last post.
User Model Class
- First we will create a class for our User. So create a class named User.java and write the following code inside. The code contains nothing but only the user attributes with a constructor and getters. You can easily do this by right click -> generate -> constructor/ getters.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 |
package net.simplifiedlearning.simplifiedcoding; /** * Created by Belal on 9/5/2017. */ //this is very simple class and it only contains the user attributes, a constructor and the getters // you can easily do this by right click -> generate -> constructor and getters public class User { private int id; private String username, email, gender; public User(int id, String username, String email, String gender) { this.id = id; this.username = username; this.email = email; this.gender = gender; } public int getId() { return id; } public String getUsername() { return username; } public String getEmail() { return email; } public String getGender() { return gender; } } |
SharedPrefManager Class
- In android side to maintain a user login session, here we are using SharedPreferenes. Inside SharedPreferences we will store the data of currently logged in user. So that we can use it in our application. So to handle all the sharedpreferences task at one place we are having this class named SharedPrefmanager.java.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 |
package net.simplifiedlearning.simplifiedcoding; import android.content.Context; import android.content.Intent; import android.content.SharedPreferences; /** * Created by Belal on 9/5/2017. */ //here for this class we are using a singleton pattern public class SharedPrefManager { //the constants private static final String SHARED_PREF_NAME = "simplifiedcodingsharedpref"; private static final String KEY_USERNAME = "keyusername"; private static final String KEY_EMAIL = "keyemail"; private static final String KEY_GENDER = "keygender"; private static final String KEY_ID = "keyid"; private static SharedPrefManager mInstance; private static Context mCtx; private SharedPrefManager(Context context) { mCtx = context; } public static synchronized SharedPrefManager getInstance(Context context) { if (mInstance == null) { mInstance = new SharedPrefManager(context); } return mInstance; } //method to let the user login //this method will store the user data in shared preferences public void userLogin(User user) { SharedPreferences sharedPreferences = mCtx.getSharedPreferences(SHARED_PREF_NAME, Context.MODE_PRIVATE); SharedPreferences.Editor editor = sharedPreferences.edit(); editor.putInt(KEY_ID, user.getId()); editor.putString(KEY_USERNAME, user.getUsername()); editor.putString(KEY_EMAIL, user.getEmail()); editor.putString(KEY_GENDER, user.getGender()); editor.apply(); } //this method will checker whether user is already logged in or not public boolean isLoggedIn() { SharedPreferences sharedPreferences = mCtx.getSharedPreferences(SHARED_PREF_NAME, Context.MODE_PRIVATE); return sharedPreferences.getString(KEY_USERNAME, null) != null; } //this method will give the logged in user public User getUser() { SharedPreferences sharedPreferences = mCtx.getSharedPreferences(SHARED_PREF_NAME, Context.MODE_PRIVATE); return new User( sharedPreferences.getInt(KEY_ID, -1), sharedPreferences.getString(KEY_USERNAME, null), sharedPreferences.getString(KEY_EMAIL, null), sharedPreferences.getString(KEY_GENDER, null) ); } //this method will logout the user public void logout() { SharedPreferences sharedPreferences = mCtx.getSharedPreferences(SHARED_PREF_NAME, Context.MODE_PRIVATE); SharedPreferences.Editor editor = sharedPreferences.edit(); editor.clear(); editor.apply(); mCtx.startActivity(new Intent(mCtx, LoginActivity.class)); } } |
Web Service URLs
- Create a new class named URLs.java to put all the Web Service URLs at one place. So here I am using a class named URLs.java.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 |
package net.simplifiedlearning.simplifiedcoding; /** * Created by Belal on 9/5/2017. */ public class URLs { private static final String ROOT_URL = "http://192.168.101.1/Android/Api.php?apicall="; public static final String URL_REGISTER = ROOT_URL + "signup"; public static final String URL_LOGIN= ROOT_URL + "login"; } |
- Now we have all the helper classes.
Adding Volley Library
- As in this project we need to use Volley for the network operation, and for this we need to add Volley to this project.
- For this come inside app level build.gradle file and inside dependencies block add volley.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 |
dependencies { compile fileTree(dir: 'libs', include: ['*.jar']) androidTestCompile('com.android.support.test.espresso:espresso-core:2.2.2', { exclude group: 'com.android.support', module: 'support-annotations' }) //adding volley with this line compile 'com.android.volley:volley:1.0.0' compile 'com.android.support:appcompat-v7:26.+' compile 'com.android.support.constraint:constraint-layout:1.0.2' testCompile 'junit:junit:4.12' } |
- After adding this you need to sync your project.
Adding Internet Permission
- As networking operations requires internet permission so inside AndroidManifest.xml define the internet permission for the application.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 |
<?xml version="1.0" encoding="utf-8"?> <manifest xmlns:android="http://schemas.android.com/apk/res/android" package="net.simplifiedlearning.simplifiedcoding"> <!-- adding internet permission --> <uses-permission android:name="android.permission.INTERNET" /> <application android:allowBackup="true" android:icon="@mipmap/ic_launcher" android:label="@string/app_name" android:roundIcon="@mipmap/ic_launcher_round" android:supportsRtl="true" android:theme="@style/AppTheme"> <activity android:name=".MainActivity"> <intent-filter> <action android:name="android.intent.action.MAIN" /> <category android:name="android.intent.category.LAUNCHER" /> </intent-filter> </activity> <activity android:name=".LoginActivity" /> <activity android:name=".ProfileActivity"></activity> </application> </manifest> |
Using Singleton Pattern for Volley
- As any app requires many network operations. So in this case it is always a good idea to use a single instance of Volley RequestQueue. For this we will use a Singleton Pattern for handling all the request queues.
- So create a new class named VolleySingleton.java and write the following code.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 |
package net.simplifiedlearning.simplifiedcoding; import android.content.Context; import com.android.volley.Request; import com.android.volley.RequestQueue; import com.android.volley.toolbox.Volley; /** * Created by Belal on 9/5/2017. */ public class VolleySingleton { private static VolleySingleton mInstance; private RequestQueue mRequestQueue; private static Context mCtx; private VolleySingleton(Context context) { mCtx = context; mRequestQueue = getRequestQueue(); } public static synchronized VolleySingleton getInstance(Context context) { if (mInstance == null) { mInstance = new VolleySingleton(context); } return mInstance; } public RequestQueue getRequestQueue() { if (mRequestQueue == null) { // getApplicationContext() is key, it keeps you from leaking the // Activity or BroadcastReceiver if someone passes one in. mRequestQueue = Volley.newRequestQueue(mCtx.getApplicationContext()); } return mRequestQueue; } public <T> void addToRequestQueue(Request<T> req) { getRequestQueue().add(req); } } |
User Registration
- Now lets perform the user registration inside MainActivity.java. The code is very simple and it is actually explaining itself. But if you think you have some confusions at some lines, feel free to comment and I will try to help you.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 |
package net.simplifiedlearning.simplifiedcoding; import android.content.Intent; import android.os.Bundle; import android.support.v7.app.AppCompatActivity; import android.text.TextUtils; import android.view.View; import android.widget.EditText; import android.widget.ProgressBar; import android.widget.RadioButton; import android.widget.RadioGroup; import android.widget.Toast; import com.android.volley.AuthFailureError; import com.android.volley.Request; import com.android.volley.Response; import com.android.volley.VolleyError; import com.android.volley.toolbox.StringRequest; import org.json.JSONException; import org.json.JSONObject; import java.util.HashMap; import java.util.Map; public class MainActivity extends AppCompatActivity { EditText editTextUsername, editTextEmail, editTextPassword; RadioGroup radioGroupGender; ProgressBar progressBar; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); progressBar = (ProgressBar) findViewById(R.id.progressBar); //if the user is already logged in we will directly start the profile activity if (SharedPrefManager.getInstance(this).isLoggedIn()) { finish(); startActivity(new Intent(this, ProfileActivity.class)); return; } editTextUsername = (EditText) findViewById(R.id.editTextUsername); editTextEmail = (EditText) findViewById(R.id.editTextEmail); editTextPassword = (EditText) findViewById(R.id.editTextPassword); radioGroupGender = (RadioGroup) findViewById(R.id.radioGender); findViewById(R.id.buttonRegister).setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { //if user pressed on button register //here we will register the user to server registerUser(); } }); findViewById(R.id.textViewLogin).setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { //if user pressed on login //we will open the login screen finish(); startActivity(new Intent(MainActivity.this, LoginActivity.class)); } }); } private void registerUser() { final String username = editTextUsername.getText().toString().trim(); final String email = editTextEmail.getText().toString().trim(); final String password = editTextPassword.getText().toString().trim(); final String gender = ((RadioButton) findViewById(radioGroupGender.getCheckedRadioButtonId())).getText().toString(); //first we will do the validations if (TextUtils.isEmpty(username)) { editTextUsername.setError("Please enter username"); editTextUsername.requestFocus(); return; } if (TextUtils.isEmpty(email)) { editTextEmail.setError("Please enter your email"); editTextEmail.requestFocus(); return; } if (!android.util.Patterns.EMAIL_ADDRESS.matcher(email).matches()) { editTextEmail.setError("Enter a valid email"); editTextEmail.requestFocus(); return; } if (TextUtils.isEmpty(password)) { editTextPassword.setError("Enter a password"); editTextPassword.requestFocus(); return; } StringRequest stringRequest = new StringRequest(Request.Method.POST, URLs.URL_REGISTER, new Response.Listener<String>() { @Override public void onResponse(String response) { progressBar.setVisibility(View.GONE); try { //converting response to json object JSONObject obj = new JSONObject(response); //if no error in response if (!obj.getBoolean("error")) { Toast.makeText(getApplicationContext(), obj.getString("message"), Toast.LENGTH_SHORT).show(); //getting the user from the response JSONObject userJson = obj.getJSONObject("user"); //creating a new user object User user = new User( userJson.getInt("id"), userJson.getString("username"), userJson.getString("email"), userJson.getString("gender") ); //storing the user in shared preferences SharedPrefManager.getInstance(getApplicationContext()).userLogin(user); //starting the profile activity finish(); startActivity(new Intent(getApplicationContext(), ProfileActivity.class)); } else { Toast.makeText(getApplicationContext(), obj.getString("message"), Toast.LENGTH_SHORT).show(); } } catch (JSONException e) { e.printStackTrace(); } } }, new Response.ErrorListener() { @Override public void onErrorResponse(VolleyError error) { Toast.makeText(getApplicationContext(), error.getMessage(), Toast.LENGTH_SHORT).show(); } }) { @Override protected Map<String, String> getParams() throws AuthFailureError { Map<String, String> params = new HashMap<>(); params.put("username", username); params.put("email", email); params.put("password", password); params.put("gender", gender); return params; } }; VolleySingleton.getInstance(this).addToRequestQueue(stringRequest); } } |
- If you are facing some problem understanding the codes, you can check the video tutorials given at the starting of this post.
User Profile
- Come inside ProfileActivity.java and write the following code. Here we are only displaying the User data and we have a button that will let the user logout from the app.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 |
package net.simplifiedlearning.simplifiedcoding; import android.content.Intent; import android.support.v7.app.AppCompatActivity; import android.os.Bundle; import android.view.View; import android.widget.TextView; public class ProfileActivity extends AppCompatActivity { TextView textViewId, textViewUsername, textViewEmail, textViewGender; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_profile); //if the user is not logged in //starting the login activity if (!SharedPrefManager.getInstance(this).isLoggedIn()) { finish(); startActivity(new Intent(this, LoginActivity.class)); } textViewId = (TextView) findViewById(R.id.textViewId); textViewUsername = (TextView) findViewById(R.id.textViewUsername); textViewEmail = (TextView) findViewById(R.id.textViewEmail); textViewGender = (TextView) findViewById(R.id.textViewGender); //getting the current user User user = SharedPrefManager.getInstance(this).getUser(); //setting the values to the textviews textViewId.setText(String.valueOf(user.getId())); textViewUsername.setText(user.getUsername()); textViewEmail.setText(user.getEmail()); textViewGender.setText(user.getGender()); //when the user presses logout button //calling the logout method findViewById(R.id.buttonLogout).setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { finish(); SharedPrefManager.getInstance(getApplicationContext()).logout(); } }); } } |
- Now lastly we will code the LoginActivity.
User Login
- Come inside LoginActivity.java and write the following code. It is almost same as the User Registration Activity (MainActivity.java).
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 |
package net.simplifiedlearning.simplifiedcoding; import android.content.Intent; import android.os.AsyncTask; import android.support.v7.app.AppCompatActivity; import android.os.Bundle; import android.text.TextUtils; import android.view.View; import android.widget.EditText; import android.widget.ProgressBar; import android.widget.Toast; import com.android.volley.AuthFailureError; import com.android.volley.Request; import com.android.volley.Response; import com.android.volley.VolleyError; import com.android.volley.toolbox.StringRequest; import org.json.JSONException; import org.json.JSONObject; import java.util.HashMap; import java.util.Map; public class LoginActivity extends AppCompatActivity { EditText editTextUsername, editTextPassword; ProgressBar progressBar; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_login); if (SharedPrefManager.getInstance(this).isLoggedIn()) { finish(); startActivity(new Intent(this, ProfileActivity.class)); } progressBar = (ProgressBar) findViewById(R.id.progressBar); editTextUsername = (EditText) findViewById(R.id.editTextUsername); editTextPassword = (EditText) findViewById(R.id.editTextPassword); //if user presses on login //calling the method login findViewById(R.id.buttonLogin).setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { userLogin(); } }); //if user presses on not registered findViewById(R.id.textViewRegister).setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { //open register screen finish(); startActivity(new Intent(getApplicationContext(), MainActivity.class)); } }); } private void userLogin() { //first getting the values final String username = editTextUsername.getText().toString(); final String password = editTextPassword.getText().toString(); //validating inputs if (TextUtils.isEmpty(username)) { editTextUsername.setError("Please enter your username"); editTextUsername.requestFocus(); return; } if (TextUtils.isEmpty(password)) { editTextPassword.setError("Please enter your password"); editTextPassword.requestFocus(); return; } //if everything is fine StringRequest stringRequest = new StringRequest(Request.Method.POST, URLs.URL_LOGIN, new Response.Listener<String>() { @Override public void onResponse(String response) { progressBar.setVisibility(View.GONE); try { //converting response to json object JSONObject obj = new JSONObject(response); //if no error in response if (!obj.getBoolean("error")) { Toast.makeText(getApplicationContext(), obj.getString("message"), Toast.LENGTH_SHORT).show(); //getting the user from the response JSONObject userJson = obj.getJSONObject("user"); //creating a new user object User user = new User( userJson.getInt("id"), userJson.getString("username"), userJson.getString("email"), userJson.getString("gender") ); //storing the user in shared preferences SharedPrefManager.getInstance(getApplicationContext()).userLogin(user); //starting the profile activity finish(); startActivity(new Intent(getApplicationContext(), ProfileActivity.class)); } else { Toast.makeText(getApplicationContext(), obj.getString("message"), Toast.LENGTH_SHORT).show(); } } catch (JSONException e) { e.printStackTrace(); } } }, new Response.ErrorListener() { @Override public void onErrorResponse(VolleyError error) { Toast.makeText(getApplicationContext(), error.getMessage(), Toast.LENGTH_SHORT).show(); } }) { @Override protected Map<String, String> getParams() throws AuthFailureError { Map<String, String> params = new HashMap<>(); params.put("username", username); params.put("password", password); return params; } }; VolleySingleton.getInstance(this).addToRequestQueue(stringRequest); } } |
- Now you can test the application.
- Bingo! It is working absolutely fine.
Source Code Download
- If you are having some troubles creating the project then don’t worry I am giving you the complete source code here. You can download it from below.
[sociallocker id=1372] Android Volley Tutorial – User Registration and Login Source Code [/sociallocker]
So thats all for this Android Volley Tutorial friends. If you found this helpful then please SHARE it. If having any feedbacks, suggestions or queries, please comment it.