我使用此页面中的代码,只需更改一些变量以及if else条件。但是,我没有改变JSONParser。 How to implement Login with HttpURLConnection and PHP server in Android
//these are the codes i use
import android.app.Activity;
import android.app.ProgressDialog;
import android.content.Intent;
import android.os.AsyncTask;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;
import org.json.JSONException;
import org.json.JSONObject;
import java.util.HashMap;
public class Startup_Activity extends Activity {
EditText patid1, patpw1;
Button patli1;
TextView patfp1;
String patientID, patientPass;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_startup_);
patid1 = (EditText) findViewById(R.id.pat_id);
patpw1 = (EditText) findViewById(R.id.pat_pw);
patli1 = (Button) findViewById(R.id.pat_li);
patfp1 = (TextView) findViewById(R.id.pat_fp);
}
public void login(View x) {
patientID = patid1.getText().toString();
patientPass = patpw1.getText().toString();
LoginOperation loginOperation = new LoginOperation();
loginOperation.execute();
}
public void forgot_password(View y) {
Intent fp = new Intent(this, Forgotpassword_Activity.class);
startActivity(fp);
}
private class LoginOperation extends AsyncTask<String, String, JSONObject> {
JSONParser jsonParser = new JSONParser();
ProgressDialog pd = new ProgressDialog(Startup_Activity.this);
private static final String LOGIN_URL = "http://localhost/dc/patient_login.php";
private static final String TAG_SUCCESS = "success";
private static final String TAG_MESSAGE = "message";
@Override
protected void onPreExecute() {
pd.setMessage("Logging in");
pd.show();
}
Boolean result = false;
@Override
protected JSONObject doInBackground(String... args) {
try {
HashMap<String, String> params = new HashMap<>();
params.put("patientID", args[0]);
params.put("patientPass", args[1]);
Log.d("request", "starting");
JSONObject json = jsonParser.makeHttpRequest(
LOGIN_URL, "POST", params);
if (json != null) {
Log.d("JSON result", json.toString());
return json;
}
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
@Override
protected void onPostExecute(JSONObject json) {
int success = 0;
String message = "";
if (pd != null && pd.isShowing()) {
pd.dismiss();
}
if (json != null) {
Toast.makeText(Startup_Activity.this, json.toString(),
Toast.LENGTH_LONG).show();
try {
success = json.getInt(TAG_SUCCESS);
message = json.getString(TAG_MESSAGE);
} catch (JSONException e) {
e.printStackTrace();
}
}
if (success == 2) {
Log.d("Success!", message);
Intent x = new Intent(this, Securityquestion_Activity.class);
finish();
startActivity(x);
}
else if (success == 1) {
Log.d("Success!", message);
Intent x = new Intent(this, Home_Activity.class);
finish();
startActivity(x);
else{
Log.d("Failure", message);
}
}
}
}
//for JSONParser
package com.example.edmar.drgilgarciadentalclinic;
import android.util.Log;
import org.json.JSONException;
import org.json.JSONObject;
import java.io.BufferedInputStream;
import java.io.BufferedReader;
import java.io.DataOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.UnsupportedEncodingException;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLEncoder;
import java.util.HashMap;
public class JSONParser {
String charset = "UTF-8";
HttpURLConnection conn;
DataOutputStream wr;
StringBuilder result;
URL urlObj;
JSONObject jObj = null;
StringBuilder sbParams;
String paramsString;
public JSONObject makeHttpRequest(String url, String method,
HashMap<String, String> params) {
sbParams = new StringBuilder();
int i = 0;
for (String key : params.keySet()) {
try {
if (i != 0){
sbParams.append("&");
}
sbParams.append(key).append("=")
.append(URLEncoder.encode(params.get(key), charset));
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
i++;
}
if (method.equals("POST")) {
// request method is POST
try {
urlObj = new URL(url);
conn = (HttpURLConnection) urlObj.openConnection();
conn.setDoOutput(true);
conn.setRequestMethod("POST");
conn.setRequestProperty("Accept-Charset", charset);
conn.setReadTimeout(10000);
conn.setConnectTimeout(15000);
conn.connect();
paramsString = sbParams.toString();
wr = new DataOutputStream(conn.getOutputStream());
wr.writeBytes(paramsString);
wr.flush();
wr.close();
} catch (IOException e) {
e.printStackTrace();
}
}
else if(method.equals("GET")){
// request method is GET
if (sbParams.length() != 0) {
url += "?" + sbParams.toString();
}
try {
urlObj = new URL(url);
conn = (HttpURLConnection) urlObj.openConnection();
conn.setDoOutput(false);
conn.setRequestMethod("GET");
conn.setRequestProperty("Accept-Charset", charset);
conn.setConnectTimeout(15000);
conn.connect();
} catch (IOException e) {
e.printStackTrace();
}
}
try {
//Receive the response from the server
InputStream in = new BufferedInputStream(conn.getInputStream());
BufferedReader reader = new BufferedReader(new InputStreamReader(in));
result = new StringBuilder();
String line;
while ((line = reader.readLine()) != null) {
result.append(line);
}
Log.d("JSON Parser", "result: " + result.toString());
} catch (IOException e) {
e.printStackTrace();
}
conn.disconnect();
// try parse the string to a JSON object
try {
jObj = new JSONObject(result.toString());
} catch (JSONException e) {
Log.e("JSON Parser", "Error parsing data " + e.toString());
}
// return JSON Object
return jObj;
}
}
这些是例外和系统错误:
02-29 22:18:05.047 1507-1507/com.example.edmar.drgilgarciadentalclinic D/dalvikvm﹕ Late-enabling CheckJNI
02-29 22:18:05.911 1507-1507/com.example.edmar.drgilgarciadentalclinic D/libEGL﹕ loaded /system/lib/egl/libEGL_genymotion.so
02-29 22:18:05.935 1507-1507/com.example.edmar.drgilgarciadentalclinic D/﹕ HostConnection::get() New Host Connection established 0xb9624ff8, tid 1507
02-29 22:18:05.963 1507-1507/com.example.edmar.drgilgarciadentalclinic D/libEGL﹕ loaded /system/lib/egl/libGLESv1_CM_genymotion.so
02-29 22:18:05.971 1507-1507/com.example.edmar.drgilgarciadentalclinic D/libEGL﹕ loaded /system/lib/egl/libGLESv2_genymotion.so
02-29 22:18:06.143 1507-1507/com.example.edmar.drgilgarciadentalclinic W/EGL_genymotion﹕ eglSurfaceAttrib not implemented
02-29 22:18:06.155 1507-1507/com.example.edmar.drgilgarciadentalclinic E/OpenGLRenderer﹕ Getting MAX_TEXTURE_SIZE from GradienCache
02-29 22:18:06.183 1507-1507/com.example.edmar.drgilgarciadentalclinic E/OpenGLRenderer﹕ Getting MAX_TEXTURE_SIZE from Caches::initConstraints()
02-29 22:18:06.187 1507-1507/com.example.edmar.drgilgarciadentalclinic D/OpenGLRenderer﹕ Enabling debug mode 0
02-29 22:18:27.471 1507-1507/com.example.edmar.drgilgarciadentalclinic D/dalvikvm﹕ GC_FOR_ALLOC freed 136K, 11% free 2805K/3124K, paused 6ms, total 7ms
02-29 22:18:27.499 1507-1507/com.example.edmar.drgilgarciadentalclinic D/dalvikvm﹕ GC_FOR_ALLOC freed 4K, 11% free 2899K/3224K, paused 3ms, total 13ms
02-29 22:18:27.579 1507-1507/com.example.edmar.drgilgarciadentalclinic I/dalvikvm-heap﹕ Grow heap (frag case) to 4.080MB for 1127532-byte allocation
02-29 22:18:27.587 1507-1516/com.example.edmar.drgilgarciadentalclinic D/dalvikvm﹕ GC_FOR_ALLOC freed <1K, 8% free 4000K/4328K, paused 9ms, total 9ms
02-29 22:18:27.647 1507-1520/com.example.edmar.drgilgarciadentalclinic W/System.err﹕ java.lang.ArrayIndexOutOfBoundsException: length=0; index=0
02-29 22:18:27.739 1507-1507/com.example.edmar.drgilgarciadentalclinic W/EGL_genymotion﹕ eglSurfaceAttrib not implemented
02-29 22:18:27.843 1507-1520/com.example.edmar.drgilgarciadentalclinic W/System.err﹕ at com.example.edmar.drgilgarciadentalclinic.Startup_Activity$LoginOperation.doInBackground(Startup_Activity.java:74)
02-29 22:18:27.875 1507-1520/com.example.edmar.drgilgarciadentalclinic W/System.err﹕ at com.example.edmar.drgilgarciadentalclinic.Startup_Activity$LoginOperation.doInBackground(Startup_Activity.java:50)
02-29 22:18:27.887 1507-1520/com.example.edmar.drgilgarciadentalclinic W/System.err﹕ at android.os.AsyncTask$2.call(AsyncTask.java:287)
02-29 22:18:27.919 1507-1520/com.example.edmar.drgilgarciadentalclinic W/System.err﹕ at java.util.concurrent.FutureTask.run(FutureTask.java:234)
02-29 22:18:27.947 1507-1520/com.example.edmar.drgilgarciadentalclinic W/System.err﹕ at android.os.AsyncTask$SerialExecutor$1.run(AsyncTask.java:230)
02-29 22:18:27.987 1507-1520/com.example.edmar.drgilgarciadentalclinic W/System.err﹕ at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1080)
02-29 22:18:27.987 1507-1520/com.example.edmar.drgilgarciadentalclinic W/System.err﹕ at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:573)
02-29 22:18:27.987 1507-1520/com.example.edmar.drgilgarciadentalclinic W/System.err﹕ at java.lang.Thread.run(Thread.java:841)
02-29 22:18:28.195 1507-1507/com.example.edmar.drgilgarciadentalclinic D/Failure﹕ [ 02-29 22:18:28.287 411: 802 W/InputMethodManagerService ]
Window already focused, ignoring focus gain of: com.android.internal.view.IInputMethodClient$Stub$Proxy@529e327c attribute=null, token = android.os.BinderProxy@5294e9f4
服务器端PHP:
<?php
include 'connection.php';
header('Content-Type: application/json');
if(isset($_POST['patientID'], $_POST['patientPass'])){
$patient_id = $_POST['patientID'];
$patient_pass = $_POST['patientPass'];
if(!empty($patient_id) && !empty($patient_pass))
{
//$encrypted_pass = md5($patient_pass);
$query = "Select * From patients Where patientid='$patient_id' and patientpassword='$patient_pass'";
$result = $db->query($query);
if(mysqli_num_rows($result)>0){
$security_check = mysqli_fetch_array($result,MYSQLI_ASSOC);
if($security_check['patientsecurity'] == NULL || $security_check['patientanswer'] == NULL){
$json['success'] = 2;
$json['message'] = 'Your account will be confirmed with your security question and answer.';
echo json_encode($json);
mysqli_close($db);
}
else{
$json['success'] = 1;
$json['message'] = 'Successfully logged in.';
echo json_encode($json);
mysqli_close($db);
}
}
else{
$json['success'] = 0;
$json['message'] = 'Incorrect Patient ID or Password.';
echo json_encode($json);
mysqli_close($db);
}
}
else
{
$json['message']="You must complete all required fields.";
echo json_encode($json);
mysqli_close($db);
}
}
?>
答案 0 :(得分:0)
这是你的罪魁祸首
02-29 22:18:27.647 1507-1520/com.example.edmar.drgilgarciadentalclinic W/System.err﹕ java.lang.ArrayIndexOutOfBoundsException: length=0; index=0
我能在代码中找到的唯一数组是
params.put("patientID", args[0]);
params.put("patientPass", args[1]);
基于此堆栈跟踪,现在我没有计算行号,但我非常确定
02-29 22:18:27.739 1507-1507/com.example.edmar.drgilgarciadentalclinic W/EGL_genymotion﹕ eglSurfaceAttrib not implemented
02-29 22:18:27.843 1507-1520/com.example.edmar.drgilgarciadentalclinic W/System.err﹕ at com.example.edmar.drgilgarciadentalclinic.Startup_Activity$LoginOperation.doInBackground(Startup_Activity.java:74)
应该引导你到同样的两行。提出一个断点并进行调试。
再往前走
loginOperation.execute();
应该传递args的中没有任何内容,导致错误原因。
@Override
protected JSONObject doInBackground(String... args)
它从未收到过args。
我希望你先弄明白。
loginOperation.execute(arg1, arg2)
应解决它。
答案 1 :(得分:0)
您遇到ArrayIndexOutOfBoundsException
因为您可能没有传递第二个参数
java.lang.ArrayIndexOutOfBoundsException: length=0; index=0
确保您的参数不超过数组的长度。
在这里,确保你的长度为2的数组。
params.put("patientID", args[0]);
params.put("patientPass", args[1]);
答案 2 :(得分:0)
更改代码中的登录方法。您必须使用Async任务执行调用传递参数。然后只有你能够在异步调用的doInbackground方法中获得这些值。
public void login(View x) {
patientID = patid1.getText().toString();
patientPass = patpw1.getText().toString();
String[] args = {patientID ,patientPass };
LoginOperation loginOperation = new LoginOperation();
loginOperation.execute(args);
}
像这个伙伴一样检查!快乐的编码