如何在android中使用php和mysql将远程数据库中的数据显示到listview中?

时间:2014-11-12 07:13:46

标签: php android mysql json listview

您好我是Android的新手,目前我正在开发一个连接到远程数据库的Android应用程序,获取数据并在列表视图中显示它。问题是,在运行应用程序时,它只显示一个简单的列表视图,但它不显示任何数据。请帮帮我。我不知道问题究竟在哪里。即使是logcat也没有显示任何错误。我正在使用xampp将我的机器作为本地服务器运行而对于ip我已经给了我的ipaddress。提前致谢 这是我的Java类

1.News.Java

package com.augustasoftsol.gmoapp;
//importing all the necessary packages...
import android.os.AsyncTask;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.webkit.WebView.FindListener;
import android.widget.Button;
import android.widget.ImageButton;
import android.app.Activity;
import android.app.ProgressDialog;
import android.content.Intent;

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.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import android.support.v4.app.Fragment;  
import android.view.LayoutInflater;  
import android.view.View;  
import android.view.ViewGroup; 
import android.os.StrictMode;



import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;


import android.widget.ListAdapter;
import android.widget.ListView;
import android.widget.SimpleAdapter;
import android.widget.TextView;
import android.widget.Toast;
public class News extends Fragment
{  
private String jsonResult;
 private final String url = "http://myipaddress/GMO/getemp.php";
 private ListView listView;


@Override  
 public View onCreateView(LayoutInflater inflater, ViewGroup container,  
           Bundle savedInstanceState) 
{  

     View rootView = inflater.inflate(R.layout.news,container,false);


     return rootView;  
 }
@Override
public void onActivityCreated(Bundle savedInstanceState) 
{
    // TODO Auto-generated method stub

    super.onActivityCreated(savedInstanceState);

     listView = (ListView)getView().findViewById(R.id.listView1);
     accessWebService();

}
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(getActivity(),
          "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();
        task.execute(new String[]{url});
    }

     // build hash set for list view
     public void ListDrwaer() {
      List<Map<String, String>> employeeList = new ArrayList<Map<String, String>>();
     String[] emp = {"employee"};
     int[] id = {android.R.id.text1};
      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.getString("employee name");
        String number = jsonChildNode.getString("employee no");
        String outPut = name + "-" + number;
        employeeList.add(createEmployee("employees", outPut));
       }
      } catch (JSONException e) {
       Toast.makeText(getActivity(), "Error" + e.toString(),
         Toast.LENGTH_SHORT).show();
      }

      SimpleAdapter simpleAdapter = new SimpleAdapter(getActivity(), employeeList, android.R.layout.simple_list_item_1,emp ,id);
      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;
    }
    }
  1. getemp.php:

      <?php
      $host="localhost"; //replace with database hostname
      $username="myusername"; //replace with database username
      $password="mypwd"; //replace with database password
      $db_name="gmo"; //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);
      ?>
    
  2. news.xml

       <?xml version="1.0" encoding="utf-8"?>
       <RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
       android:layout_width="match_parent"
       android:layout_height="match_parent"
       android:background="#ffffff"
       android:orientation="vertical" >
    
       <ListView
       android:id="@+id/listView1"
       android:layout_width="match_parent"
       android:layout_height="wrap_content"
       android:layout_alignParentLeft="true"
       android:layout_below="@+id/searchit"
       android:layout_marginTop="24dp" >
       </ListView>
    
      </RelativeLayout>
    

1 个答案:

答案 0 :(得分:0)

我认为问题出在你的PHP代码中,因为它与表属性不匹配。 尝试在php和java代码中正确匹配表的coloumn名称。希望你的问题能解决。