php - Android 应用程序向 mysql 数据库添加数据会抛出 JSONException

标签 php android mysql json

我正在尝试使用 Android 应用程序在 mysql 数据库的表 PERSON(nom,pass_world) 中添加一行。 当我在浏览器中执行 php 代码(savedata.php)时,它显示:query_result":"SUCCESS",这意味着成功添加了一行。 我在 google 中搜索了一些允许 Android 应用程序将数据添加到 mysql 数据库的代码,然后我尝试了它,但不幸的是它抛出 JSONEexcption 并显示消息“解析 JSON 数据时出错”,如下面的代码所示:

savedata.php

<?php
$con=mysqli_connect("localhost","root","","othmane");
if (mysqli_connect_errno($con))
{
   echo '{"query_result":"ERROR"}';
}

$name = $_GET['nom'];
$pass = $_GET['pass_world'];
 
$result = mysqli_query($con,"INSERT INTO person (nom,pass_world) VALUES ('$name', '$pass')");
 
if($result == true) {
    echo '{"query_result":"SUCCESS"}';
}
else{
    echo '{"query_result":"FAILURE"}';
}
mysqli_close($con);
?>

MainActivity.java

public class MainActivity extends AppCompatActivity {
EditText inputName;
EditText inputpwd;
Button button;
String nom, password;


@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    inputName = (EditText) (findViewById(R.id.editText));
    inputpwd = (EditText) (findViewById(R.id.editText2));
    button = (Button) findViewById(R.id.button);
}

public void save(View view) {
    nom = inputName.getText().toString();
    password = inputpwd.getText().toString();

    new SignupActivity(this).execute(nom, password);
}

}

SignupAtivity.java

public class SignupActivity extends AsyncTask<String, Void, String> {

private Context context;

public SignupActivity(Context context) {
    this.context = context;
}

protected void onPreExecute() {

}

@Override
protected String doInBackground(String... params) {
    String link;
    String data;
    BufferedReader bufferedReader;
    String result;

    try {
        data = "?nom=jean";
        data += "&pass_world=123456";

        link = "http://localhost/save/savedata.php" + data;
        URL url = new URL(link);
        HttpURLConnection con = (HttpURLConnection) url.openConnection();

        bufferedReader = new BufferedReader(new InputStreamReader(con.getInputStream()));
        result = bufferedReader.readLine();
        return result;
    } catch (Exception e) {
        return new String("Exception: " + e.getMessage());
    }
}
@Override
protected void onPostExecute(String result) {
    String jsonStr = result;
    if (jsonStr != null) {
        try {
            JSONObject jsonObj = new JSONObject(jsonStr);
            String query_result = jsonObj.getString("query_result");
            if (query_result.equals("SUCCESS")) {
                Toast.makeText(context, "Data inserted successfully. Signup successfull.", Toast.LENGTH_SHORT).show();
            } else if (query_result.equals("FAILURE")) {
                Toast.makeText(context, "Data could not be inserted. Signup failed.", Toast.LENGTH_SHORT).show();
            } else {
                Toast.makeText(context, "Couldn't connect to remote database.", Toast.LENGTH_SHORT).show();
            }
        } catch (JSONException e) {
            e.printStackTrace();
            Toast.makeText(context,"Error parsing JSON data.", Toast.LENGTH_SHORT).show();
        }
    } else {
        Toast.makeText(context, "Couldn't get any JSON data.", Toast.LENGTH_SHORT).show();
    }
}

}

日志猫:

03-07 06:42:26.992 8503-8503/com.example.othmane.myapplication D/!!: 异常: 无法连接到 localhost/127.0.0.1 (端口 80): 连接失败: ECONNREFUSED (连接被拒绝) 03-07 06:42:29.844 8503-8503/com.example.othmane.myapplication W/System.err:org.json.JSONException:java.lang.String类型的值异常无法转换为JSONObject 03-07 06:42:29.845 8503-8503/com.example.othmane.myapplication W/System.err: 在 org.json.JSON.typeMismatch(JSON.java:111) 03-07 06:42:29.845 8503-8503/com.example.othmane.myapplication W/System.err: 在 org.json.JSONObject.(JSONObject.java:160) 03-07 06:42:29.845 8503-8503/com.example.othmane.myapplication W/System.err: 在 org.json.JSONObject.(JSONObject.java:173) 03-07 06:42:29.845 8503-8503/com.example.othmane.myapplication W/System.err: 在 com.example.othmane.myapplication.SignupActivity.onPostExecute(SignupActivity.java:60) 03-07 06:42:29.845 8503-8503/com.example.othmane.myapplication W/System.err: 在 com.example.othmane.myapplication.SignupActivity.onPostExecute(SignupActivity.java:20) 03-07 06:42:29.845 8503-8503/com.example.othmane.myapplication W/System.err: 在 android.os.AsyncTask.finish(AsyncTask.java:651) 03-07 06:42:29.845 8503-8503/com.example.othmane.myapplication W/System.err: 在 android.os.AsyncTask.-wrap1(AsyncTask.java) 03-07 06:42:29.845 8503-8503/com.example.othmane.myapplication W/System.err: 在 android.os.AsyncTask$InternalHandler.handleMessage(AsyncTask.java:668) 03-07 06:42:29.846 8503-8503/com.example.othmane.myapplication W/System.err: 在 android.os.Handler.dispatchMessage(Handler.java:102) 03-07 06:42:29.847 8503-8503/com.example.othmane.myapplication W/System.err: 在 android.os.Looper.loop(Looper.java:148) 03-07 06:42:29.847 8503-8503/com.example.othmane.myapplication W/System.err: 在 android.app.ActivityThread.main(ActivityThread.java:5417) 03-07 06:42:29.847 8503-8503/com.example.othmane.myapplication W/System.err:在java.lang.reflect.Method.invoke( native 方法) 03-07 06:42:29.847 8503-8503/com.example.othmane.myapplication W/System.err: 在 com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:726) 03-07 06:42:29.847 8503-8503/com.example.othmane.myapplication W/System.err: 在 com.android.internal.os.ZygoteInit.main(ZygoteInit.java:616) 03-07 06:42:29.847 8503-8503/com.example.othmane.myapplication D/!!: 异常: 无法连接到 localhost/127.0.0.1 (端口 80): 连接失败: ECONNREFUSED (连接被拒绝)

最佳答案

您必须提及提供POST服务的服务器的IP地址。

link = "http://localhost/save/savedata.php" + data;

将其设置为

link = "http://<IP ADDRESS : PORT>/save/savedata.php" + data;

关于php - Android 应用程序向 mysql 数据库添加数据会抛出 JSONException,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35836300/

相关文章:

java - 在 Fragment 的 onAttach(Activity) 中存储 Activity

android - 运行时错误膨胀 fragment

Java 和 MySQL - "Unrecognized statement"

php - Symfony 2 在两个域上登录

php - 选择嵌套查询 CodeIgniter

php - 构建我的 MySQL 搜索查询以与 PDO 一起使用

mysql - 在多个表中搜索相同的值并获取结果来自的表

php - 仍然使用 PDO 参数化查询攻击 SQL 注入(inject)

android - 如何在 Android Studio 中获取 Pixel 5 模拟器

php - SQL : Merge two rows by some ID and keep values