我无法在Google表格中查找数据。我已经创建了一个UI登录页面,还将新用户创建到Google表格中。如果工作表中已经有这样的用户,我该如何认证?我可以成功地将用户添加到Google表格中,但是我不确定如何检索它并检查是否已经注册了此类用户。希望能引起一些专家分享如何做
下面是Java代码...
package com.example.testing;
import android.app.ProgressDialog;
import android.content.Intent;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ListAdapter;
import android.widget.SimpleAdapter;
import android.widget.TextView;
import android.widget.Toast;
import com.android.volley.AuthFailureError;
import com.android.volley.DefaultRetryPolicy;
import com.android.volley.Request;
import com.android.volley.RequestQueue;
import com.android.volley.Response;
import com.android.volley.RetryPolicy;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.StringRequest;
import com.android.volley.toolbox.Volley;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.Map;
import java.util.Objects;
import butterknife.BindView;
import butterknife.ButterKnife;
public class LoginActivity extends AppCompatActivity {
private static final String TAG = "LoginActivity";
private static final int REQUEST_SIGNUP = 0;
@BindView(R.id.input_email)
EditText _emailText;
@BindView(R.id.input_password)
EditText _passwordText;
@BindView(R.id.btn_login)
Button _loginButton;
@BindView(R.id.link_signup)
TextView _signupLink;
ProgressDialog loading;
ListAdapter adapter;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_login);
ButterKnife.bind(this);
_loginButton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
login();
}
});
_signupLink.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
// Start the Signup activity
Intent intent = new Intent(getApplicationContext(), SignupActivity.class);
startActivityForResult(intent, REQUEST_SIGNUP);
finish();
overridePendingTransition(R.anim.push_left_in, R.anim.push_left_out);
}
});
}
public void login() {
Log.d(TAG, "Login");
if (!validate()) {
onLoginFailed();
return;
}
_loginButton.setEnabled(false);
final ProgressDialog progressDialog = new ProgressDialog(LoginActivity.this,
R.style.AppTheme);
progressDialog.setIndeterminate(true);
//progressDialog.setMessage("Authenticating...");
progressDialog.show();
final String email = _emailText.getText().toString();
final String password = _passwordText.getText().toString();
// TODO: Implement your own authentication logic here.
StringRequest stringRequest = new StringRequest(Request.Method.POST, "https://script.google.com/macros/s/AKfycbzOQBgFNvo9u70kJvsaXj_PmU8_orHdTyEx1AgzH7rzXW0x6Y0S/exec",
new Response.Listener<String>() {
@Override
public void onResponse(String response) {
//you will get your response in log
Log.e("response", response);
try {
JSONArray array = new JSONArray(response);
for (int i = 0; i < array.length(); i++) {
JSONArray array1 = array.getJSONObject(i).getJSONArray("items");
for (int j = 0; j < array1.length(); j++) {
Intent intent = new Intent(getApplicationContext(),LoginActivity.class);
startActivity(intent);
}
}
} catch (JSONException e) {
e.printStackTrace();
}
}
},
new Response.ErrorListener() {
@Override
public void onErrorResponse(VolleyError error) {
Toast.makeText(getApplicationContext(), "Email or password is empty", Toast.LENGTH_LONG).show();
// Toast.makeText(getApplicationContext(), "Invalid username or password", Toast.LENGTH_SHORT).show();
Log.e("Error", "msg==>" + error);
}
}) {
protected Map<String, String> getParams() throws AuthFailureError {
Map<String, String> reqMap = new LinkedHashMap<>();
reqMap.put("email", email);
reqMap.put("password", password);
reqMap.put("action","addItem");
Log.e("request","addItem" + reqMap);
return reqMap;
}
};
stringRequest.setRetryPolicy(new DefaultRetryPolicy(DefaultRetryPolicy.DEFAULT_TIMEOUT_MS * 30, DefaultRetryPolicy.DEFAULT_MAX_RETRIES, DefaultRetryPolicy.DEFAULT_BACKOFF_MULT));
RequestQueue queue = Volley.newRequestQueue(this);
queue.add(stringRequest);
new android.os.Handler().postDelayed(
new Runnable() {
public void run() {
// On complete call either onLoginSuccess or onLoginFailed
onLoginSuccess();
Intent intent = new Intent(getApplicationContext(),MainActivity.class);
startActivity(intent);
// onLoginFailed();
progressDialog.dismiss();
}
}, 3000);
}
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if (requestCode == REQUEST_SIGNUP) {
if (resultCode == RESULT_OK) {
// TODO: Implement successful signup logic here
// By default we just finish the Activity and log them in automatically
this.finish();
}
}
}
@Override
public void onBackPressed() {
// Disable going back to the MainActivity
moveTaskToBack(true);
}
public void onLoginSuccess() {
_loginButton.setEnabled(true);
finish();
}
public void onLoginFailed() {
Toast.makeText(getBaseContext(), "Login failed", Toast.LENGTH_LONG).show();
_loginButton.setEnabled(true);
}
public boolean validate() {
boolean valid = true;
String email = _emailText.getText().toString();
String password = _passwordText.getText().toString();
if (email.isEmpty() || !android.util.Patterns.EMAIL_ADDRESS.matcher(email).matches()) {
_emailText.setError("enter a valid email address");
valid = false;
} else {
_emailText.setError(null);
}
if (password.isEmpty() || password.length() < 4 || password.length() > 10) {
_passwordText.setError("between 6 and 10 alphanumeric characters");
valid = false;
} else {
_passwordText.setError(null);
}
//if(Objects.equals(_emailText.getText().toString(), "testing@gmail.com")&&Objects.equals(_passwordText.getText().toString(),"admin"))
//{
// Toast.makeText(LoginActivity.this,"You have Authenticated Successfully",Toast.LENGTH_LONG).show();
//}else
//{
// Toast.makeText(LoginActivity.this,"Authentication Failed",Toast.LENGTH_LONG).show();
//}
return valid;
}
}
这是Google App脚本:
var ss = SpreadsheetApp.openByUrl("https://docs.google.com/spreadsheets/d/1zJJ8aMgq-arBn_rabsT8zAB0hynIiQwx_4f57ifnpT8/edit#gid=0");
var sheet = ss.getSheetByName('New_Users');
function doPost(e){
var action = e.parameter.action;
if(action == 'addItem'){
return addItem(e);
}
}
function doGet(e){
var action = e.parameter.action;
if(action == 'getItems'){
return getItems(e);
}
}
function addItem(e){
var date = new Date();
var id = "User "+sheet.getLastRow(); // User1
var itemName = e.parameter.itemName;
var address = e.parameter.address;
var email = e.parameter.email;
var mobile = e.parameter.mobile;
var password = e.parameter.password;
var reEnterPassword = e.parameter.reEnterPassword;
sheet.appendRow ([date,id,itemName,address,email,mobile,password,reEnterPassword]);
return ContentService.createTextOutput("Success").setMimeType (ContentService.MimeType.TEXT);
}
function getItems(e){
var records={};
var rows = sheet.getRange(2, 1, sheet.getLastRow() - 1,sheet.getLastColumn()).getValues();
data = [];
for (var r = 0, l = rows.length; r < l; r++) {
var row = rows[r],
record = {};
record['itemName'] = row[2];
record['address']=row[3];
record['email']=row[4];
record['mobile']=row[5];
record['password']=row[6];
record['reEnterPassword']=row[7];
data.push(record);
}
records.items = data;
var result=JSON.stringify(records);
return ContentService.createTextOutput(result).setMimeType (ContentService.MimeType.JSON);
}
这是XML代码:
<?xml version="1.0" encoding="utf-8"?>
<ScrollView xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:background="@drawable/globe"
android:clipToPadding="false"
android:fillViewport="false"
android:fitsSystemWindows="true">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
android:paddingLeft="24dp"
android:paddingTop="56dp"
android:paddingRight="24dp">
<ImageView
android:layout_width="wrap_content"
android:layout_height="115dp"
android:layout_gravity="center_horizontal"
android:layout_marginBottom="24dp"
android:src="@drawable/tdc" />
<!-- Email Label -->
<android.support.design.widget.TextInputLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginTop="8dp"
android:layout_marginBottom="8dp"
android:background="@color/grey_50">
<EditText
android:id="@+id/input_email"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:drawableLeft="@drawable/ic_action_email"
android:hint="Email"
android:inputType="textEmailAddress" />
</android.support.design.widget.TextInputLayout>
<!-- Password Label -->
<android.support.design.widget.TextInputLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginTop="8dp"
android:layout_marginBottom="8dp"
android:background="@color/grey_50">
<EditText
android:id="@+id/input_password"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:drawableLeft="@drawable/ic_action_pass"
android:hint="Password"
android:inputType="textPassword" />
</android.support.design.widget.TextInputLayout>
<android.support.v7.widget.AppCompatButton
android:id="@+id/btn_login"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:layout_marginTop="24dp"
android:layout_marginBottom="24dp"
android:padding="12dp"
android:text="Login" />
<TextView
android:id="@+id/link_signup"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_marginBottom="24dp"
android:gravity="center"
android:text="No account yet? Create one"
android:textSize="16dip" />
</LinearLayout>
</ScrollView>