1

我的 json 解析器中有以下代码。我尝试从 iso-8859-1 更改为 utf-8。但我总是得到这个错误。我做错了什么?我无法弄清楚我做错了什么。

package com.iwantnew.www;    
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;

    }
}

我已经为我的数据库使用了 mysql。我是使用数据库的 android 新手。帮助PLZ!我的 php 文件如下所示:

<?php

/*
 * Following code will create a new product row
 * All product details are read from HTTP Post Request
 */1

// array for JSON response
$response = array();

// check for required fields
if (isset($_POST['quantity']) && isset($_POST['price']) && isset($_POST['descriptions'])) {

    //$location = $_POST['location'];
    $quantity = $_POST['quantity'];
    $price = $_POST['price'];
    //$productID = $_POST['area'];
    $contact = $_POST['contact'];
    $descriptions = $_POST['descriptions'];

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

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

    // mysql inserting a new row
    $result = mysql_query("INSERT INTO room_tb(quantity, price,description) VALUES('$quantity', '$price','$descriptions')");
    //$result1 = mysql_query("INSERT INTO users(userContactNumber) VALUES('$contact')");

    // check if row inserted or not
    if (($result)/*&& ($result1)*/) {
        // successfully inserted into database
        $response["success"] = 1;
        $response["message"] = "Room added successfully.";

        // echoing JSON response
        echo json_encode($response);
    } else {
        // failed to insert row
        $response["success"] = 0;
        $response["message"] = "Oops! An error occurred.";

        // echoing JSON response
        echo json_encode($response);
    }
} else {
    // required field is missing
    $response["success"] = 0;
    $response["message"] = "Required field(s) is missing";

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

我的 java 文件看起来像这样..我在这里使用了 POST METHod。

package com.iwantnew.www;

import java.util.ArrayList;
import java.util.List;

import org.apache.http.NameValuePair;
import org.apache.http.message.BasicNameValuePair;
import org.json.JSONException;
import org.json.JSONObject;

import android.app.Activity;
import android.app.ProgressDialog;
import android.content.Intent;
import android.os.AsyncTask;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;

public class post_item extends Activity {
    private ProgressDialog pDialog;
    JSONParser jsonParser = new JSONParser();
    Button add_room;
    EditText contact_no;
    EditText no_of_room;
    EditText price_per_room;
    EditText description;

    private static String url_create_product = "http://10.0.2.2/android_iwant/android_add_room.php";

    private static final String TAG_SUCCESS = "success";

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

        //contact_no = (EditText) findViewById(R.id.contact_no);
        no_of_room = (EditText) findViewById(R.id.no_of_room);
        price_per_room = (EditText) findViewById(R.id.price_per_room);
        description = (EditText) findViewById(R.id.description);

        add_room = (Button) findViewById(R.id.add_room);

        add_room.setOnClickListener(new View.OnClickListener() {

            @Override
            public void onClick(View v) {
                // creating new product in background thread
                new add_new_room().execute();
            }
        });
    }
// suru...
    class add_new_room extends AsyncTask<String, String, String> {

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

        /**
         * Creating product
         * */
        protected String doInBackground(String... args) {
            //String contact = contact_no.getText().toString();
            String quantity = no_of_room.getText().toString();
            String price = price_per_room.getText().toString();
            String descriptions = description.getText().toString();

            // Building Parameters
            List<NameValuePair> params = new ArrayList<NameValuePair>();
            //params.add(new BasicNameValuePair("contact", contact));
            params.add(new BasicNameValuePair("quantity", quantity));
            params.add(new BasicNameValuePair("price", price));
            params.add(new BasicNameValuePair("descriptions", descriptions));

            // getting JSON Object
            // Note that create product url accepts POST method
            JSONObject json = jsonParser.makeHttpRequest(url_create_product,
                    "POST", params);

            // check log cat fro response
            Log.d("Create Response", json.toString());

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

                if (success == 1) {
                    // successfully created product
                    Intent i = new Intent(getApplicationContext(), MainActivity.class);
                    startActivity(i);

                    // closing this screen
                    finish();
                } else {
                    // failed to create product
                }
            } 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 done
            pDialog.dismiss();
        }

    }
}

禁用 Twitter Bootstrap 折叠切换

我正在使用 Twitter Boostraps 组件折叠来显示一些字段,这些字段是通过单击另一个字段来完成的。但是,如果我再次单击同一字段,其他字段将再次隐藏(即切换)。

我想要的是禁用切换,以便在第二次单击该字段时字段不会隐藏。这可以通过一些内置方法轻松完成,还是我需要深入研究 js 文件来自己更改它?

4

3 回答 3

3

Blackbelt 和 Nizam 涵盖了您的问题的 Java 方面。我将介绍 PHP 方面。

您的 PHP 脚本中最大的错误似乎如下(除非它只是复制和粘贴错误):

<?php

/*
 * Following code will create a new product row
 * All product details are read from HTTP Post Request
 */1
   ^
   |
  The number 1 does not belong here

您的 PHP 脚本可能只是中止并显示语法错误消息,而不是 JSON 字符串输出。

最重要的是,您的 PHP 脚本中存在 SQL 注入漏洞。了解如何使用准备好的语句。

编辑:我在您的 PHP 脚本中发现的另一个错误:

if (isset($_POST['quantity']) && isset($_POST['price']) && isset($_POST['descriptions'])) {

您检查是否设置了 POST 参数“说明”。它应该是最后没有's'的“描述”。

于 2013-08-20T15:08:29.033 回答
2

首先,将其if(method.equalsIgnoreCase("post"))设为“黑带”建议。还有一个建议——

在从服务器接收一些文本(无论是否为 JSON)时,我更喜欢在对其执行任何操作之前始终检查响应。

来,试试

HttpEntity httpEntity=httpResponse.getEntity();
String all=EntityUtils.toString(httpEntity);
 Log.d("response",all);
于 2013-08-20T14:56:32.113 回答
2

大多数情况下,您的错误在于:

if(method == "POST"){
 }else if(method == "GET")

java中的字符串比较必须使用equalsorequalsIgnoreCase方法。在您的情况下, InputStreamis为空,并且永远不会初始化。因此,您正在尝试将StringBuilder.toString()返回的空字符串转换为JSONObject.

编辑:

改变

if(method == "POST"){
 }else if(method == "GET")

if(method.equalsIgnoreCase("POST")){
 // your code
 }else if(method.equalsIgnoreCase("GET"))
 // your code

看看它是否有任何区别(至少错误应该改变)

于 2013-08-20T14:43:48.763 回答