Вы находитесь на странице: 1из 17

Activity_mai.

xml

<?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"
android:orientation="vertical"
tools:context=".MainActivity">

<TextView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="Username"/>

<EditText
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:id="@+id/editTextUsername"
android:hint="Username"
android:text=""
/>
<TextView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="Password"/>

<EditText
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:id="@+id/editTextPassword"
android:text=""
android:hint="Password"
/>
<Button
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:id="@+id/buttonLogin"
android:text="Login"/>

<androidx.core.widget.ContentLoadingProgressBar
android:id="@+id/progressBar"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:max="100"
android:progress="1"
android:progressDrawable="@android:drawable/alert_dark_frame" />

<TextView
android:id="@+id/registro"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="Registrarse" />

</LinearLayout>

Activity_Register
<?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"
android:orientation="vertical"
tools:context=".Register">

<TextView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="REGISTRO DE USUARIO"
/>
<TextView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="Username"/>

<EditText
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:id="@+id/editTextUsernamer"
android:hint="Username"
android:text=""
/>
<TextView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="Password"/>

<EditText
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:id="@+id/editTextPasswordr"
android:text=""
android:hint="Password"
/>
<TextView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="Password Otra Vez"/>

<EditText
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:id="@+id/editTextPassword2r"
android:text=""
android:hint="Password"
/>
<Button
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:id="@+id/buttonRegister"
android:text="Login"/>

</LinearLayout>

Activity Navigation Drawer


<?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=".NavigationDrawerActivity">

</androidx.constraintlayout.widget.ConstraintLayout>
CLASE MainActivity (Activity)

package com.example.androidwebservices;

import androidx.appcompat.app.AppCompatActivity;

import android.content.Intent;
import android.os.AsyncTask;
import android.os.Bundle;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.widget.EditText;
import android.widget.ProgressBar;
import android.widget.Toast;

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

import java.util.HashMap;

public class MainActivity extends AppCompatActivity {


EditText editTextUsername, editTextPassword;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
editTextUsername = (EditText) findViewById(R.id.editTextUsername);
editTextPassword = (EditText) findViewById(R.id.editTextPassword);

//if user presses on login


//calling the method userLogin
findViewById(R.id.buttonLogin).setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {

userLogin();
}
});
findViewById(R.id.registro).setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
startActivity(new Intent(getApplicationContext(), Register.class));
}
});
/*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(), SignupActivity.class));
}
});

findViewById(R.id.textViewForgotPassword).setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
finish();
startActivity(new Intent(getApplicationContext(), ForgotPasswordActivity.class));
}
});

*/
}

private void userLogin() {


Log.d("newwwss", "Login Function Called");
//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

class UserLogin extends AsyncTask<Void, Void, String> {

ProgressBar progressBar;

@Override
protected void onPreExecute() {
Log.d("Mensaje 1: ", "Login Function Called PreExecute");
super.onPreExecute();
progressBar = (ProgressBar) findViewById(R.id.progressBar);
progressBar.setVisibility(View.VISIBLE);
}

@Override
protected void onPostExecute(String s) {

super.onPostExecute(s);
progressBar.setVisibility(View.GONE);

try {
//Toast.makeText(getApplicationContext(),s.toString(), Toast.LENGTH_SHORT).show();
Log.d("Notificando onPost", s);
//converting response to json object
JSONObject obj = new JSONObject(s);
Log.d("JsonObject", String.valueOf(obj));
//if no error in response
if (!obj.getBoolean("error")) {

Log.d("Error Display","Inside Loop");


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("phone")
);*/
User user = new User(
obj.getInt("id"),
obj.getString("username"),
obj.getString("email"),
obj.getString("phone")
);

//Storing the user in shared preferences


SharedPrefManager.getInstance(getApplicationContext()).userLogin(user);

//Starting the profile activity


//finish();
startActivity(new Intent(getApplicationContext(), NavigationDrawerActivity.class));
} else {
Toast.makeText(getApplicationContext(), "Datos de Usuario Incorrecto",
Toast.LENGTH_SHORT).show();
}
} catch (JSONException e) {
e.printStackTrace();
}
}

@Override
protected String doInBackground(Void... voids) {
//Creating request handler object
Log.d("newwwss", "INBackGround");
WebServiceURL URLs = new WebServiceURL();
RequestHandler requestHandler = new RequestHandler();

//Creating request parameters


HashMap<String, String> params = new HashMap<>();
params.put("username", username);
params.put("password", password);

//returning the Response of user login


Log.d("URL",URLs.URL_LOGIN);
Log.d("username",username);
Log.d("password",password);
Log.d("Return",requestHandler.sendPostRequest(URLs.URL_LOGIN, params).toString());
return requestHandler.sendPostRequest(URLs.URL_LOGIN, params);
}
}
UserLogin ul = new UserLogin();
ul.execute();
}
}

CLASE WebServiceURL

package com.example.androidwebservices;

public class WebServiceURL {


private static final String ROOT_URL ="http://192.168.2.22/ebsp/api.php?apicall=";

public static final String URL_REGISTER = ROOT_URL + "register";


public static final String URL_LOGIN = ROOT_URL + "login";
public static final String URL_PRODUCT = ROOT_URL + "product";
public static final String URL_UPDATEUSER = ROOT_URL + "update";
public static final String URL_FORGOTPASSWORD = ROOT_URL + "forgotPassword";
public static final String URL_RESETPASSWORD = ROOT_URL + "resetPassword";
public static final String URL_ORDERCONFIRM = ROOT_URL + "orderConfirm";
}

CLASE User

package com.example.androidwebservices;

public class User {


private String username, email, phone;
private int id;

public User(int id, String username, String email, String phone) {


this.id = id;
this.username = username;
this.email = email;
this.phone = phone;
}

public String getUsername() {


return username;
}

public String getEmail() {


return email;
}

public String getPhone() {


return phone;
}

public int getId() {


return id;
}
}

CLASE SharedPrefManager

package com.example.androidwebservices;

import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;

public class SharedPrefManager {


//the constants
private static final String SHARED_PREF_NAME = "exampleapp";
private static final String KEY_USERNAME = "keyusername";
private static final String KEY_EMAIL = "keyemail";
private static final String KEY_PHONE = "keyphone";
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_PHONE, user.getPhone());
editor.apply();
}

//this method will check whether the 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_PHONE, 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, MainActivity.class));
}
}
CLASE RequestHandler

package com.example.androidwebservices;

import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.io.UnsupportedEncodingException;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLEncoder;
import java.util.HashMap;
import java.util.Map;

import javax.net.ssl.HttpsURLConnection;

public class RequestHandler {


public String sendPostRequest(String requestURL, HashMap<String, String> postDataParams) {
URL url;

StringBuilder sb = new StringBuilder();


try {
url = new URL(requestURL);
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setReadTimeout(15000);
conn.setConnectTimeout(15000);
conn.setRequestMethod("POST");
conn.setDoInput(true);
conn.setDoOutput(true);

OutputStream os = conn.getOutputStream();

BufferedWriter writer = new BufferedWriter(


new OutputStreamWriter(os, "UTF-8"));
writer.write(getPostDataString(postDataParams));

writer.flush();
writer.close();
os.close();
int responseCode = conn.getResponseCode();

if (responseCode == HttpsURLConnection.HTTP_OK) {

BufferedReader br = new BufferedReader(new InputStreamReader(conn.getInputStream()));


sb = new StringBuilder();
String response;

while ((response = br.readLine()) != null) {


sb.append(response);
}
}

} catch (Exception e) {
e.printStackTrace();
}
return sb.toString();
}

//The following method will convert a key-value data pair into a query string as needed to send to the server.
private String getPostDataString(HashMap<String, String> params) throws UnsupportedEncodingException {
StringBuilder result = new StringBuilder();
boolean first = true;
for (Map.Entry<String, String> entry : params.entrySet()) {
if (first)
first = false;
else
result.append("&");

result.append(URLEncoder.encode(entry.getKey(), "UTF-8"));
result.append("=");
result.append(URLEncoder.encode(entry.getValue(), "UTF-8"));
}
return result.toString();
}
}

CLASE Register (ACtivity)

package com.example.androidwebservices;

import androidx.appcompat.app.AppCompatActivity;

import android.content.Intent;
import android.os.AsyncTask;
import android.os.Bundle;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.widget.EditText;
import android.widget.ProgressBar;
import android.widget.Toast;

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

import java.util.HashMap;

public class Register extends AppCompatActivity {


EditText editTextUsername, editTextPassword,editTextPassword2;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_register);
editTextUsername = (EditText) findViewById(R.id.editTextUsernamer);
editTextPassword = (EditText) findViewById(R.id.editTextPasswordr);
editTextPassword2 = (EditText) findViewById(R.id.editTextPassword2r);
findViewById(R.id.buttonRegister).setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
userRegister();
}
});

}
private void userRegister() {
Log.d("newwwss", "Login Function Called");
//First getting the values
final String username = editTextUsername.getText().toString();
final String password = editTextPassword.getText().toString();
final String password2 = editTextPassword2.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 (TextUtils.isEmpty(password2)) {
editTextPassword2.setError("Please enter your password");
editTextPassword2.requestFocus();

return;
}
if (!TextUtils.equals(password,password2)) {
editTextPassword2.setError("Password no son Iguales, intente otra vez");
editTextPassword.setText("");
editTextPassword2.setText("");
editTextPassword.requestFocus();
return;
}

//If everything is fine

class UserRegister extends AsyncTask<Void, Void, String> {

ProgressBar progressBar;

@Override
protected void onPreExecute() {
Log.d("Mensaje 1: ", "Login Function Called PreExecute");
super.onPreExecute();

@Override
protected void onPostExecute(String s) {

super.onPostExecute(s);

try {
//Toast.makeText(getApplicationContext(),s.toString(), Toast.LENGTH_SHORT).show();
Log.d("Notificando onPost", s);
//converting response to json object
JSONObject obj = new JSONObject(s);
Log.d("JsonObject", String.valueOf(obj));
//if no error in response
if (!obj.getBoolean("error")) {
Log.d("Error Display","Inside Loop");
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("phone")
);
User user = new User(
obj.getInt("id"),
obj.getString("username"),
obj.getString("email"),
obj.getString("phone")
);
*/
//Storing the user in shared preferences

//Starting the profile activity


//finish();
startActivity(new Intent(getApplicationContext(), MainActivity.class));
} else {
Toast.makeText(getApplicationContext(), "Datos de Usuario Incorrecto",
Toast.LENGTH_SHORT).show();
}
} catch (JSONException e) {
e.printStackTrace();
}
}

@Override
protected String doInBackground(Void... voids) {
//Creating request handler object
Log.d("newwwss", "INBackGround");
WebServiceURL URLs = new WebServiceURL();
RequestHandler requestHandler = new RequestHandler();

//Creating request parameters


HashMap<String, String> params = new HashMap<>();
params.put("username", username);
params.put("password", password);

//returning the Response of user login


Log.d("URL",URLs.URL_REGISTER);
Log.d("username",username);
Log.d("password",password);
//Log.d("Return",requestHandler.sendPostRequest(URLs.URL_REGISTER, params).toString());
return requestHandler.sendPostRequest(URLs.URL_REGISTER, params);
}
}
UserRegister ul = new UserRegister();
ul.execute();
}

}
CLASE NavigationDrawerActivity
package com.example.androidwebservices;

import androidx.appcompat.app.AppCompatActivity;

import android.os.Bundle;

public class NavigationDrawerActivity extends AppCompatActivity {

@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_navigation_drawer);
}
}
WEBSERVICE
Api.php

<?php
require_once 'config.php';
$response = array();

if(isset($_GET['apicall'])){
switch($_GET['apicall']){

case 'login':

$username = $_POST['username'];
$password = $_POST['password'];
$stmt = $con->prepare("SELECT id, username, email, phone FROM
users WHERE username = ? AND password = ?");
$stmt->bind_param("ss",$username, $password);
$stmt->execute();
$stmt->store_result();

if($stmt->num_rows > 0){

$stmt->bind_result($id, $username, $email, $phone);


$stmt->fetch();
$user = array(
'error'=>false,
'message'=>'Login Correcto de Usuario',
'id'=>$id,
'username'=>$username,
'email'=>$email,
'phone'=>$phone
);
//array_push($data, $user);
echo json_encode($user);
//$response['error'] = false;
//$response['message'] = 'Login successful';
//$response['user'] = $user;
//print_r ($user);
}else{
//$response['error'] = false;
//$response['message'] = 'Invalid username or password';
$user = array(
'error'=>true,
'message'=>'Login Incorrecto',
'id'=>'',
'username'=>'',
'email'=>'',
'phone'=>''
);
echo json_encode($user);
}
break;

case 'signup':

break;

case 'register':
$username = $_POST['username'];
$password = $_POST['password'];

//$username = $_GET['username'];
// $password = $_GET['password'];
$stmt = $con->prepare("SELECT id, username, email, phone FROM
users WHERE username = ? AND password = ?");
$stmt->bind_param("ss",$username, $password);
$stmt->execute();
$stmt->store_result();

if($stmt->num_rows <=0){
//$stmt->bind_result( $username);
//$stmt2 = $con->prepare("insert into users (username,
password) values ( ? , ?");
$q= "insert into users (username, password) values
( '$username' , '$password')";
//echo $q;
$stmt2 = $con->prepare($q);
//$stmt2->bind_param("ss",$username, $password);

$stmt2->execute();
$stmt2->store_result();

$stmt2->fetch();
$user = array(
'error'=>false,
'message'=>'Registro de Usuario Correcto',
'username'=>$username

);
//array_push($data, $user);
echo json_encode($user);
//$response['error'] = false;
//$response['message'] = 'Login successful';
//$response['user'] = $user;
//print_r ($user);
}else{
//$response['error'] = false;
//$response['message'] = 'Invalid username or password';
$user = array(
'error'=>true,
'message'=>'Registro Incorrecto.. Usuario Existe',
'id'=>'',
'username'=>'',
'email'=>'',
'phone'=>''
);
echo json_encode($user);
}
break;

break;
default:
$response['error'] = true;
$response['message'] = 'Invalid Operation Called';
}
}
else{
$response['error'] = true;
$response['message'] = 'Invalid API Call';
}

?>

config.php
<?php
$host = 'localhost';
$user = 'utp';
$pass = '12345';
$db = 'androidtest';

// Create connection
$con = mysqli_connect($host, $user, $pass, $db);

// Check connection
if (!$con) { die("Connection failed: " . mysqli_connect_error()); }
// Else{ echo "Connected"; }
?>

Вам также может понравиться