2016-02-29 64 views
1

我也使用這個頁面中的代碼,只是改變了一些變量和其他條件。不過,我沒有改變JSONParser。 How to implement Login with HttpURLConnection and PHP server in Android當我使用JSONParser運行我的android登錄活動(httpurlconnection)

//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: [email protected] attribute=null, token = [email protected] 

服務器端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

我編輯了堆棧跟蹤@Daniel Nugent感謝您的回覆。 – Elle

回答

0

這是您的罪魁禍首

02-29 22:18:27.647 1507-1520/com.example.edmar.drgilgarciadentalclinic W/System.err﹕ java.lang.ArrayIndexOutOfBoundsException: length=0; index=0 

而唯一的陣列我可以在第四季找到E碼是

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) 

它從未收到參數。

我希望你先弄明白。

loginOperation.execute(arg1, arg2) 

應該解決它。

+0

感謝您的回覆@Khanal。所以,你的意思是我應該這樣輸入:loginOperation.execute(patientID,patientPass); ? – Elle

+0

@elle是的,這是正確的。 –

+0

對不起剛剛看到它。讓堆棧跟蹤你的BBF。 :) – Khanal

0

你有遇到ArrayIndexOutOfBoundsException,因爲你可能無法通過第二個參數

java.lang.ArrayIndexOutOfBoundsException: length=0; index=0 

確保你的論點不超過數組的長度。

在這裏,請確保您數組長度2.

params.put("patientID", args[0]); 
params.put("patientPass", args[1]); 
0

更改登錄方法在你的code.You必須與異步任務執行調用傳遞參數。那麼只有你能夠在異步調用的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); 
    } 

Check this buddy!快樂編碼

+0

沒有必要明確地創建一個帶有可變參數的數組... –

+0

您是否建議將數組值直接傳遞給異步任務? – Sreejin

+0

謝謝。當我處理大量變量時,你的回答也幫助了我:) – Elle

相關問題