首页 > 解决方案 > 将 android 连接到队列应用程序的数据库

问题描述

我对android比较陌生,希望你们能提供任何帮助。在我的项目中,我正在尝试创建一个队列系统,以便登录到我的应用程序的任何人都必须输入会话名称。输入此会话名称会将他们移动到具有 2 个选项的新页面:问题和演示。单击其中一个选项,他们的信息将被发送到持有他们之前输入的会话的数据库。会话是该数据库中的表。基本上在我的项目中,我试图连接到一个名为 queue_lnsconnection 的数据库(phpmyadmin)。此数据库包含一个要使用的空会话。我试图指出会话。会话是该数据库中的一个表。我收到一条错误消息“com.android.volley.volleyerror java.lang.nullpointerexception:attempt to invoke virtual method 'int java.lang.string.

请注意,我创建了一个登录页面。

StudentActivity2.java

public class StudentActivity2 extends AppCompatActivity {

    EditText joinSession;

    // Creating button;
    Button joinButton;

    // Creating Volley RequestQueue.
    RequestQueue requestQueue;

    // Create string variable to hold the EditText Value.
    String SessionHolder;
    String DecisionHolder;
    String FirstNameHolder;
    String LastNameHolder;

    // Creating Progress dialog.
    ProgressDialog progressDialog;
    String HttpUrl = "http://192.168.2.150:8080/decisionAndroid.php";

    Boolean CheckEditText;


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_student2);
        joinSession = (EditText) findViewById(R.id.sessName);

// Assigning ID's to Button.
        joinButton = (Button) findViewById(R.id.session);
        // Creating Volley newRequestQueue .
        requestQueue = Volley.newRequestQueue(StudentActivity2.this);

// Assigning Activity this to progress dialog.
        progressDialog = new ProgressDialog(StudentActivity2.this);
        joinButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                CheckEditTextIsEmptyOrNot();

                if (CheckEditText) {

                    PushedButton();

                } else {

                    Toast.makeText(StudentActivity2.this, "Please fill all form fields.", Toast.LENGTH_LONG).show();

                }


            }
        });
    }
        public void CheckEditTextIsEmptyOrNot() {

            // Getting values from EditText.
            SessionHolder = joinSession.getText().toString().trim();


            // Checking whether EditText value is empty or not.
            if (TextUtils.isEmpty(SessionHolder)) {

                // If any of EditText is empty then set variable value as False.
                CheckEditText = false;

            } else {

                // If any of EditText is filled then set variable value as True.
                CheckEditText = true;
            }
        }
    public void PushedButton() {

        // Showing progress dialog at user registration time.
        progressDialog.setMessage("Please Wait");
        progressDialog.show();

        // Creating string request with post method.
        StringRequest stringRequest = new StringRequest(Request.Method.POST, HttpUrl,
                new Response.Listener<String>() {
                    @Override
                    public void onResponse(String ServerResponse) {

                        // Hiding the progress dialog after all task complete.
                        progressDialog.dismiss();

                        // Matching server responce message to our text.
                        if(ServerResponse.equalsIgnoreCase("Data Matched")) {

                            // If response matched then show the toast.
                            Toast.makeText(StudentActivity2.this, "Logged In Successfully", Toast.LENGTH_LONG).show();

                            // Finish the current Login activity.
                            finish();

                            // Opening the user profile activity using intent.
                            Intent intent=new Intent(StudentActivity2.this,MainActivity.class);

                            // Sending User Email to another activity using intent.
                            intent.putExtra("SessionTAG", SessionHolder);

                            startActivity(intent);
                        }
                        else {

                            // Showing Echo Response Message Coming From Server.
                            Toast.makeText(StudentActivity2.this, ServerResponse, Toast.LENGTH_LONG).show();

                        }


                    }
                },
                new Response.ErrorListener() {
                    @Override
                    public void onErrorResponse(VolleyError volleyError) {

                        // Hiding the progress dialog after all task complete.
                        progressDialog.dismiss();

                        // Showing error message if something goes wrong.
                        Toast.makeText(StudentActivity2.this, volleyError.toString(), Toast.LENGTH_LONG).show();
                    }
                }) {
            @Override
            protected Map<String, String> getParams() {

                // Creating Map String Params.
                Map<String, String> params = new HashMap<String, String>();

                // Adding All values to Params.
                // The firs argument should be same sa your MySQL database table columns.
                params.put("id", SessionHolder);
                params.put("decision", DecisionHolder);




                return params;
            }

        };
        // Creating RequestQueue.
        RequestQueue requestQueue = Volley.newRequestQueue(StudentActivity2.this);

        // Adding the StringRequest object into requestQueue.
        requestQueue.add(stringRequest);

    }
    }

检查会话.php

<?php

//Define your host here.
$HostName = "localhost";

//Define your database username here.
$HostUser = "root";

//Define your database password here.
$HostPass = "";

//Define your database name here.
$DatabaseName = "queue_lnsconnection";

?>

决定Android.php

<?php

if($_SERVER['REQUEST_METHOD']=='POST'){

include 'CheckSession.php';
$con = mysqli_connect($HostName,$HostUser,$HostPass,$DatabaseName);

  $First_Name = $_POST['firstname'];
 $Last_Name = $_POST['lastname'];
  $Bench = $_POST['bench'];
 $Decision = $_POST['decision'];


 $CheckSQL = "SELECT * FROM queue_template";
 $check = mysqli_fetch_array(mysqli_query($con,$CheckSQL));
 $result = mysqli_query($con,$CheckSQL);
 $row = mysql_num_rows($result);
 //if(isset($check))

 if($row>0){
echo "Data Matched";
}
else{
echo "Bench not valid";
}

}else{
echo "Check Again";
}
mysqli_close($con);

?>

我试图尽可能减少代码,但我不确定问题是什么。提前致谢!

标签: phpandroidmysqlinput

解决方案


Android 无法读取网页内容,尝试使用如下 JSON 响应

在你的PHP 文件中

    <?php 
// do Connection to DB if 
(isset($_POST['bench'])) {

 $bench = $_POST['bench'];

 $sql = "SELECT COUNT(*) AS num FROM `queue_template ` WHERE bench = : bench";

// Prepare the SQL statement.
$stmt = $dbConn->prepare($sql);

// Bind our bench value to the : bench parameter.
$stmt->bindValue(': bench', $bench);

// Execute the statement.
$stmt->execute();

// Fetch the row / result.
$row = $stmt->fetch(PDO::FETCH_ASSOC);

// If num is bigger than 0, the bench already exists.
if($row['num'] > 0){

// Do your code Here like inserting in SQL or some Functions...
...
 // required field is missing
    $response["success"] = 1;
    $response["message"] = "Bench not exist.";

// echoing JSON response
    echo json_encode($response);
       }else{
       // bench already exist.

    // required field is missing
    $response["success"] = 0;
    $response["message"] = "Bench already exist.";

    // echoing JSON response
    echo json_encode($response);


}

} //Closing if statement 

?>

并在您的 Android Studio 中将此类添加到您的 Activity 类中并在 Gradle 中导入 Json

implementation 'com.googlecode.json-simple:json-simple:1.1'

这是课程

private  class CheckBench extends AsyncTask<String, String, String> {
    String bench = // get Value from EditText or whatever

    // You can add more Strings Ints or anything here


    /**
     * Before starting background thread Show Progress Dialog
     * */
    @Override
    protected void onPreExecute() {

        super.onPreExecute();
        pDialog = new ProgressDialog(PostShow.this);
        pDialog.setMessage("Checking...");
        pDialog.setIndeterminate(false);
        pDialog.setCancelable(true);
        pDialog.show();
    }

    /**
     * Creating product
     * */
    @Override
    protected String doInBackground(String... params) {

        List<NameValuePair> param = new ArrayList<NameValuePair>();

        //add your Strings Ints... as params here
        param.add(new BasicNameValuePair("bench", bench));



        JSONObject json = jsonParser.makeHttpRequest(HttpUrl, "POST", param);
        try {
            int success = json.getInt("success");
            String messages = json.getString("message");
            if (success == 1) {

            }else{
                Toast.makeText(getApplicationContext(), messages,
                        Toast.LENGTH_LONG).show();
            }

        } catch (Exception e) {
            try {
                String messager = json.getString("message");
                Toast.makeText(getApplicationContext(), messager,
                        Toast.LENGTH_LONG).show();
            } catch (JSONException ex) {
                ex.printStackTrace();
            }



            // Toast.makeText(getApplicationContext(), "Error", Toast.LENGTH_LONG).show();
        }
        return null;
    }


    /**
     * After completing background task Dismiss the progress dialog
     * **/
    protected void onPostExecute(String url_link) {
        // dismiss the dialog once done
        COMMENTAIRE.setText("");
        pDialog.dismiss();
        Toast.makeText(getApplicationContext(), "Bench CHecked",
                Toast.LENGTH_LONG).show();

    }
}

推荐阅读