MySQL查询从Android应用程序到远程数据库

时间:2015-05-25 01:05:36

标签: java php android mysql json

我想在远程数据库上执行以下php查询

$result = mysqli_query($con->myconn, "SELECT id, stake, user, returns, teams, status FROM `bet` WHERE user = $user") or die(mysql_error());

我唯一的问题是我不确定如何修改我的JSONParser类,以便我可以同时将user参数传递给数据库并接收结果。它目前看起来像这样,只允许我检索值或发送值。

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 mehtod


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) {

            if (!line.startsWith("<", 0)) {
                if (!line.startsWith("(", 0)) {
                    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;
   }
}

代码:

 public class DisplayAllBets extends ActionBarActivity {
private String user1 = "user";
private static String url_all_games =      "***";
JSONParser jParser = new JSONParser();
private static final String TAG_SUCCESS = "success";
private static final String TAG_GAMELIST = "gamelist";
private static final String TAG_ID = "id";
private static final String TAG_STAKE = "stake";
private static final String TAG_RETURNS = "returns";
private static final String TAG_TEAMS = "teams";
private static final String TAG_STATUS = "status";
JSONArray allgames = null;
private ProgressDialog pDialog;


@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_display_all_bets);
    // Hashmap for ListView
    ArrayList<HashMap<String, String>> gamesList = new ArrayList<HashMap<String, String>>();

    // Loading products in Background Thread
    class LoadAllGames extends AsyncTask<String, String, String> {
        private String id;
        private String stake;
        private String user;
        private String returns;
        private String teams;
        private String status;

        */
       /**
         * Before starting background thread Show Progress Dialog
         *//*

        @Override
        protected void onPreExecute() {
            super.onPreExecute();
            pDialog = new ProgressDialog(DisplayAllBets.this);
            pDialog.setMessage("Loading Bets. Please wait...");
            pDialog.setIndeterminate(false);
            pDialog.setCancelable(false);
            pDialog.show();
        }

        */
        /**
         * getting All products from url
         *//*

        protected String doInBackground(String... args) {
            // Building Parameters
            List<NameValuePair> params = new ArrayList<NameValuePair>();
            // getting JSON string from URL
            JSONObject json = jParser.makeHttpRequest(url_all_games, "GET", params);

            // Check your log cat for JSON reponse
            Log.d("All Games: ", json.toString());

            try {
                // Checking for SUCCESS TAG
                int success = json.getInt(TAG_SUCCESS);

                if (success == 1) {
                    // products found
                    // Getting Array of Games
                    allgames = json.getJSONArray(TAG_GAMELIST);

                    // looping through All Products
                    for (int i = 0; i < allgames.length(); i++) {
                        JSONObject c = allgames.getJSONObject(i);

                        // Storing each json item in variable
                        id = c.getString(TAG_ID);
                        stake = c.getString(TAG_STAKE);
                        returns = c.getString(TAG_RETURNS);
                        status = c.getString(TAG_STATUS);
                        teams = c.getString(TAG_TEAMS);;



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

                        // adding each child node to HashMap key => value
                        map.put(TAG_ID, id);
                        map.put(TAG_TEAMS, teams);
                        map.put(TAG_STAKE, stake);
                        map.put(TAG_RETURNS, returns);
                        map.put(TAG_STATUS, status);


                        // adding HashList to ArrayList
                        gamesList.add(map);
                    }
                    //  } else {
                    // no products found
                    // Launch Add New product Activity
                    //      Intent i = new Intent(getApplicationContext(),
                    //             NewProductActivity.class);
                    // Closing all previous activities
                    //     i.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
                    //      startActivity(i);
                }
            } catch (JSONException e) {
                e.printStackTrace();
            }

            return "";
        }

0 个答案:

没有答案