将数据从android传递到php以显示在listview中

时间:2014-08-25 07:24:30

标签: php android json listview

这是我的列表视图的活动

    @Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.layout_listview);

    Bundle b = getIntent().getExtras();
    categ = b.getString("category_name");

    new ProgressTask(ListDataActivity.this).execute();

}

class ProgressTask extends AsyncTask<String, Void, Boolean> {

    ArrayList<HashMap<String, String>> jsonlist = new ArrayList<HashMap<String, String>>();

    ConnectivityManager conMgr = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
    {
        if (conMgr.getActiveNetworkInfo() != null
                && conMgr.getActiveNetworkInfo().isAvailable()
                && conMgr.getActiveNetworkInfo().isConnected()) {
        } else {
            Toast.makeText(getApplicationContext(),
                    "INTERNET CONNECTION NOT PRESENT", Toast.LENGTH_SHORT)
                    .show();
            startActivity(new Intent(ListDataActivity.this,
                    MainActivity.class));
        }

    }

    // private List<Message> messages;
    public ProgressTask(ListActivity activity) {
        context = activity;
    }

    private Context context;

    protected void onPreExecute() {
    }

    @Override
    protected void onPostExecute(final Boolean success) {
        ListAdapter adapter = new SimpleAdapter(context, jsonlist,
                R.layout.row_listitem, new String[] { name, Category },
                new int[] { R.id.vehicleType, R.id.vehicleColor }) {

            @Override
            public View getView(int position, View convertView,
                    ViewGroup parent) {

                if (convertView == null) {

                    // This a new view we inflate the new layout

                    LayoutInflater inflater = (LayoutInflater) context
                            .getSystemService(Context.LAYOUT_INFLATER_SERVICE);

                    convertView = inflater.inflate(R.layout.row_listitem,
                            null);
                }

                // TODO Auto-generated method stub
                if (position % 2 == 1) {

                    convertView.setBackgroundColor(Color.rgb(120, 151, 66));
                } else {
                    convertView.setBackgroundColor(Color.rgb(86, 107, 129));
                }
                return super.getView(position, convertView, parent);
            }
        };

        setListAdapter(adapter);

        lv = getListView();

        lv.setOnItemClickListener(new OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view,
                    int position, long id) {

                @SuppressWarnings("unchecked")
                HashMap<String, String> map = (HashMap<String, String>) lv
                        .getItemAtPosition(position);
                String name = map.get("name");
                Intent intent = new Intent(ListDataActivity.this,
                        DataViewActivity.class);
                intent.putExtra("itemName", name);
                startActivity(intent);
            }
        });
    }

    protected Boolean doInBackground(final String... args) {

        baseAdapter jParser = new baseAdapter();

        ArrayList<NameValuePair> postParameters = new ArrayList<NameValuePair>();
        // define the parameter
        postParameters.add(new BasicNameValuePair("787", categ));
        try {
            CustomHttpClient.executeHttpGet("787");
        } catch (Exception e1) {
            // TODO Auto-generated catch block
            e1.printStackTrace();
        } // get JSON data from URL
        url = url + postParameters;
        JSONArray json = jParser.getJSONFromUrl(url);

        if (json != null) {
            for (int i = 0; i < json.length(); i++) {

                try {
                    JSONObject c = json.getJSONObject(i);

                    String vtype = c.getString(name);
                    String vfuel = c.getString(Category);

                    HashMap<String, String> map = new HashMap<String, String>();

                    // Add child node to HashMap key & value
                    map.put(name, vtype);
                    map.put(Category, vfuel);

                    jsonlist.add(map);
                } catch (JSONException e) {
                    e.printStackTrace();
                }
            }
        }
        return null;

    }
}

baseAdapter类

public class baseAdapter {

static InputStream iStream = null;
static JSONArray jarray = null;
static String json = "";

public baseAdapter() {
}

public JSONArray getJSONFromUrl(String url) {

    StringBuilder builder = new StringBuilder();
    HttpClient client = new DefaultHttpClient();
    HttpGet httpGet = new HttpGet(url);
    try {
        HttpResponse response = client.execute(httpGet);
        StatusLine statusLine = response.getStatusLine();
        int statusCode = statusLine.getStatusCode();
        if (statusCode == 200) {
            HttpEntity entity = response.getEntity();
            InputStream content = entity.getContent();
            BufferedReader reader = new BufferedReader(
                    new InputStreamReader(content));
            String line;
            while ((line = reader.readLine()) != null) {
                builder.append(line);
            }
        } else {
            Log.e("==>", "Failed to download file");
        }
    } catch (ClientProtocolException e) {
        e.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
    }

    // Parse String to JSON object
    try {
        jarray = new JSONArray(builder.toString());
    } catch (JSONException e) {
        Log.e("JSON Parser", "Error parsing data " + e.toString());
    }

    // return JSON Object
    return jarray;

}

这是我的PHP代码 PHP:

if(isset($_POST['787'])){
$id = $_POST['787'];

$sql = "SELECT * FROM hospitals_data where Category='$id'";
$result = mysql_query($sql);
while($row=mysql_fetch_assoc($result))
$output[]=$row;
print(json_encode($output));
mysql_close();   
}

logcat的:

08-25 13:06:57.085: W/System.err(13843): java.lang.IllegalStateException: Target host must not be null, or set in parameters. scheme=null, host=null, path=787
08-25 13:06:57.085: W/System.err(13843):    at org.apache.http.impl.client.DefaultRequestDirector.determineRoute(DefaultRequestDirector.java:591)
08-25 13:06:57.085: W/System.err(13843):    at org.apache.http.impl.client.DefaultRequestDirector.execute(DefaultRequestDirector.java:293)
08-25 13:06:57.085: W/System.err(13843):    at org.apache.http.impl.client.AbstractHttpClient.execute(AbstractHttpClient.java:591)
08-25 13:06:57.085: W/System.err(13843):    at org.apache.http.impl.client.AbstractHttpClient.execute(AbstractHttpClient.java:510)
08-25 13:06:57.085: W/System.err(13843):    at org.apache.http.impl.client.AbstractHttpClient.execute(AbstractHttpClient.java:488)
08-25 13:06:57.085: W/System.err(13843):    at com.example.careandcure.CustomHttpClient.executeHttpGet(CustomHttpClient.java:158)
08-25 13:06:57.085: W/System.err(13843):    at com.example.careandcure.ListDataActivity$ProgressTask.doInBackground(ListDataActivity.java:143)
08-25 13:06:57.085: W/System.err(13843):    at com.example.careandcure.ListDataActivity$ProgressTask.doInBackground(ListDataActivity.java:1)
08-25 13:06:57.085: W/System.err(13843):    at android.os.AsyncTask$2.call(AsyncTask.java:264)
08-25 13:06:57.085: W/System.err(13843):    at java.util.concurrent.FutureTask$Sync.innerRun(FutureTask.java:305) 
08-25 13:06:57.085: W/System.err(13843):    at java.util.concurrent.FutureTask.run(FutureTask.java:137)
08-25 13:06:57.085: W/System.err(13843):    at android.os.AsyncTask$SerialExecutor$1.run(AsyncTask.java:208)
08-25 13:06:57.085: W/System.err(13843):    at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1076)
08-25 13:06:57.095: W/System.err(13843):    at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:569)
08-25 13:06:57.095: W/System.err(13843):    at java.lang.Thread.run(Thread.java:864)
08-25 13:06:57.095: W/dalvikvm(13843): threadid=11: thread exiting with uncaught exception (group=0x40aa8228)
08-25 13:06:57.105: E/AndroidRuntime(13843): FATAL EXCEPTION: AsyncTask #1
08-25 13:06:57.105: E/AndroidRuntime(13843): java.lang.RuntimeException: An error occured while executing doInBackground() 
08-25 13:06:57.105: E/AndroidRuntime(13843):    at android.os.AsyncTask$3.done(AsyncTask.java:278)
08-25 13:06:57.105: E/AndroidRuntime(13843): Caused by: java.lang.IllegalArgumentException: Illegal character in path at index 34:    http://172.16.0.118/jsonscript.php[787=general]
08-25 13:06:57.105: E/AndroidRuntime(13843):    at java.net.URI.create(URI.java:727)
08-25 13:06:57.105: E/AndroidRuntime(13843):    at org.apache.http.client.methods.HttpGet.<init>(HttpGet.java:75)
08-25 13:06:57.105: E/AndroidRuntime(13843):    at com.example.careandcure.baseAdapter.getJSONFromUrl(baseAdapter.java:33)
08-25 13:06:57.105: E/AndroidRuntime(13843):    at com.example.careandcure.ListDataActivity$ProgressTask.doInBackground(ListDataActivity.java:149)
08-25 13:06:57.105: E/AndroidRuntime(13843):    at com.example.careandcure.ListDataActivity$ProgressTask.doInBackground(ListDataActivity.java:1)
08-25 13:06:57.105: E/AndroidRuntime(13843):    at android.os.AsyncTask$2.call(AsyncTask.java:264)
08-25 13:06:57.105: E/AndroidRuntime(13843):    at java.util.concurrent.FutureTask$Sync.innerRun(FutureTask.java:305)

我从之前的活动中获得字符串category_name。 我需要解析这个字符串到PHP,以便我可以查询字符串基础上的项目.. 尝试通过添加parm传递这种方式,但提前得到错误.. thanx ..

1 个答案:

答案 0 :(得分:0)

此解决方案基于您的旧代码,没有postParameters

好的,这就是你需要做的事情

1-将类别声明为活动中的全局变量

String categ  = "";
@Override
protected void onCreate(Bundle savedInstanceState) {
:
:

2-保持代码以分配类别categ = b.getString("category_name");

的值

3- at doInBackground(),将新的param category_name连接到URL:

protected Boolean doInBackground(final String... args) {
      url = url + "?cat_name=" + categ;
:
:
:
在您的PHP页面(您使用网址调用的页面)中,阅读参数cat_name并使用它来获取数据

:
:
$catName = $_GET['cat_name'];
:
:

如果我找对你,这就是你要找的。