1

我一直在尝试制作一个应用程序来连接到在 xampp 服务器上运行的数据库。过去我制作了一个 java 应用程序来执行此操作,我使用 JDBC 连接到数据库。我检查了这是否适用于android,我找到了一个在android上使用JDBC的教程,但它对我不起作用。我另外两次连接数据库的尝试是 HttpURLConnection 和 HttpClient 方法。我通过浏览找到的解决方案尚未解决我的问题。我尝试的两个解决方案是,编辑 xampp httpd-xampp.conf 以允许任何连接。第二个是在 PhpMyAdmin 权限部分为电话添加用户。我不知道我可以尝试哪些其他选择。谁能给我任何关于这个问题的建议。一个普通的java应用程序可以毫无问题地连接到服务器,我也可以在我的手机网络浏览器上访问服务器。只是应用程序无法建立连接。

编辑在我在这里找到的一个问题之后。我尝试使用 AsyncTask 使用 JDBC 连接到我的数据库,发布该问题的用户在建立连接时没有遇到问题。所以如果全班,我看不出我的代码在哪里出错了

应用代码

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.Statement;

import android.app.Activity;
import android.os.AsyncTask;
import android.os.Bundle;
import android.util.Log;
import android.view.Menu;
import android.view.MotionEvent;
import android.view.View;
import android.view.View.OnTouchListener;
import android.widget.TextView;

public class ViewCarsEntered extends Activity implements OnTouchListener 
{

private TextView displayCars;

@Override
protected void onCreate(Bundle savedInstanceState) 
{
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_view_cars_entered);
    displayCars = (TextView)findViewById(R.id.carSpaceDisplay);
    displayCars.setOnTouchListener(this);
}

/**
 * Connect to the database 
 * @return String
 */
private class ConnectToDatabase extends AsyncTask<String,Void,String>
{
    @Override
    protected String doInBackground(String... arg0) 
    {
        String response = " ";
        String total = "";
        int rowCounter = 0;

        try
        {
            Class.forName("com.mysql.jdbc.Driver");
            Connection connection = DriverManager.getConnection("jdbc:mysql://server_ip:3306/dbname", "username", "password");
            Statement statement = connection.createStatement();
            ResultSet resultSet = statement.executeQuery("SELECT VehicleDetected FROM entry");

            while(resultSet.next())
            {
                rowCounter++;
            }

            total = Integer.toString(rowCounter);

            response = " I am connected to the database";       
            Log.d("DebugTag", response);

        }catch(Exception e){
            response = "Couldn't get a connection";
            Log.e("Error_Tag", response);
        }
        return response;
    }

    @Override
    protected void onPostExecute(String result)
    {
        displayCars.setText(result);
    }   
}

/**
 * Constructor for the AsynchronousTask inner Class
 */
public void ConnectToDatabase()
{
     ConnectToDatabase connect = new ConnectToDatabase();
     connect.execute();
}


@Override
public boolean onTouch(View v, MotionEvent event) 
{
    ConnectToDatabase();
    return false;
}

@Override
public boolean onCreateOptionsMenu(Menu menu) 
{
    // Inflate the menu; this adds items to the action bar if it is present.
    getMenuInflater().inflate(R.menu.view_cars_entered, menu);
    return true;
}
}
4

1 回答 1

1

我让应用程序正常工作。我使用了 HttpClient 方法。我将该代码添加到 AsyncTask 内部类中。在 PHP 端,我没有给出运行服务器的 pc 的 ip,而是使用本地主机。这是下面的代码,希望这对将来的某人有所帮助。

connect_to_database.php

<?php

//Parameters for connecting to the database
$hostname = "localhost";
$database_name = "dbname";
$username = "user";
$password = "pass";

//Connection String. If it fails causes error message
$connection = mysql_connect($hostname,$username,$password) or trigger_error(mysql_error(),E_USER_ERROR);

//Access the database
mysql_select_db($database_name, $connection);

/*Query to get number of cars and execute the query
 *If there is a problem with the query an error is returned */
$get_number_of_cars = "SELECT VehicleDetected FROM entry ";
$query_runner = mysql_query($get_number_of_cars) or die(mysql_error());
$counter = 0;

while($row = mysql_fetch_array($query_runner))
{
    $counter++;
}

echo $counter;
?>

ViewCarsEntered.java

import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.ResponseHandler;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.BasicResponseHandler;
import org.apache.http.impl.client.DefaultHttpClient;

import android.app.Activity;
import android.app.ProgressDialog;
import android.graphics.Color;
import android.os.AsyncTask;
import android.os.Bundle;
import android.util.Log;
import android.view.Menu;
import android.view.MotionEvent;
import android.view.View;
import android.view.View.OnTouchListener;
import android.widget.TextView;

public class ViewCarsEntered extends Activity implements OnTouchListener
{

private TextView displayCars;
private TextView displaySuggestionMessage;
private HttpPost post;
private HttpResponse httpResponse;
private HttpClient client;
private ProgressDialog dialog = null;

@Override
protected void onCreate(Bundle savedInstanceState) 
{
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_view_cars_entered);
    displayCars = (TextView)findViewById(R.id.carSpaceDisplay);
    displaySuggestionMessage = (TextView)findViewById(R.id.carSpaceSuggestionsBox);
    displayCars.setOnTouchListener(this);
}

/**
 * Connect to the database 
 * @return String
 */
private class ConnectToDatabase extends AsyncTask<String,Void,String>
{
    @Override
    protected String doInBackground(String... arg0) 
    {
        String serverResponse = " ";

        try
        {
            client = new DefaultHttpClient();
            post = new HttpPost("http://server_ip/folder_for_php_script/connect_to_database.php");
            httpResponse = client.execute(post);

            ResponseHandler<String> responseHandler = new BasicResponseHandler();
            serverResponse = client.execute(post, responseHandler);

        }catch(Exception e){
            serverResponse = "Could not connect to Database";
            Log.e("Error_Tag", e.toString());
        }
        return serverResponse;
    }

    @Override
    protected void onPostExecute(String result)
    {
        displayCars.setText(result);

        int responseCheck = Integer.parseInt(result);

        if( responseCheck <= 7 )
        {
            displayCars.setTextColor(Color.BLACK);
            displaySuggestionMessage.setText("It is ok to park in the main car park");
        }

        else if( responseCheck <= 11)
        {
            displayCars.setTextColor(Color.YELLOW);
            displaySuggestionMessage.setText("You may want to try the B block");
        }

        else if( responseCheck >= 12)
        {
            displayCars.setTextColor(Color.RED);
            displaySuggestionMessage.setText("Consider Alternate Parking");
        }
    }   
}

/**
 * Constructor for the AsynchronousTask inner Class
 */
public void ConnectToDatabase()
{
    ConnectToDatabase connect = new ConnectToDatabase();
    connect.execute();
}

@Override
public boolean onTouch(View v, MotionEvent event) 
{
    ConnectToDatabase();
    return true;
}

@Override
public boolean onCreateOptionsMenu(Menu menu) 
{
    // Inflate the menu; this adds items to the action bar if it is present.
    getMenuInflater().inflate(R.menu.view_cars_entered, menu);
    return true;
}
}
于 2013-04-22T21:50:24.867 回答