【发布时间】:2013-12-29 15:36:26
【问题描述】:
我正在学习安卓。我正在尝试从 Android 读取 PHP 输出(通过 JSON)。
如果我给出站点 URL,它会获取值。如果您进入该站点,它会显示如下所示的 Json 代码。
http://cpriyankara.coolpage.biz/employee_details.php";
{"emp_info":[{"员工姓名":"Adam","员工编号":"101700"},{"员工姓名":"John","员工编号":"101701"},{ “员工姓名”:“保罗”,“员工编号”:“101702”},{“员工姓名”:“马克”,“员工编号”:“101703”},{“员工姓名”:“唐纳德”,员工编号":"101704"},{"员工姓名":"大脑","员工编号":"101705"},{"员工姓名":"Kevin","员工编号":"101706"}]}
如果我给我的本地主机 PHP 站点,它也以 Json 格式显示,如上所示。 (我正在使用 WAMPSERVER 运行 PHP)
{"emp_info":[{"员工姓名":"Adam","员工编号":"101700"},{"员工姓名":"John","员工编号":"101701"},{ “员工姓名”:“保罗”,“员工编号”:“101702”},{“员工姓名”:“马克”,“员工编号”:“101703”},{“员工姓名”:“唐纳德”,员工编号":"101704"},{"员工姓名":"大脑","员工编号":"101705"},{"员工姓名":"Kevin","员工编号":"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
包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;
}
}
【问题讨论】:
-
如何输入
localhostURL?你在使用移动 OR 模拟器吗? -
我正在使用模拟器。是的,我在地址或 URL 中给了localhost/PHPMYSQL/index.php