如何从我的Android应用程序发送一个字符串变量到PHP,然后使用该变量进行查询并将其作为json响应发送?

时间:2013-01-29 12:52:05

标签: php android json phpmyadmin httpwebrequest

我似乎无法让我的android应用程序使用json将字符串变量发送到php,然后使用该变量进行查询,将返回对我的应用程序的json响应。然后我将使用结果创建一个ListView。 在显示进度对话框的部分显示之前,它不会出错 “正在加载产品详情。请稍等......”

我的java课程:

package com.example.androidhive;

import java.io.BufferedReader;
import java.io.IOException; 
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.UnsupportedEncodingException;
import java.util.List;
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.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.client.utils.URLEncodedUtils;
import org.apache.http.impl.client.DefaultHttpClient;
import org.json.JSONException;
import org.json.JSONObject;
import android.util.Log;




public class JSONParser {

static InputStream is = null;
static JSONObject jObj = null;
static String json = "";

// constructor
public JSONParser() {

}

// function get json from url
// by making HTTP POST or GET method
public JSONObject makeHttpRequest(String url, String method,
        List<NameValuePair> params) {

    // Making HTTP request
    try {

        // check for request method
        if(method == "POST"){
            // request method is POST
            // defaultHttpClient
            DefaultHttpClient httpClient = new DefaultHttpClient();
            HttpPost httpPost = new HttpPost(url);
            httpPost.setEntity(new UrlEncodedFormEntity(params));

            HttpResponse httpResponse = httpClient.execute(httpPost);
            HttpEntity httpEntity = httpResponse.getEntity();
            is = httpEntity.getContent();

        }else if(method == "GET"){
            // request method is GET
            DefaultHttpClient httpClient = new DefaultHttpClient();
            String paramString = URLEncodedUtils.format(params, "utf-8");
            url += "?" + paramString;
            HttpGet httpGet = new HttpGet(url);

            HttpResponse httpResponse = httpClient.execute(httpGet);
            HttpEntity httpEntity = httpResponse.getEntity();
            is = httpEntity.getContent();
        }          

    } catch (UnsupportedEncodingException e) {
        e.printStackTrace();
    } catch (ClientProtocolException e) {
        e.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
    }

    try {
        BufferedReader reader = new BufferedReader(new InputStreamReader(
                is, "iso-8859-1"), 8);
        StringBuilder sb = new StringBuilder();
        String line = null;
        while ((line = reader.readLine()) != null) {
            sb.append(line + "\n");
        }
        is.close();
        json = sb.toString();
    } catch (Exception e) {
        Log.e("Buffer Error", "Error converting result " + e.toString());}

    // try parse the string to a JSON object
    try {
        jObj = new JSONObject(json);
    } catch (JSONException e) {
        Log.e("JSON Parser", "Error parsing data " + e.toString());
    }

    // return JSON String
    return jObj;

    }
}

ItemName,Ingredients,Price,Category,userRating是我数据库中的列。

package com.example.androidhive;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import org.apache.http.NameValuePair;
import org.apache.http.message.BasicNameValuePair;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import android.annotation.TargetApi;
import android.app.ListActivity;
import android.app.ProgressDialog;
import android.content.Intent;
import android.graphics.Color;
import android.os.AsyncTask;
import android.os.Build;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ListAdapter;
import android.widget.ListView;
import android.widget.SimpleAdapter;
import android.widget.TextView;
import android.widget.AdapterView.OnItemClickListener;

public class CategoryItems extends ListActivity{

String category;
// products JSONArray
JSONArray categoryItems = null;
// Progress Dialog
private ProgressDialog pDialog;

// JSON parser class
JSONParser jsonParser = new JSONParser();
ArrayList<HashMap<String, String>> categoryItemsList;
// single product url
private static final String url_post_category_items = "http://192.168.1.2/OrderAp_php/get_category_items.php?Category=category";
private static final String url_get_category_items = "http://192.168.1.2/OrderAp_php/get_category_items.php";
// JSON Node names
private static final String TAG_SUCCESS = "success";   
private static final String TAG_PRICE = "Price";
private static final String TAG_ITEMNAME = "ItemName";
private static final String TAG_INGREDIENTS = "Ingredients";
private static final String TAG_CATEGORY = "Category";
private static final String TAG_CATEGORYITEMS = "categoryItems";

@TargetApi(Build.VERSION_CODES.JELLY_BEAN)
@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.layout_category_item_menu);

    Intent i = getIntent();

    // getting category Name from intent
    category = i.getStringExtra(TAG_CATEGORY);

     new SendToPhp().execute();

     // Getting categoryItems in background thread
      new GetCategoryItems().execute();

      // Get listview
      ListView lvc = getListView();
      lvc.setCacheColorHint(Color.TRANSPARENT);

     // on selecting single product
     // launching Edit Product Screen

      lvc.setOnItemClickListener(new OnItemClickListener() {

         @Override
         public void onItemClick(AdapterView<?> parent, View view,
                 int position, long id) {
             // getting values from selected ListItem
             String itemName = ((TextView) view.findViewById(R.id.ci_itemName)).getText()
                     .toString();
             String price = ((TextView) view.findViewById(R.id.ci_price)).getText()
                     .toString();
             String ingredients = ((TextView) view.findViewById(R.id.ci_ingredients)).getText()
                     .toString();
             String category = ((TextView) view.findViewById(R.id.ci_category)).getText()
                     .toString();

             // Starting new intent
             Intent in = new Intent(getApplicationContext(),
                     LiveOrderItem.class);
             // sending to next activity
             in.putExtra(TAG_ITEMNAME, itemName);
             in.putExtra(TAG_PRICE, price);
             in.putExtra(TAG_INGREDIENTS, ingredients);
             in.putExtra(TAG_CATEGORY, category);


             // starting new activity and expecting some response back
             startActivityForResult(in, 100);
         }
     });
} 


@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
    super.onActivityResult(requestCode, resultCode, data);
    // if result code 100
    if (resultCode == 100) {
        // if result code 100 is received
        // means user edited/deleted product
        // reload this screen again
        Intent intent = getIntent();
        finish();
        startActivity(intent);
    }

}
/**
 * Background Async Task to Get complete product details
 * */
class GetCategoryItems extends AsyncTask<String, String, String> {

    /**
     * Before starting background thread Show Progress Dialog
     * */
    @Override
    protected void onPreExecute() {
        super.onPreExecute();
        pDialog = new ProgressDialog(CategoryItems.this);
        pDialog.setMessage("Loading product details. Please wait...");
        pDialog.setIndeterminate(false);
        pDialog.setCancelable(true);
        pDialog.show();
    }

    /**
     * Getting product details in background thread
     * */
    protected String doInBackground(String... params) {

        // updating UI from Background Thread
        runOnUiThread(new Runnable() {
            public void run() {
                // Check for success tag
                int success;

                    // Building Parameters
                    List<NameValuePair> params = new ArrayList<NameValuePair>();

                    // getting product details by making HTTP request
                    // Note that product details url will use GET request
                    JSONObject json = jsonParser.makeHttpRequest(
                            url_get_category_items, "GET", params);

                    // check your log for json response
                    Log.d("category items", json.toString());

                    try {
                    // json success tag
                    success = json.getInt(TAG_SUCCESS);
                    if (success == 1) {
                        // products found
                        // Getting Array of Products
                        categoryItems = json.getJSONArray(TAG_CATEGORYITEMS);
                        for (int i = 0; i < categoryItems.length(); i++) {
                            JSONObject c = categoryItems.getJSONObject(i);

                            // Storing each json item in variable
                            String itemName = c.getString(TAG_ITEMNAME);
                            String price = c.getString(TAG_PRICE);
                            String ingredients = c.getString(TAG_INGREDIENTS);
                            String category= c.getString(TAG_CATEGORY);

                            // creating new HashMap
                            HashMap<String, String> map = new HashMap<String, String>();
                            //HashMap<String, Integer> intMap = new HashMap<String, Integer>();

                            // adding each child node to HashMap key => value
                            map.put(TAG_ITEMNAME, itemName);
                            map.put(TAG_INGREDIENTS, ingredients);
                            map.put(TAG_PRICE, price);
                            map.put(TAG_CATEGORY, category);

                            // adding HashList to ArrayList
                            categoryItemsList.add(map);

                        }
                    }else{
                        // product not found
                    }
                } catch (JSONException e) {
                    e.printStackTrace();
                }
            }
        });

        return null;
    }

    /**
     * After completing background task Dismiss the progress dialog
     * **/
    protected void onPostExecute(String file_url) {
        // dismiss the dialog once got all details
        pDialog.dismiss();
     // updating UI from Background Thread
        runOnUiThread(new Runnable() {
            public void run() {
                /**
                 * Updating parsed JSON data into ListView
                 * */
                ListAdapter adapter = new SimpleAdapter(
                        CategoryItems.this,
                        categoryItemsList,
                        R.layout.category_item_list_item, 

                        new String[] { TAG_ITEMNAME,TAG_PRICE,TAG_INGREDIENTS,TAG_CATEGORY},
                        new int[] { R.id.ci_itemName, R.id.ci_price,R.id.ci_ingredients, R.id.ci_category }
                        );
                // updating listview
                setListAdapter(adapter);
            }
        });
    }
}

/**
 * Background Async Task to  Save product Details
 * */
class SendToPhp extends AsyncTask<String, String, String> {

    /**
     * Before starting background thread Show Progress Dialog
     * */
    @Override
   protected void onPreExecute() {
        super.onPreExecute();
        pDialog = new ProgressDialog(CategoryItems.this);
        pDialog.setIndeterminate(false);
        pDialog.setMessage("sending to php");
        pDialog.setCancelable(true);
        pDialog.show();
    }

    /**
     * Saving product
     * */
    protected String doInBackground(String... args) {

        // sending category name to php
        List<NameValuePair> params = new ArrayList<NameValuePair>();
        params.add(new BasicNameValuePair(TAG_CATEGORY, category));

        // sending modified data through http request
        // Notice that update product url accepts POST method
        JSONObject json = jsonParser.makeHttpRequest(url_post_category_items,
                "POST", params);

        // check json success tag
        try {
            int success = json.getInt(TAG_SUCCESS);

            if (success == 1) {
                // successfully updated
                Intent i = getIntent();
                // send result code 100 to notify about product update
                setResult(100, i);
                finish();
            } else {

            }
        } catch (JSONException e) {
            e.printStackTrace();
        }

        return null;
    }

    /**
     * After completing background task Dismiss the progress dialog
     * **/
    protected void onPostExecute(String file_url) {
        // dismiss the dialog once product updated
        pDialog.dismiss();

        }
    }
}

我的PHP代码:

<?php

/*
 * Following code will list all the products
 * A product is identified by product id (pid)
 */

// array for JSON response
$response = array();
// check for required fields
if (isset($_GET['category'])){
$category = $_GET['category'];


// include db connect class
require_once __DIR__ . '/db_connect.php';

// connecting to db
$db = new DB_CONNECT();

 // get all category items from items table where category is the variable  sent to php
 $result = mysql_query("SELECT * FROM `items` WHERE category = '$category' LIMIT 0, 30 ") or die(mysql_error());

// check for empty result
if (mysql_num_rows($result) > 0) {
// looping through all results
// products node
$response["categoryItems"] = array();

while ($row = mysql_fetch_array($result)) {
    // temp user array
    $item = array();
    $item["ItemName"]    = $row["ItemName"];
$item["Ingredients"] = $row["Ingredients"];
$item["Price"]       = $row["Price"];
$item["Picture"]     = $row["Picture"];
$item["UserRating"]  = $row["UserRating"];
$item["Category"]    = $row["Category"];

// push single product into final response array
    array_push($response["categoryItems"], $item);
}
// success
$response["success"] = 1;

// echoing JSON response
echo json_encode($response);
}else {

}
} else {
// no products found
$response["success"] = 0;
$response["message"] = "No products found";

// echo no users JSON
echo json_encode($response);
}
?>

我已多次查看代码并纠正了许多错误,但我似乎无法使其工作,我是编程的新手,这是我的高级项目

我在'makeHttpRequest'下添加了一个日志,结果如下:     protected String doInBackground(String ... args){

        // sending category name to php
        List<NameValuePair> params = new ArrayList<NameValuePair>();
        params.add(new BasicNameValuePair(TAG_CATEGORY, category));

        // sending modified data through http request
        // Notice that update product url accepts POST method
        JSONObject json = jsonParser.makeHttpRequest(url_post_category_items,
                "POST", params);

        Log.d("category sent ", params.toString());


01-29 17:07:02.330: D/AbsListView(10360): Get MotionRecognitionManager
01-29 17:07:02.400: D/dalvikvm(10360): GC_CONCURRENT freed 1198K, 12% free 14691K/16583K, paused 13ms+14ms, total 46ms
*01-29 17:07:02.450: D/category sent(10360): [Category=Bread in oven]*
01-29 17:07:02.575: D/AndroidRuntime(10360): Shutting down VM
01-29 17:07:02.575: W/dalvikvm(10360): threadid=1: thread exiting with uncaught exception (group=0x4204b2a0)
01-29 17:07:02.585: E/AndroidRuntime(10360): FATAL EXCEPTION: main
01-29 17:07:02.585: E/AndroidRuntime(10360): android.os.NetworkOnMainThreadException
01-29 17:07:02.585: E/AndroidRuntime(10360):    at android.os.StrictMode$AndroidBlockGuardPolicy.onNetwork(StrictMode.java:1118)
01-29 17:07:02.585: E/AndroidRuntime(10360):    at libcore.io.BlockGuardOs.connect(BlockGuardOs.java:84)
01-29 17:07:02.585: E/AndroidRuntime(10360):    at libcore.io.IoBridge.connectErrno(IoBridge.java:127)
01-29 17:07:02.585: E/AndroidRuntime(10360):    at libcore.io.IoBridge.connect(IoBridge.java:112)
01-29 17:07:02.585: E/AndroidRuntime(10360):    at java.net.PlainSocketImpl.connect(PlainSocketImpl.java:192)
01-29 17:07:02.585: E/AndroidRuntime(10360):    at java.net.PlainSocketImpl.connect(PlainSocketImpl.java:459)
01-29 17:07:02.585: E/AndroidRuntime(10360):    at java.net.Socket.connect(Socket.java:842)
01-29 17:07:02.585: E/AndroidRuntime(10360):    at org.apache.http.conn.scheme.PlainSocketFactory.connectSocket(PlainSocketFactory.java:119)
01-29 17:07:02.585: E/AndroidRuntime(10360):    at org.apache.http.impl.conn.DefaultClientConnectionOperator.openConnection(DefaultClientConnectionOperator.java:144)
01-29 17:07:02.585: E/AndroidRuntime(10360):    at org.apache.http.impl.conn.AbstractPoolEntry.open(AbstractPoolEntry.java:164)
01-29 17:07:02.585: E/AndroidRuntime(10360):    at org.apache.http.impl.conn.AbstractPooledConnAdapter.open(AbstractPooledConnAdapter.java:119)
01-29 17:07:02.585: E/AndroidRuntime(10360):    at org.apache.http.impl.client.DefaultRequestDirector.execute(DefaultRequestDirector.java:360)
01-29 17:07:02.585: E/AndroidRuntime(10360):    at org.apache.http.impl.client.AbstractHttpClient.execute(AbstractHttpClient.java:670)
01-29 17:07:02.585: E/AndroidRuntime(10360):    at org.apache.http.impl.client.AbstractHttpClient.execute(AbstractHttpClient.java:509)
01-29 17:07:02.585: E/AndroidRuntime(10360):    at org.apache.http.impl.client.AbstractHttpClient.execute(AbstractHttpClient.java:487)
01-29 17:07:02.585: E/AndroidRuntime(10360):    at com.example.androidhive.JSONParser.makeHttpRequest(JSONParser.java:62)
01-29 17:07:02.585: E/AndroidRuntime(10360):    at com.example.androidhive.CategoryItems$GetCategoryItems$1.run(CategoryItems.java:154)
01-29 17:07:02.585: E/AndroidRuntime(10360):    at android.os.Handler.handleCallback(Handler.java:615)
01-29 17:07:02.585: E/AndroidRuntime(10360):    at android.os.Handler.dispatchMessage(Handler.java:92)
01-29 17:07:02.585: E/AndroidRuntime(10360):    at android.os.Looper.loop(Looper.java:137)
01-29 17:07:02.585: E/AndroidRuntime(10360):    at android.app.ActivityThread.main(ActivityThread.java:4898)
01-29 17:07:02.585: E/AndroidRuntime(10360):    at java.lang.reflect.Method.invokeNative(Native Method)
01-29 17:07:02.585: E/AndroidRuntime(10360):    at java.lang.reflect.Method.invoke(Method.java:511)
01-29 17:07:02.585: E/AndroidRuntime(10360):    at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1006)
01-29 17:07:02.585: E/AndroidRuntime(10360):    at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:773)
01-29 17:07:02.585: E/AndroidRuntime(10360):    at dalvik.system.NativeStart.main(Native Method)
01-29 17:12:11.110: I/Process(10360): Sending signal. PID: 10360 SIG: 9

0 个答案:

没有答案