Webservices Android
Webservices Android
xml
<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>
</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;
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));
}
});
*/
}
//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;
}
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")) {
@Override
protected String doInBackground(Void... voids) {
//Creating request handler object
Log.d("newwwss", "INBackGround");
WebServiceURL URLs = new WebServiceURL();
RequestHandler requestHandler = new RequestHandler();
CLASE WebServiceURL
package com.example.androidwebservices;
CLASE User
package com.example.androidwebservices;
CLASE SharedPrefManager
package com.example.androidwebservices;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
//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;
}
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;
OutputStream os = conn.getOutputStream();
writer.flush();
writer.close();
os.close();
int responseCode = conn.getResponseCode();
if (responseCode == HttpsURLConnection.HTTP_OK) {
} 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();
}
}
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;
}
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;
}
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();
@Override
protected String doInBackground(Void... voids) {
//Creating request handler object
Log.d("newwwss", "INBackGround");
WebServiceURL URLs = new WebServiceURL();
RequestHandler requestHandler = new RequestHandler();
}
CLASE NavigationDrawerActivity
package com.example.androidwebservices;
import androidx.appcompat.app.AppCompatActivity;
import android.os.Bundle;
@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();
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"; }
?>