我一直在尝试创建一个应用程序来连接到xampp服务器上运行的数据库。我以前做了一个java应用程序,我用JDBC连接数据库。我检查了这是否适用于android,我找到了一个教程,其中JDBC在Android上使用,但它对我不起作用。我连接到数据库的另外两次尝试是HttpURLConnection和HttpClient方法。我从浏览中找到的解决方案尚未解决我的问题。我尝试的两个解决方案是编辑xampp httpd-xampp.conf以允许任何连接。第二个是在PhpMyAdmin privilages部分添加手机用户。我不知道我还能尝试哪些其他选择。谁能给我任何关于这个问题的建议。一个普通的Java应用程序可以连接到服务器没有问题,我也可以访问我的手机网络浏览器上的服务器。它只是无法建立连接的应用程序。
编辑在回答问题后,我找到了here。我尝试使用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;
}
}
答案 0 :(得分: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;
}
}