我不能让我的Andr​​oid应用程序连接到外部数据库我XAMPP服务器上 [英] I can't get my android app to connect to an external database on my xampp server

查看:248
本文介绍了我不能让我的Andr​​oid应用程序连接到外部数据库我XAMPP服务器上的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我一直在试图让一个应用程序连接到服务器的XAMPP上运行的数据库。我做了一个Java应用程序,在过去要做到这一点,我用JDBC连接到数据库。我检查,看看这是否是适用于机器人,我发现那里的JDBC是在Android上使用的教程,但它并没有为我工作。我在连接数据库的另外两个尝试是,在HttpURLConnection类和HttpClient的方法。我从浏览发现了解决方案,并没有解决我的问题呢。这两种方案我都试过,编辑XAMPP的httpd-xampp.conf允许任何连接。二是增加了对在phpMyAdmin的的privilages部分手机用户。我不知道还有什么其他的选择,我可以尝试。谁能给我任何意见这个问题。一个普通的Java应用程序可以连接到没有问题的服务器,我也可以访问我的手机浏览器完成。它只是无法建立连接的应用程序。

修改下面一个问题,我发现这里 href=\"http://stackoverflow.com/questions/13037730/java-android-asynctask-mysql-connection\">。我试图连接到我用谁张贴这个问题的AsyncTask的用户JDBC数据库没有捣乱的连接。所以,我没有看到我和我的code怎么回事错的,如果满级

应用code

 进口java.sql.Connection中;
进口java.sql.DriverManager中;
进口java.sql.ResultSet中;
进口java.sql.Statement中;进口android.app.Activity;
进口android.os.AsyncTask;
进口android.os.Bundle;
进口android.util.Log;
进口android.view.Menu;
进口android.view.MotionEvent;
进口android.view.View;
进口android.view.View.OnTouchListener;
进口android.widget.TextView;公共类ViewCarsEntered扩展活动实现OnTouchListener
{私人TextView的displayCars;@覆盖
保护无效的onCreate(捆绑savedInstanceState)
{
    super.onCreate(savedInstanceState);
    的setContentView(R.layout.activity_view_cars_entered);
    displayCars =(的TextView)findViewById(R.id.carSpaceDisplay);
    displayCars.setOnTouchListener(本);
}/ **
 *连接到数据库
 * @返回字符串
 * /
私有类ConnectToDatabase扩展的AsyncTask<弦乐,太虚,字符串>
{
    @覆盖
    保护字符串doInBackground(字符串...为arg0)
    {
        串响应=;
        字符串总=;
        INT rowCounter = 0;        尝试
        {
            的Class.forName(com.mysql.jdbc.Driver);
            连接连接=的DriverManager.getConnection(JDBC的:mysql:// SERVER_IP:3306 / DBNAME,用户名,密码);
            声明语句= connection.createStatement();
            ResultSet中的resultSet = Statement.executeQuery的(选择VehicleDetected从入门);            而(resultSet.next())
            {
                rowCounter ++;
            }            总= Integer.toString(rowCounter);            响应=我连接到数据库;
            Log.d(DebugTag,响应);        }赶上(例外五){
            响应=无法取得联系;
            Log.e(Error_Tag,响应);
        }
        返回响应;
    }    @覆盖
    保护无效onPostExecute(字符串结果)
    {
        displayCars.setText(结果);
    }
}/ **
 *构造函数AsynchronousTask内部类
 * /
公共无效ConnectToDatabase()
{
     ConnectToDatabase连接=新ConnectToDatabase();
     connect.execute();
}
@覆盖
公共布尔onTouch(视图V,MotionEvent事件)
{
    ConnectToDatabase();
    返回false;
}@覆盖
公共布尔onCreateOptionsMenu(菜单菜单)
{
    //充气菜单;如果是present这增加了项目操作栏。
    。getMenuInflater()膨胀(R.menu.view_cars_entered,菜单);
    返回true;
}
}


我得到了应用程序的工作。我用了HttpClient的方法。我补充说,code到AsyncTask的内部类。在PHP端,而不是给PC的IP运行的服务器,我只是用本地主机。这里是code以下希望这将帮助别人的未来。

connect_to_database.php

 < PHP用于连接到数据库//参数
$主机=localhost的;
$数据库名称=DBNAME;
$用户名=用户;
$密码=通行证;//连接字符串。如果失败原因的错误信息
$连接= mysql_connect($主机名,用户名$,$密码)或trigger_error(mysql_error(),E_USER_ERROR);//访问数据库
mysql_select_db($数据库名称,$连接);/ *查询来获取汽车的数量和执行查询
 *如果有问题,则返回一个错误的查询* /
$ get_number_of_cars =SELECT VehicleDetected从入门;
$ query_runner =的mysql_query($ get_number_of_cars)或死亡(mysql_error());
$计数器= 0;而($行= mysql_fetch_array($ query_runner))
{
    $柜台++;
}回声$计数器;
?>

ViewCarsEntered.java

 进口org.apache.http.Htt presponse;
进口org.apache.http.client.HttpClient;
进口org.apache.http.client.ResponseHandler;
进口org.apache.http.client.methods.HttpPost;
进口org.apache.http.impl.client.BasicResponseHandler;
进口org.apache.http.impl.client.DefaultHttpClient;进口android.app.Activity;
进口android.app.ProgressDialog;
进口android.graphics.Color;
进口android.os.AsyncTask;
进口android.os.Bundle;
进口android.util.Log;
进口android.view.Menu;
进口android.view.MotionEvent;
进口android.view.View;
进口android.view.View.OnTouchListener;
进口android.widget.TextView;公共类ViewCarsEntered扩展活动实现OnTouchListener
{私人TextView的displayCars;
私人TextView的displaySuggestionMessage;
私人HttpPost岗位;
私人的Htt presponse HTT presponse;
私人HttpClient的客户端;
私人ProgressDialog对话框= NULL;@覆盖
保护无效的onCreate(捆绑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(本);
}/ **
 *连接到数据库
 * @返回字符串
 * /
私有类ConnectToDatabase扩展的AsyncTask<弦乐,太虚,字符串>
{
    @覆盖
    保护字符串doInBackground(字符串...为arg0)
    {
        串serverResponse =;        尝试
        {
            客户端=新DefaultHttpClient();
            后=新HttpPost(HTTP://server_ip/folder_for_php_script/connect_to_database.php);
            HTT presponse = client.execute(岗位);            ResponseHandler所<串GT; ResponseHandler所=新BasicResponseHandler();
            serverResponse = client.execute(邮局,ResponseHandler所);        }赶上(例外五){
            serverResponse =无法连接到数据库;
            Log.e(Error_Tag,e.toString());
        }
        返回serverResponse;
    }    @覆盖
    保护无效onPostExecute(字符串结果)
    {
        displayCars.setText(结果);        INT responseCheck =的Integer.parseInt(结果);        如果(responseCheck&下; = 7)
        {
            displayCars.setTextColor(Color.BLACK);
            displaySuggestionMessage.setText(这是确定的主要停车场停放);
        }        否则,如果(responseCheck< = 11)
        {
            displayCars.setTextColor(Color.YELLOW);
            displaySuggestionMessage.setText(你可能想尝试的B地块);
        }        否则,如果(responseCheck> = 12)
        {
            displayCars.setTextColor(Color.RED);
            displaySuggestionMessage.setText(考虑备用停车场);
        }
    }
}/ **
 *构造函数AsynchronousTask内部类
 * /
公共无效ConnectToDatabase()
{
    ConnectToDatabase连接=新ConnectToDatabase();
    connect.execute();
}@覆盖
公共布尔onTouch(视图V,MotionEvent事件)
{
    ConnectToDatabase();
    返回true;
}@覆盖
公共布尔onCreateOptionsMenu(菜单菜单)
{
    //充气菜单;如果是present这增加了项目操作栏。
    。getMenuInflater()膨胀(R.menu.view_cars_entered,菜单);
    返回true;
}
}

I have been trying to make an app to connect to a database running on a xampp server. I have made a java application to do this in the past, I used JDBC to connect to the database. I checked to see if this was applicable to android, I found a tutorial where the JDBC was used on android but it did not work for me. My other two attempts at connecting to the database was, the HttpURLConnection and HttpClient methods. The solutions I have found from browsing, have not solved my issue yet. The two solutions I tried were, editing the xampp httpd-xampp.conf to allow any connections. The second was adding a user for the phone in the PhpMyAdmin privilages section. I don't know what other options I can try. Can anyone give me any advice to this issue. A normal java application can connect to the server with no problems, I can also access the server on my phones web browser. It's just the app that can't establish a connection.

EDIT Following a question I found here. I tried connecting to my database with the JDBC using an AsyncTask the user who posted that question didn't have trouble making a connection. So I don't see where I am going wrong with my code here if the full class

App code

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;
}
}

解决方案

I Got the app working. I used the HttpClient approach. I added that code into a AsyncTask inner class. On the PHP side instead of giving the ip of the pc running the server, I just used local host. here is the code below hopefully this will help someone in the future.

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;
}
}

这篇关于我不能让我的Andr​​oid应用程序连接到外部数据库我XAMPP服务器上的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆