【问题标题】:org.json.JSONException: Value Connection of type java.lang.String cannot be converted to JSONArrayorg.json.JSONException:java.lang.String 类型的值连接无法转换为 JSONArray
【发布时间】:2020-03-26 17:33:39
【问题描述】:

我正在尝试登录,它给了我JSONExceptionError。下面是我的登录代码。如果我将localhost 放在我的 php 代码中,它可以工作,但是对于这个 IP 地址它不起作用。

public class MainActivity extends AppCompatActivity  {

TextView textView;
Button login_button;
EditText Username,Password;
String username,password;
String login_url = "http://192.168.0.21/maps/login.php";
AlertDialog.Builder builder;
@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    textView = (TextView)findViewById(R.id.reg_txt);
    textView.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            Intent intent = new Intent(MainActivity.this,Register.class);
            startActivity(intent);
        }
    });
    builder = new AlertDialog.Builder(MainActivity.this);
    login_button = (Button)findViewById(R.id.bn_login);
    Username = (EditText)findViewById(R.id.login_name);
    Password = (EditText)findViewById(R.id.login_password);
    login_button.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
             username = Username.getText().toString();
             password = Password.getText().toString();
            if(username.equals("")||password.equals("")){
                builder.setTitle("Something went wrong");
                displayAlert("Enter a valid username and password");
            }
            else{
                StringRequest stringRequest = new StringRequest(Request.Method.POST, login_url, new Response.Listener<String>() {
                    @Override
                    public void onResponse(String response) {
                        try {
                            JSONArray jsonArray = new JSONArray(response);
                            JSONObject jsonObject = jsonArray.getJSONObject(0);
                            String code = jsonObject.getString("code");
                            if(code.equals("login_failed")){
                                builder.setTitle("Error in login");
                                displayAlert(jsonObject.getString("message"));
                            }
                            else{
                                startActivity(new Intent(MainActivity.this,MapsActivity.class));
                            }
                        } catch (JSONException e) {
                            e.printStackTrace();
                        }

                    }
                }, new Response.ErrorListener() {
                    @Override
                    public void onErrorResponse(VolleyError error) {
                        Toast.makeText(MainActivity.this, error.getMessage(), Toast.LENGTH_LONG).show();
                    }
                }){
                  @Override
                  protected Map<String,String> getParams() throws AuthFailureError{
                      Map<String,String> params = new HashMap<>();
                      params.put("user_name",username);
                      params.put("password",password);
                    return params;
                  }
                };
                MySingeleton.getInstance(MainActivity.this).addToRequestque(stringRequest);
            }
        }
    });
}
public void displayAlert(String message){
    builder.setMessage(message);
    builder.setPositiveButton("OK", new DialogInterface.OnClickListener() {
        @Override
        public void onClick(DialogInterface dialog, int which) {
            Username.setText("");
            Password.setText("");
        }
    });
    AlertDialog alertDialog = builder.create();
    alertDialog.show();
}
}

下面是我的php连接代码。在浏览器中运行后,它给出了输出,但数据没有插入到数据库中。

<?php
header('Content-Type: application/json');
$host = "";
$user_name = "android";
$user_password = "^AndroidReg2019";
$db_name = "mapdb";

$conn = mysqli_connect($host,$user_name,$user_password,$db_name);

if($conn)
echo "Connection success..";
else
echo "Connection failed...";
?>

以下是我的登录 php 代码。

<?php
require "init.php";
$user_name = $_POST["user_name"];
$password = $_POST["password"];
$sql = "select user_name from user_info where user_name = '$user_name' and password = '$password';";
$result = mysqli_query($conn,$sql);
$response = array();
if(mysqli_num_rows($result)>0){
$row = mysqli_fetch_row($result);
$name  = $row[0];
$code = "login_success";
array_push($response,array("code"=>$code,"user_name"=>$user_name));
echo json_encode($response);
}
else{
$code = "login_failed";
$message = "Please verify credentials and try login again.";
array_push($response,array("code"=>$code,"message"=>$message));
echo json_encode($response);
}
mysqli_close($conn);
?>

【问题讨论】:

  • 链接 192.168.0.21/maps/login.php 是否在 POSTMAN/任何其他 REST 服务工具中工作?
  • 是的。它的工作。
  • 你能把你发送到链接的Json发给我吗?
  • 不,我的意思是您通过邮件发送的值
  • name=a&email=a&user_name=a&password=a

标签: php android json


【解决方案1】:

问题出在这行

JSONArray jsonArray = new JSONArray(response);
JSONObject jsonObject = jsonArray.getJSONObject(0)

您的数据已经是一个 JSONObject。无需将响应转换为数组并获取对象。

这样做很简单:

JSONObject jsonObject = new JSONObject(response);

【讨论】:

  • 你的回答很到位,但她面临的问题是与她的 SQL 的连接,一些 PHP 与 MYSQL 的连接问题
【解决方案2】:

以下是我的一些观察结果

  • 您正在解析代码中提到的参数中的名称
  • 你只是在解析

params.put("用户名",用户名); params.put("密码",密码);

  • 还可以尝试修剪您的用户名和密码,以确保您没有解析不必要的空格
  • 最后一个选项尝试将 localhost 放入 $host = "";表示 $host = "localhost"

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2015-11-05
    • 2016-11-29
    • 2016-07-09
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多