Android-从mysql到listview检索数据

时间:2015-12-19 10:02:14

标签: php android mysql json listview

我遇到下面代码的问题,我从中得到了它 http://codeoncloud.blogspot.com/2013/07/android-mysql-php-json-tutorial.html 我无法获取列表视图,屏幕只显示文本视图。

MainActivity.java

import android.app.Activity;
import android.os.AsyncTask;
import android.os.Bundle;
import android.widget.ListView;
import android.widget.SimpleAdapter;
import android.widget.Toast;

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 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;

public class MainActivity extends Activity {
    private String jsonResult;
    private String url = "http://192.168.100.5/connect1.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) {
            ListDrawer();
        }
    }// 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 ListDrawer() {
        List<Map<String, String>> employeeList = new ArrayList<Map<String, String>>();

        try {
            JSONObject jsonResponse = new JSONObject(jsonResult);
            JSONArray jsonMainNode = jsonResponse.optJSONArray("trial");

            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(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;
    }
}

activity_main.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="Employees" />
    </TableRow>
    <ListView
        android:id="@+id/listView1"
        android:layout_width="match_parent"
        android:layout_height="328dp"
        >
    </ListView>
</LinearLayout>

connect1.php

<?php
$host="localhost"; //replace with database hostname 
$username="root"; //replace with database username 
$password=""; //replace with database password 
$db_name="db"; //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 trial"; 
$result = mysql_query($sql);
$json = array();

if(mysql_num_rows($result)){
while($row=mysql_fetch_assoc($result)){
$json['trial'][]=$row;
}
}
mysql_close($con);
echo json_encode($json); 
?> 

数据库(Wampp服务器)结构

enter image description here

有人可以帮我检索数据吗?

logcat的

12-23 18:30:58.772 2484-2484/nundloll.myapplication I/art: Not late-enabling -Xcheck:jni (already on)
12-23 18:30:58.773 2484-2484/nundloll.myapplication I/art: Late-enabling JIT
12-23 18:30:58.783 2484-2484/nundloll.myapplication I/art: JIT created with code_cache_capacity=2MB compile_threshold=1000
12-23 18:30:58.919 2484-2484/nundloll.myapplication W/System: ClassLoader referenced unknown path: /data/app/nundloll.myapplication-3/lib/x86
12-23 18:30:59.013 2484-2499/nundloll.myapplication D/OpenGLRenderer: Use EGL_SWAP_BEHAVIOR_PRESERVED: true
12-23 18:30:59.019 2484-2484/nundloll.myapplication D/: HostConnection::get() New Host Connection established 0xab77f890, tid 2484
12-23 18:30:59.083 2484-2499/nundloll.myapplication D/: HostConnection::get() New Host Connection established 0xab77f940, tid 2499
12-23 18:30:59.110 2484-2499/nundloll.myapplication I/OpenGLRenderer: Initialized EGL, version 1.4
12-23 18:30:59.294 2484-2499/nundloll.myapplication W/EGL_emulation: eglSurfaceAttrib not implemented
12-23 18:30:59.294 2484-2499/nundloll.myapplication W/OpenGLRenderer: Failed to set EGL_SWAP_BEHAVIOR on surface 0xabdbeb20, error=EGL_SUCCESS
12-23 18:31:00.594 2484-2491/nundloll.myapplication W/art: Suspending all threads took: 81.126ms
12-23 18:31:01.065 2484-2491/nundloll.myapplication W/art: Suspending all threads took: 53.291ms
12-23 18:31:01.774 2484-2491/nundloll.myapplication W/art: Suspending all threads took: 266.747ms
12-23 18:31:02.479 2484-2491/nundloll.myapplication W/art: Suspending all threads took: 27.278ms
12-23 18:31:02.789 2484-2499/nundloll.myapplication W/EGL_emulation: eglSurfaceAttrib not implemented
12-23 18:31:02.789 2484-2499/nundloll.myapplication W/OpenGLRenderer: Failed to set EGL_SWAP_BEHAVIOR on surface 0xabdbf2a0, error=EGL_SUCCESS
12-23 18:31:04.595 2484-2499/nundloll.myapplication E/Surface: getSlotFromBufferLocked: unknown buffer: 0xab7599d0
12-23 18:31:07.471 2484-2491/nundloll.myapplication W/art: Suspending all threads took: 14.072ms
12-23 18:31:13.448 2484-2491/nundloll.myapplication W/art: Suspending all threads took: 11.590ms

0 个答案:

没有答案