Suppose you were asked to add a login activity to the Application.
How do you make Login as the First Activity instead of Main Activity as the First Activity(Page)?
Let's get started.
PHP Server Side
Step 1: Create a table name as users3
CREATE TABLE `users3` ( `username` varchar(23) NOT NULL, `password` varchar(80) NOT NULL, PRIMARY KEY (`username`) )
INSERT INTO `users3` (`username`, `password`) VALUES ('user1', 'u1234');
Step 2: Create a php page name as LoginJ.php
<?php //php // Get raw data from request $json = file_get_contents('php://input'); // Convert json to php object $json_object = json_decode($json, true); // Get pid value from json object $username = $json_object['username']; //htmlspecialchars to be added $password = $json_object['password']; //htmlspecialchars to be added // array for JSON response $response = array(); // include db connect class require_once __DIR__ . '/db_connect.php'; // connecting to db $myConnection= new DB_CONNECT(); $myConnection->connect(); // mysql inserting a new row $sqlCommand="select password from users3 where username= '$username'"; // echo $sqlCommand; $result =mysqli_query($myConnection->myconn, "$sqlCommand"); // check for empty result if (mysqli_num_rows($result) > 0) { $result = mysqli_fetch_array($result); if($password ==$result["password"] ) { $response["success"] = 1; $response["message"] = "Login Successful"; } else { $response["success"] = 0; $response["message"] = "Login Failed"; } } else { // no product found $response["success"] = 0; $response["message"] = "Login Failed"; // echo no users JSON } echo json_encode($response); ?>
Android Client Side
Step 1: Create a new Empty Activity name as Login
activity_login.xml
<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:gravity="center_horizontal" android:orientation="vertical" tools:context=".LoginActivity"> <EditText android:id="@+id/username" android:layout_width="match_parent" android:layout_height="wrap_content" android:hint="@string/prompt_username" android:inputType="text" android:maxLines="1" android:singleLine="true" /> <EditText android:id="@+id/password" android:layout_width="match_parent" android:layout_height="wrap_content" android:hint="@string/prompt_password" android:imeActionId="6" android:imeActionLabel="@string/action_sign_in_short" android:imeOptions="actionUnspecified" android:inputType="textPassword" android:maxLines="1" android:singleLine="true" /> <Button android:id="@+id/btnSignIn" style="?android:textAppearanceSmall" android:layout_width="match_parent" android:layout_height="wrap_content" android:layout_marginTop="16dp" android:text="@string/action_sign_in" android:textStyle="bold" /> </LinearLayout>
Step 2: Modify strings.xml as shown below:
<!-- Strings related to login --> <string name="prompt_username">Username</string> <string name="prompt_password">Password</string> <string name="action_sign_in">Sign in</string> <string name="action_sign_in_short">Sign in</string> <string name="error_invalid_email">This email address is invalid</string> <string name="error_invalid_password">This password is too short</string> <string name="error_incorrect_password">This password is incorrect</string> <string name="error_field_required">This field is required</string> <string name="permission_rationale">"Contacts permissions are needed for providing email completions." </string>
Step 3: Modify LoginActivity.java. Copy and Paste the code below:
package networkclient.mdad.sql_databaseexample; import android.content.Intent; import android.support.v7.app.AppCompatActivity; import android.os.Bundle; import android.util.Log; import android.view.View; import android.widget.Button; import android.widget.EditText; import android.widget.Toast; import com.android.volley.Request; import com.android.volley.RequestQueue; import com.android.volley.Response; import com.android.volley.VolleyError; import com.android.volley.toolbox.JsonObjectRequest; import com.android.volley.toolbox.Volley; import org.json.JSONException; import org.json.JSONObject; /** * A login screen that offers login via email/password. */ public class LoginActivity extends AppCompatActivity { private EditText mPassword,mUserName; private Button btnSignIn; // url to update product private static final String url_login = MainActivity.ipBaseAddress+"/loginJ.php"; // JSON Node names private static final String TAG_SUCCESS = "success"; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_login); mPassword = (EditText) findViewById(R.id.password); mUserName = (EditText) findViewById(R.id.username); btnSignIn = (Button) findViewById(R.id.btnSignIn); // view products click event btnSignIn.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { String pw= mPassword.getText().toString(); String uName= mUserName.getText().toString(); if(pw.isEmpty()) { mPassword.setError(getString(R.string.error_field_required)); }else if(uName.isEmpty()) { mUserName.setError(getString(R.string.error_field_required)); }else { JSONObject dataJson = new JSONObject(); try{ dataJson.put("username", uName); dataJson.put("password", pw); }catch(JSONException e){ } postData(url_login,dataJson,1 ); } } }); } public void postData(String url, final JSONObject json, final int option){ RequestQueue requestQueue = Volley.newRequestQueue(this); JsonObjectRequest json_obj_req = new JsonObjectRequest( Request.Method.POST, url, json, new Response.Listener<JSONObject>() { @Override public void onResponse(JSONObject response) { switch (option){ case 1:checkResponseLogin(response); break; } } }, new Response.ErrorListener() { @Override public void onErrorResponse(VolleyError error) { error.printStackTrace(); // String alert_message; // alert_message = error.toString(); // showAlertDialogue("Error", alert_message); } }); requestQueue.add(json_obj_req); } public void checkResponseLogin(JSONObject response) { Log.i("----Response", response+" "+url_login); try { if(response.getInt(TAG_SUCCESS)==1){ finish(); Intent i = new Intent(this, MainActivity.class); startActivity(i); }else{ Toast.makeText(this, "Wrong Password", Toast.LENGTH_SHORT).show(); } } catch (JSONException e) { e.printStackTrace(); } } }
Step 4: Try running your App now. You will find that Login is NOT the First acitivity(Page).
Step 5: How to set Login Activity as the First Activity (Page) to Launch?
Modify AndroidManifest.xml as shown below
We make LoginActivity as the MAIN , LAUNCHER
<activity android:name=".LoginActivity"> <intent-filter> <action android:name="android.intent.action.MAIN" /> <category android:name="android.intent.category.LAUNCHER" /> </intent-filter> </activity>
No comments:
Post a Comment
Note: only a member of this blog may post a comment.