2017-07-27 72 views
0

好吧,我已經完成了上述任務,但我不滿意它。它看起來非常複雜。使用PHP連接數據庫與其他方式在Android

我需要一些其他解決方法來解決這個問題,因爲我在android開發方面的經驗非常少,找不到任何其他方式。

下面是我做過的。我將向您展示訪問數據庫的簡單登錄系統。

以下是登錄活動。

package com.example.andorid.ersnexus.userlogin; 

import android.app.Activity; 
import android.content.Intent; 
import android.net.ConnectivityManager; 
import android.os.Bundle; 
import android.support.v7.app.AppCompatActivity; 
mport android.view.View; 
import android.widget.Button; 
import android.widget.EditText; 
import android.widget.Toast; 

import com.example.andorid.ersnexus.R; 
import 
com.example.andorid.ersnexus.userprofile.homeactivity. 
UserProfileHomeActivity; 
import com.example.andorid.ersnexus.usersignup.UserSignUpActivity; 
import com.example.andorid.ersnexus.util.SharedPreferencesData; 
import com.example.andorid.ersnexus.webservices.BackgroundDbConnector; 


//This is the main activity of the app. 
//It is the user login screen where users logs in or sign up's. 

public class UserLoginActivity extends AppCompatActivity { 

private EditText mUserName; 
private EditText mUserPassword; 
private Button mLoginButton; 
private Button mSignUpButton; 
//private UserBaseHelper mHelper; 
private String userName; 
private String pass; 
//private String password; 
//private String mErno; 
public static Activity mActivity; 
public static Boolean mActive; 

@Override 
public void onCreate (Bundle savedInstanceState) { 
    super.onCreate(savedInstanceState); 
    setContentView(R.layout.activity_user_login); 

    mActivity = this; 

    Boolean status = SharedPreferencesData.getStoredLoginStatus(UserLoginActivity.this); 
    if(status){ 
     Intent i = new Intent(UserLoginActivity.this, UserProfileHomeActivity.class); 
     startActivity(i); 
    } 

    //mHelper = new UserBaseHelper(this); 


    //user UserName editText in activity_user_login 
    mUserName = (EditText) findViewById(R.id.login_user_name); 


    //PASSWORD editText 
    mUserPassword = (EditText) findViewById(R.id.login_user_pass); 


    //SignUp button 
    mSignUpButton = (Button) findViewById(R.id.sign_up_button); 
    mSignUpButton.setOnClickListener(new View.OnClickListener() { 
     @Override 
     public void onClick (View v) { 
      Intent i = new Intent(UserLoginActivity.this, UserSignUpActivity.class); 
      startActivity(i); 

     } 
    }); 


    //Login Button 
    mLoginButton = (Button) findViewById(R.id.login_button); 
    mLoginButton.setOnClickListener(new View.OnClickListener() { 
     @Override 
     public void onClick (View v) { 
      if(isNetworkAvailableAndConnected()) { 
       /*try { 
        if(!InetAddress.getByName("192.168.2.3").isReachable(5000)){ 
         throw new Exception("Host does not exist::"); 
        } 
       } catch (Exception e) { 
        e.printStackTrace(); 
        Toast.makeText(UserLoginActivity.this, 
          "Server Is Down",Toast.LENGTH_SHORT).show(); 
       }*/ 
       String type = "login"; 
       userName = mUserName.getText().toString(); 
       pass = mUserPassword.getText().toString(); 
       //password = mHelper.fetchUserPass(userName); 
       //mErno = mHelper.fetchErNo(userName); 
       //String fullName = mHelper.fetchFullName(userName); 

       ***BackgroundDbConnector backgroundDbConnector = new 
         BackgroundDbConnector(UserLoginActivity.this); 
       backgroundDbConnector.execute(type, userName, pass);*** 

       SharedPreferencesData.setStoredUsername(UserLoginActivity.this, userName); 
      }else { 
       Toast.makeText(UserLoginActivity.this, 
         "No Internet Connection",Toast.LENGTH_SHORT).show(); 
      } 

     } 
    }); 

} 

@Override 
public void onStart() { 
    super.onStart(); 
    mActive = true; 
} 

@Override 
public void onStop() { 
    super.onStop(); 
    mActive = false; 
} 

private boolean isNetworkAvailableAndConnected() { 
    ConnectivityManager cm = (ConnectivityManager) getSystemService(CONNECTIVITY_SERVICE); 

    boolean isNetworkAvailable = cm.getActiveNetworkInfo() != null; 

    return isNetworkAvailable && 
      cm.getActiveNetworkInfo().isConnected(); 
} 

} 

發佈請求是通過backgroundTask送來

BackgroundDbConnector backgroundDbConnector = new 
         BackgroundDbConnector(UserLoginActivity.this); 

backgroundDbConnector.execute(type, userName, pass); 

然後在下面的東西在後臺的AsyncTask情況:

try { 
       //Fetch the username and password from the background method call. 
       String username = params[1]; 
       String password = params[2]; 

       mHttpURLConnection = URLManager. 
         getConnection(URLManager.LOGIN_URL); 

       //Creating the outputStream 
       OutputStream outputStream = mHttpURLConnection.getOutputStream(); 
       //Writing in the outputStream. 
       BufferedWriter bufferedWriter = new BufferedWriter(new 
         OutputStreamWriter(outputStream, "UTF-8")); 

       //This is for connecting the variables in the app and in the php file. 
       String postData = URLEncoder.encode("username", "UTF-8") + "=" +//$_POST["username"] 
         URLEncoder.encode(username, "UTF-8") + "&" + 
         URLEncoder.encode("password", "UTF-8") + "=" +//$_POST["password"] 
         URLEncoder.encode(password, "UTF-8"); 

       //Feeding the data. 
       bufferedWriter.write(postData); 
       bufferedWriter.flush(); 
       bufferedWriter.close(); 
       outputStream.close(); 

       //Creating an inputStream to fetch the results. 
       InputStream inputStream = mHttpURLConnection.getInputStream(); 

       BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(
         inputStream, "iso-8859-1")); 

       //Getting the results 
       String result = ""; 
       String line; 
       while ((line = bufferedReader.readLine()) != null) { 
        result += line; 
       } 
       bufferedReader.close(); 
       inputStream.close(); 
       mHttpURLConnection.disconnect(); 
       //Returning the results 
       return result; 
} 

最後的PHP文件如下:

<?php 
require "conn.php"; 

$user_name = $_POST["username"]; 
$user_pass = $_POST["password"]; 

$mysql_qry = "SELECT * FROM student_data WHERE username='$user_name' AND 
password='$user_pass';"; 

$result = mysqli_query($conn, $mysql_qry); 
$row_cnt = mysqli_num_rows($result); 

if($row_cnt > 0){ 
$row = mysqli_fetch_assoc($result); 
$erno = $row["enrollmentnumber"]; 
echo $erno; 
} 
else{ 
echo "Wrong Username or Password"; 
} 
?> 

所以大多數數據庫連接做這樣的,我需要一些其他方式來做到這一點

我有一個直覺,正如你可以看到任務所需要的背景,在一些處理其他方式,但我沒有得到一個...

所以那些誰有Android的良好經驗,請指導我通過正確的道路。

在此先感謝那些花時間閱讀我的代碼的開發人員。

這裏是我的項目鏈接。請看看並測試你是否想要,我會喜歡關於我的代碼的意見。

https://github.com/shrungBhatt/ErNexus

+0

你直接把用戶輸入到數據庫中查詢 - ***非常糟糕,非常危險*** – FKEinternet

+0

如果我那麼我登錄,我需要取用戶名直接來自editText.Or是你說我應該先加密它,然後發送它,然後解密,然後把它放在查詢中? –

+0

他正在談論你信任用戶輸入的方式'$ user_name = $ _POST [「username」];'。然後準備好沒有安全檢查的SQL。 – jagad89

回答

0

好吧,我發現了一個另類,它很可愛實現。

try { 
      //Fetch the username and password from the background method call. 
      String username = params[1]; 
      String password = params[2]; 

      mHttpURLConnection = URLManager. 
        getConnection(URLManager.LOGIN_URL); 

      //Creating the outputStream 
      OutputStream outputStream = mHttpURLConnection.getOutputStream(); 
      //Writing in the outputStream. 
      BufferedWriter bufferedWriter = new BufferedWriter(new 
        OutputStreamWriter(outputStream, "UTF-8")); 

      //This is for connecting the variables in the app and in the php file. 
      String postData = URLEncoder.encode("username", "UTF-8") + "=" +//$_POST["username"] 
        URLEncoder.encode(username, "UTF-8") + "&" + 
        URLEncoder.encode("password", "UTF-8") + "=" +//$_POST["password"] 
        URLEncoder.encode(password, "UTF-8"); 

      //Feeding the data. 
      bufferedWriter.write(postData); 
      bufferedWriter.flush(); 
      bufferedWriter.close(); 
      outputStream.close(); 

      //Creating an inputStream to fetch the results. 
      InputStream inputStream = mHttpURLConnection.getInputStream(); 

      BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(
        inputStream, "iso-8859-1")); 

      //Getting the results 
      String result = ""; 
      String line; 
      while ((line = bufferedReader.readLine()) != null) { 
       result += line; 
      } 
      bufferedReader.close(); 
      inputStream.close(); 
      mHttpURLConnection.disconnect(); 
      //Returning the results 
      return result; 
} 

以上全部代碼被Volley替換爲以下代碼。 ,這裏是新的代碼

StringRequest stringRequest = new StringRequest(Request.Method.POST, URLManager. 
         LOGIN_URL, new Response.Listener<String>() { 
        @Override 
        public void onResponse(String response) { 
         if (response != null && 
           !response.equals("Wrong Username or Password")) { 
          SharedPreferencesData.setStoredLoginStatus(mContext, true); 
          SharedPreferencesData.setStoredErno(mContext, response); 
          mContext.startActivity(new Intent(mContext, 
            UserProfileHomeActivity.class)); 
         } else { 
          Toast.makeText(mContext, "Wrong Username or Password!", 
            Toast.LENGTH_SHORT) 
            .show(); 
         } 
        } 
       }, new Response.ErrorListener() { 
        @Override 
        public void onErrorResponse(VolleyError error) { 
         Toast.makeText(UserLoginActivity.this, error.toString(), 
           Toast.LENGTH_SHORT).show(); 

        } 
       }) { 
        @Override 
        protected Map<String, String> getParams() { 
         Map<String, String> params = new HashMap<>(); 
         params.put(KEY_USERNAME, userName); 
         params.put(KEY_PASSWORD, pass); 
         return params; 
        } 
       }; 

       SharedPreferencesData.setStoredUsername(UserLoginActivity.this, userName); 

       RequestQueue requestQueue = Volley.newRequestQueue(UserLoginActivity.this); 
       requestQueue.add(stringRequest);