我正在学习Android。我试图从Android中读取PHP输出(通过JSON)。
如果我提供网站网址,则会获取该网址。如果您进入该站点,它将显示如下的Json代码。
http://cpriyankara.coolpage.biz/employee_details.php“;
{“emp_info”:[{“员工姓名”:“Adam”,“员工号码”:“101700”},{“员工姓名”:“John”,“员工号码”:“101701”},{ “员工姓名”:“保罗”,“员工否”:“101702”},{“员工姓名”:“马克”,“员工否”:“101703”},{“员工姓名”:“唐纳德”,“员工编号:“”101704“},{”员工姓名“:”大脑“,”员工编号“:”101705“},{”员工姓名“:”凯文“,”员工编号“:”101706“}]}
如果我给我的本地主机PHP站点,它也以Json的格式显示如上所示。 (我使用WAMPSERVER运行PHP)
{“emp_info”:[{“员工姓名”:“Adam”,“员工号码”:“101700”},{“员工姓名”:“John”,“员工号码”:“101701”},{ “员工姓名”:“保罗”,“员工否”:“101702”},{“员工姓名”:“马克”,“员工否”:“101703”},{“员工姓名”:“唐纳德”,“员工编号:“”101704“},{”员工姓名“:”大脑“,”员工编号“:”101705“},{”员工姓名“:”凯文“,”员工编号“:”101706“}]}
但是在Android中它显示结果如果我给网站,但如果我给localhost地址它说应用程序意外停止。
请让我知道为什么??在这种情况下,我怎么能看到错误或异常。
我在下面提供了PHP和Android代码。
PHP代码:
<?php
$host=""; //replace with database
$username="root"; //replace with database username
$password="root"; //replace with database password
$db_name="and"; //replace with database name
$con=mysql_connect("$host", "$username", "$password")or die("cannot connect");
mysql_select_db("$db_name")or die("cannot select DB");
$sql = "select * from emp_info";
$result = mysql_query($sql);
$json = array();
if(mysql_num_rows($result)){
while($row=mysql_fetch_assoc($result)){
$json['emp_info'][]=$row;
}
}
mysql_close($con);
echo json_encode($json);
?>
Android Java代码:
在URL中的以下代码中,我更改为localhost URL
package com.example.phpmysql;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import org.apache.http.HttpResponse;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import android.os.AsyncTask;
import android.os.Bundle;
import android.app.Activity;
import android.view.Menu;
import android.widget.ListView;
import android.widget.SimpleAdapter;
import android.widget.Toast;
public class MainActivity extends Activity {
private String jsonResult;
Private String url = "http://cpriyankara.coolpage.biz/employee_details.php";
private ListView listView;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
listView = (ListView) findViewById(R.id.listView1);
accessWebService();
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
// Async Task to access the web
private class JsonReadTask extends AsyncTask<String, Void, String> {
@Override
protected String doInBackground(String... params) {
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost(params[0]);
try {
HttpResponse response = httpclient.execute(httppost);
jsonResult = inputStreamToString(
response.getEntity().getContent()).toString();
}
catch (ClientProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return null;
}
private StringBuilder inputStreamToString(InputStream is) {
String rLine = "";
StringBuilder answer = new StringBuilder();
BufferedReader rd = new BufferedReader(new InputStreamReader(is));
try {
while ((rLine = rd.readLine()) != null) {
answer.append(rLine);
}
}
catch (IOException e) {
// e.printStackTrace();
Toast.makeText(getApplicationContext(),
"Error..." + e.toString(), Toast.LENGTH_LONG).show();
}
return answer;
}
@Override
protected void onPostExecute(String result) {
ListDrwaer();
}
}// end async task
public void accessWebService() {
JsonReadTask task = new JsonReadTask();
// passes values for the urls string array
task.execute(new String[] { url });
}
// build hash set for list view
public void ListDrwaer() {
List<Map<String, String>> employeeList = new ArrayList<Map<String, String>>();
try {
JSONObject jsonResponse = new JSONObject(jsonResult);
JSONArray jsonMainNode = jsonResponse.optJSONArray("emp_info");
for (int i = 0; i < jsonMainNode.length(); i++) {
JSONObject jsonChildNode = jsonMainNode.getJSONObject(i);
String name = jsonChildNode.optString("employee name");
String number = jsonChildNode.optString("employee no");
String outPut = name + "-" + number;
employeeList.add(createEmployee("employees", outPut));
}
} catch (JSONException e) {
Toast.makeText(getApplicationContext(), "Error" + e.toString(),
Toast.LENGTH_SHORT).show();
}
SimpleAdapter simpleAdapter = new SimpleAdapter(this, employeeList,
android.R.layout.simple_list_item_1,
new String[] { "employees" }, new int[] { android.R.id.text1 });
listView.setAdapter(simpleAdapter);
}
private HashMap<String, String> createEmployee(String name, String number) {
HashMap<String, String> employeeNameNo = new HashMap<String, String>();
employeeNameNo.put(name, number);
return employeeNameNo;
}
}
答案 0 :(得分:1)
当localhost工作时,我假设你是从正确托管http://cpriyankara.coolpage.biz/employee_details.php的计算机发出请求的?
localhost表示“我现在正在提出请求的这台机器”。
所以,除非您的Android机器运行的Web服务器可以使用localhost访问名为/employee_details.php的文件,否则无法使用它。
答案 1 :(得分:1)
您可以使用机器IP地址(即10.0.2.2
)访问本地主机,并使用可能为80
或8080
的端口号,并将其添加为http:// 10.0.2.2:8080/
< / p>
要查找您的机器IP地址,请使用ipconfig
请参阅here更多详情
更新
在manifest.xml
中添加互联网权限,有时无法解决问题,然后创建另一个AVD
实例。
答案 2 :(得分:0)