我正在尝试从使用xampp mysql创建的localhost数据库中检索数据。
public class JASONUseActivity extends Activity {
EditText byear; // To take birthyear as input from user
Button submit;
TextView tv; // TextView to show the result of MySQL query
String returnString; // to store the result of MySQL query after decoding JSON
/** Called when the activity is first created. */
@Override
protected void onCreate(Bundle savedInstanceState) {
StrictMode.setThreadPolicy(new StrictMode.ThreadPolicy.Builder()
.detectDiskReads().detectDiskWrites().detectNetwork() // StrictMode is most commonly used to catch accidental disk or network access on the application's main thread
.penaltyLog().build());
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
byear = (EditText) findViewById(R.id.editText1);
submit = (Button) findViewById(R.id.submitbutton);
tv = (TextView) findViewById(R.id.showresult);
// define the action when user clicks on submit button
submit.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
// declare parameters that are passed to PHP script i.e. the name birth year and its value submitted by user
ArrayList < NameValuePair > postParameters = new ArrayList < NameValuePair > ();
// define the parameter
postParameters.add(new BasicNameValuePair("birthyear", byear.getText().toString()));
String response = null;
// call executeHttpPost method passing necessary parameters
try {
response = CustomHttpClient.executeHttpPost("http://localhost/jasonscript.php", postParameters);
// store the result returned by PHP script that runs MySQL query
String result = response.toString();
我无法在textview中查看数据。网址是否正确?
这是位于xampp / htdocs
中的jasonscript.php<?php
$db_host = "localhost";
$db_uid = "root";
$db_pass = "";
$db_name = "";
$db_con = mysql_connect($db_host, $db_uid, $db_pass) or die('could not connect');
mysql_select_db($db_name);
$sql = "SELECT * FROM people WHERE birthyear > '" . $_POST["birthyear"] . "'";
$result = mysql_query($sql);
while ($row = mysql_fetch_assoc($result))
$output[] = $row;
print(json_encode($output));
mysql_close();
?>
我已在清单文件中提供了互联网权限。
提前致谢。
答案 0 :(得分:1)
localhost
是指其环回接口,不您托管要连接的数据库的开发计算机。要使虚拟设备连接到开发机器的环回接口,您需要使用10.0.2.2
。您可以将URL更改为这样的内容,以便点击您的开发机器:
CustomHttpClient.executeHttpPost("http://10.0.2.2/jasonscript.php", postParameters);
有关模拟器网络如何工作的更多详细信息,请参阅我的回答here。
答案 1 :(得分:0)
当您在Android设备上使用localhost
时,您正在尝试使用设备本身的服务。使用服务器的IP /主机名来获取数据。
旁注:另请查看ASyncTask
here,因为在onCreate中下载数据会锁定您的UI-Thread(如果需要很长时间)并且可能会导致App Not Responding
或{{ 1}}。即使它没有发生崩溃,用户体验也会因为应用程序没有响应而降级。