在Android Kotlin中无法通过String Request volley传递数据

时间:2019-07-12 07:22:09

标签: php android kotlin android-volley

因此,我尝试将android应用程序与存储在Phpmyadmin中的数据库连接。我正在使用Volley,因为很多人都推荐这样做。我遵循了一些教程,最后得到了以下代码:

lateinit var etLoginEmail : EditText
lateinit var etLoginPass : EditText
lateinit var btnLog_in : Button

override fun onCreate(savedInstanceState: Bundle?) {
    super.onCreate(savedInstanceState)
    setContentView(R.layout.activity_login)
    if(android.os.Build.VERSION.SDK_INT > 9){
        StrictMode.setThreadPolicy(StrictMode.ThreadPolicy.Builder().permitAll().build())
    }
     etLoginEmail = findViewById(R.id.etLoginEmail) as EditText
     etLoginPass = findViewById(R.id.etLoginPass) as EditText
    btnLog_in = findViewById(R.id.btnLog_in) as Button

    btnLog_in.setOnClickListener {
        if (etLoginEmail?.text.isNullOrEmpty()) {
            etLoginEmail?.error = "Email must be filled"
        } else if (etLoginPass?.text.isNullOrEmpty()) {
            etLoginPass?.error = "Password must be filled"
        } else{            
            doLogin(etLoginEmail.text.toString(), etLoginPass.text.toString())
            }
        }
    }
 fun doLogin(userEmail: String, userPass: String){
    val stringRequest = object : StringRequest(Request.Method.POST, "http://localhost/my_app/login.php",
        Response.Listener<String> { response ->
            Toast.makeText(applicationContext, response.toString(), Toast.LENGTH_LONG).show()
            try {
                val obj = JSONObject(response)
                    startActivity(Intent(this, TabbedHome::class.java))
                    finish()
                Toast.makeText(applicationContext, obj.getString("message"), Toast.LENGTH_LONG).show()
            } catch (e: JSONException) {
                e.printStackTrace()
                Toast.makeText(applicationContext, "please try again", Toast.LENGTH_LONG).show()
            }
        },
        object : Response.ErrorListener {
            override fun onErrorResponse(volleyError: VolleyError) {
                Toast.makeText(applicationContext, volleyError.message, Toast.LENGTH_LONG).show()
            }
        }) {
        @Throws(AuthFailureError::class)
        override fun getParams(): Map<String, String> {
            val params = HashMap<String, String>()
            params.put("user_email", userEmail)
            params.put("user_pass", userPass)
            return params
        }
    }
    VolleySingleton.instance?.addToRequestQueue(stringRequest)
}

我将这些Volley工具导入了我的Login.kt类

import com.android.volley.AuthFailureError
import com.android.volley.Request
import com.android.volley.VolleyError
import com.android.volley.toolbox.StringRequest
import com.android.volley.Response

但是,当我在设备上运行该应用程序时,齐射代码不起作用。我在logcat中也没有收到任何错误。当我单击按钮时,它什么也没做。甚至没有显示任何错误消息。只有这样的错误E/ANDR-PERF-MPCTL: Invalid profile no. 0, total profiles 0 only

我在邮递员上尝试了我的php代码,它的工作原理就像冠军。这是我的php代码:

<?php
session_start();
require_once 'connection.php';
 if($_SERVER["REQUEST_METHOD"]=="POST"){         
    $user_email = $_POST["user_email"];
    $user_pass = $_POST['user_pass']; 

}
     if ((empty($user_email)) || (empty($user_pass))) { 
        $response->success = 0;
        $response->message = "Field must be filled"; 
        die(json_encode($response));
     }
$query = mysqli_query($con, "SELECT * FROM tb_user WHERE user_email='$user_email'");
     $row = mysqli_fetch_array($query);
     $result = $mysqli->query($row);
        $followingdata = $result->fetch_assoc();
     $_SESSION['user_id'] = $row['user_id']; 
 if (password_verify($user_pass, $row['user_pass'])) {
     if (!empty($row)){
        $response = new usr();
        $response->success = 1;
        $_SESSION['user_id'] = $_POST['user_id'];
        $response->message = "Welcome ".$row['user_name'];
        $response->user_id = $row['user_id'];
        $response->user_name = $row['user_name'];
        $_SESSION['user_id'] = $row['user_id'];
        $user_id = $row['user_id'];
        die(json_encode($response));
     }
} else { 

            $response->success = 0;
            $response->message = "Email or pass is in correct";
            die(json_encode($response));
         } 
     mysqli_close($con);
?>

我试图在Internet上搜索一些看起来像我的问题,但仍然找不到我的问题的答案。我还已经将此代码放在<manifest>标签下方,<application>标签之前的AndroidManifest.xml上。

<uses-permission android:name="android.permission.INTERNET"/>

这是我导入的依赖项。

dependencies {
    implementation fileTree(dir: 'libs', include: ['*.jar'])
    implementation "org.jetbrains.kotlin:kotlin-stdlib-jdk7:$kotlin_version"
    implementation 'com.android.support:appcompat-v7:28.0.0'
    implementation 'com.android.support.constraint:constraint-layout:1.1.3'
    implementation 'android.arch.lifecycle:extensions:1.1.1'
    testImplementation 'junit:junit:4.12'
    androidTestImplementation 'com.android.support.test:runner:1.0.2'
    implementation 'com.android.volley:volley:1.1.0'
    implementation 'com.squareup.retrofit2:retrofit:2.1.0'
    implementation 'com.squareup.retrofit2:converter-gson:2.1.0'
    implementation 'com.google.code.gson:gson:2.6.1'
    implementation 'com.squareup.okhttp3:okhttp:3.2.0'
    implementation "com.squareup.retrofit2:adapter-rxjava2:2.3.0"
    implementation "com.squareup.retrofit2:converter-moshi:2.0.0"
    implementation "io.reactivex.rxjava2:rxandroid:2.0.1"
    implementation 'com.squareup.okhttp3:logging-interceptor:3.4.1'
    implementation 'com.android.support:design:28.0.0'
    androidTestImplementation 'com.android.support.test.espresso:espresso-core:3.0.2'
}

我导入了1个以上的依赖项来传递数据,因为我尝试了所有操作,但没有任何效果...

有人可以告诉我我做错了什么吗?任何帮助将不胜感激。非常感谢!!!

1 个答案:

答案 0 :(得分:1)

php side,您正在解码json,但是在android side,您正在将参数传递为form-data

因此,要么更改php-side代码以接收form-data,要么在Android端以原始格式(作为JSON)传递数据。

要通过POST请求接收表单数据,请尝试以下代码:

if($_SERVER["REQUEST_METHOD"]=="POST"){         
    $user_email = $_POST["user_email"];
    $user_pass = $_POST['user_pass']; 
}

使用以上代码,您可以在form-data上发布PHP。现在,您可以对数据进行任何操作。