将应用程序连接到本地mysql数据库


Connect app to local mysql database

我正在使用此视频尝试将android应用程序连接到本地托管的MySQL数据库。php脚本似乎不是问题所在,因为它在本地(通过internet explorer)运行良好,并且我不断收到导致应用程序崩溃的空指针异常。

的主要活动

 protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    this.responseTextView = (TextView) this.findViewById(R.id.responseTextView);
    new GetAllCustomerTask().execute(new ApiConnector());
}
public void setTextToTextView(JSONArray jsonArray)
{
    String s  = "";
    for(int i=0; i<jsonArray.length();i++){
        JSONObject json = null;
        try {
            json = jsonArray.getJSONObject(i);
            s = s +
                    "Name : "+json.getString("name")+"'n"+
                    "Owner : "+json.getInt("owner")+"'n"+
                    "Species : "+json.getInt("species")+"'n"+
                    "Sex : "+json.getInt("sex")+"'n"+
                    "Birth : "+json.getInt("birth")+"'n"+
                    "Death : "+json.getInt("death")+"'n";
        } catch (JSONException e) {
            e.printStackTrace();
        }
    }
    this.responseTextView.setText(s);
}
private class GetAllCustomerTask extends AsyncTask<ApiConnector,Long,JSONArray>
{
    @Override
    protected JSONArray doInBackground(ApiConnector... params) {
         return params[0].GetAllCustomers();
    }
    @Override
    protected void onPostExecute(JSONArray jsonArray) {
        setTextToTextView(jsonArray);
    }
}

ApiConnector类

String url = "http://localhost/getallcustomers.php";
    HttpEntity httpEntity = null;
    try
    {
        DefaultHttpClient httpClient = new DefaultHttpClient();  // Default HttpClient
        HttpGet httpGet = new HttpGet(url);
        HttpResponse httpResponse = httpClient.execute(httpGet);
        httpEntity = httpResponse.getEntity();
    } catch (ClientProtocolException e) {
        e.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
    }
    JSONArray jsonArray = null;
    if (httpEntity != null) {
        try {
            String entityResponse = EntityUtils.toString(httpEntity);
            Log.e("Entity Response  : ", entityResponse);
            jsonArray = new JSONArray(entityResponse);
        } catch (JSONException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
    return jsonArray;
}

我认为问题可能出在网址上,但正如我之前所说,它似乎可以通过互联网浏览器正常工作。

任何帮助都将不胜感激。

您的问题与Android、MySQL或PHP无关。在我看来,您需要花时间学习计算机网络的基础知识,以便在您的计算机和移动设备之间进行通信。

看看这篇文章:如何连接Android与PHP MySQL

这篇文章可能会帮助你更好地了解你真正的问题是什么。以下是你需要思考的主要步骤:

  • 两台机器都需要在同一网络(LAN)上
  • 需要在计算机上打开相应的端口,以便允许入站连接(防火墙的配置)

希望这能帮助你解决你的问题。