从MySQL数据库使用JSON和PHP读取数据到ListView控件 [英] Fetching data from Mysql DB to listView using JSON and PHP
本文介绍了从MySQL数据库使用JSON和PHP读取数据到ListView控件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我想获取Android中的ListView从MySQL数据库的数据。但不知何故,我没能显示在列表视图中的数据。
我试图用这个教程,即的 HTTP://$c$concloud.blogspot.in/2013/07/android-mysql-php-json-tutorial.html
下面是我的MainActivity.java
公共类MainActivity延伸活动{
私人字符串jsonResult;
私人字符串URL =http://10.0.2.2/markit/login.php;
私人的ListView ListView的;
私人TextView的textv1;
@覆盖
保护无效的onCreate(包savedInstanceState){
super.onCreate(savedInstanceState);
的setContentView(R.layout.activity_main);
ListView的=(的ListView)findViewById(R.id.listView1);
textv1 =(TextView中)findViewById(R.id.textView1);
accessWebService();
}
@覆盖
公共布尔onCreateOptionsMenu(功能菜单){
//充气菜单;这增加了项目操作栏,如果它是present。
。getMenuInflater()膨胀(R.menu.main,菜单);
返回true;
}
//异步任务来访问网络
私有类JsonReadTask扩展的AsyncTask<字符串,太虚,字符串> {
@覆盖
保护字符串doInBackground(字符串... PARAMS){
HttpClient的HttpClient的=新DefaultHttpClient();
HttpPost httppost =新HttpPost(PARAMS [0]);
尝试 {
HTT presponse响应= httpclient.execute(httppost);
jsonResult = inputStreamToString(
。response.getEntity()的getContent())的toString()。
}
赶上(ClientProtocolException E){
e.printStackTrace();
}赶上(IOException异常E){
e.printStackTrace();
}
返回null;
}
私人的StringBuilder inputStreamToString(InputStream的是){
字符串rLine =;
StringBuilder的答案=新的StringBuilder();
的BufferedReader RD =新的BufferedReader(新InputStreamReader的(是));
尝试 {
而((rLine = rd.readLine())!= NULL){
answer.append(rLine);
}
}
赶上(IOException异常E){
// e.printStackTrace();
Toast.makeText(getApplicationContext(),
错误......+ e.toString(),Toast.LENGTH_LONG).show();
}
返回的答案;
}
@覆盖
保护无效onPostExecute(字符串结果){
ListDrwaer();
}
} //结束异步任务
公共无效accessWebService(){
JsonReadTask任务=新JsonReadTask();
//通行证的网址字符串数组值
task.execute(新的String [] {URL});
}
//构建列表视图哈希集合
公共无效ListDrwaer(){
列表与LT;地图<字符串,字符串>> EmployeeList的=新的ArrayList<地图<字符串,字符串>>();
尝试 {
JSONObject的jsonResponse =新的JSONObject(jsonResult);
JSONArray jsonMainNode = jsonResponse.optJSONArray(emp_info);
的for(int i = 0; I< jsonMainNode.length();我++){
的JSONObject jsonChildNode = jsonMainNode.getJSONObject(ⅰ);
字符串名称= jsonChildNode.optString(employee_name);
串号= jsonChildNode.optString(employee_no);
字符串输出=名+ - +数字;
//textv1.setText(name);
//textv1.setText(jsonResult);
employeeList.add(createEmployee(员工,输出));
}
}赶上(JSONException E){
Toast.makeText(getApplicationContext(),错误+ e.toString()
Toast.LENGTH_SHORT).show();
}
SimpleAdapter simpleAdapter =新SimpleAdapter(这一点,EmployeeList的,
android.R.layout.simple_list_item_1,
新的String [] {员工},新的INT [] {android.R.id.text1});
listView.setAdapter(simpleAdapter);
}
私人的HashMap<字符串,字符串> createEmployee(字符串名称,串号){
HashMap的<字符串,字符串> employeeNameNo =新的HashMap<字符串,字符串>();
employeeNameNo.put(姓名,号码);
返回employeeNameNo;
}
}
下面是mainactivity.xml
< LinearLayout中的xmlns:机器人=http://schemas.android.com/apk/res/android
的xmlns:工具=http://schemas.android.com/tools
机器人:layout_width =match_parent
机器人:layout_height =match_parent
机器人:paddingBottom会=@扪/ activity_vertical_margin
机器人:以下属性来=@扪/ activity_horizontal_margin
机器人:paddingRight =@扪/ activity_horizontal_margin
机器人:paddingTop =@扪/ activity_vertical_margin
工具:上下文=MainActivity。>
<的TableRow
机器人:ID =@ + ID / tableRow1
机器人:layout_width =WRAP_CONTENT
机器人:layout_height =WRAP_CONTENT>
<的TextView
机器人:ID =@ + ID / textView1
机器人:layout_width =WRAP_CONTENT
机器人:layout_height =WRAP_CONTENT
机器人:文本=TextView的/>
< /的TableRow>
<的ListView
机器人:ID =@ + ID / ListView1的
机器人:layout_width =match_parent
机器人:layout_height =WRAP_CONTENT
>
< / ListView控件>
< / LinearLayout中>
的login.php
< PHP
$主机=localhost的; //替换数据库主机名
$用户名=根; //更换数据库用户名
$密码=; //替换数据库密码
$ DB_NAME =麦盖提; //替换数据库名称
$ CON =的mysql_connect(localhost的根,)或死亡(无法连接);
mysql_select_db(麦盖提)或死亡(无法选择数据库);
$的SQL =选择emp_info *;
$结果= mysql_query($ SQL);
$ JSON =阵列();
如果(mysql_num_rows($结果)){
而($行= mysql_fetch_assoc($结果)){
$ JSON ['emp_info'] [] = $行;
}
}
则mysql_close($ CON);
回声json_en code($ JSON);
?>
解决方案
更改此
字符串名称= jsonChildNode.optString(employee_name);
串号= jsonChildNode.optString(employee_no);
到
字符串名称= jsonChildNode.getString(EMP_NAME);
串号= jsonChildNode.getString(EMP_NO);
I am trying to fetch data from mysql DB in android listview. But somehow I am not been able to display the data in the listView
I was trying this with the help of a tutorial,i.e., http://codeoncloud.blogspot.in/2013/07/android-mysql-php-json-tutorial.html
Below is my MainActivity.java
public class MainActivity extends Activity {
private String jsonResult;
private String url = "http://10.0.2.2/markit/login.php";
private ListView listView;
private TextView textv1;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
listView = (ListView) findViewById(R.id.listView1);
textv1=(TextView)findViewById(R.id.textView1);
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;
//textv1.setText(name);
//textv1.setText(jsonResult);
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;
}
}
Below is mainactivity.xml
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:paddingBottom="@dimen/activity_vertical_margin"
android:paddingLeft="@dimen/activity_horizontal_margin"
android:paddingRight="@dimen/activity_horizontal_margin"
android:paddingTop="@dimen/activity_vertical_margin"
tools:context=".MainActivity" >
<TableRow
android:id="@+id/tableRow1"
android:layout_width="wrap_content"
android:layout_height="wrap_content" >
<TextView
android:id="@+id/textView1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="TextView" />
</TableRow>
<ListView
android:id="@+id/listView1"
android:layout_width="match_parent"
android:layout_height="wrap_content"
>
</ListView>
</LinearLayout>
Login.php
<?php
$host="localhost"; //replace with database hostname
$username="root"; //replace with database username
$password=""; //replace with database password
$db_name="markit"; //replace with database name
$con=mysql_connect("localhost", "root", "")or die("cannot connect");
mysql_select_db("markit")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);
?>
解决方案
Change this
String name = jsonChildNode.optString("employee_name");
String number = jsonChildNode.optString("employee_no");
to
String name = jsonChildNode.getString("emp_name");
String number = jsonChildNode.getString("emp_no");
这篇关于从MySQL数据库使用JSON和PHP读取数据到ListView控件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文