Warning: file_get_contents(/data/phpspider/zhask/data//catemap/3/android/235.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Java json中的分析错误_Java_Android_Arrays_Json - Fatal编程技术网

Java json中的分析错误

Java json中的分析错误,java,android,arrays,json,Java,Android,Arrays,Json,当我运行我的应用程序时,出现了以下错误,并且ADV中显示了一个空白页。 我在解析输入时遇到了一个问题: 分析数据org.json.JSONException时出错:无法将类型为java.lang.String的值转换为JSONObject 如果我能得到一些帮助,我将不胜感激 类ListQuest.java 您正在解析的字符串很可能不是您认为的字符串,实际上也不是json。我猜这是某种以“你”开头的信息 在logcat中查找引发异常的行,并将该行与从“”错误解析数据org.JSON.JSONExc

当我运行我的应用程序时,出现了以下错误,并且ADV中显示了一个空白页。 我在解析输入时遇到了一个问题:


分析数据org.json.JSONException时出错:无法将类型为java.lang.String的值转换为JSONObject

如果我能得到一些帮助,我将不胜感激

类ListQuest.java
您正在解析的字符串很可能不是您认为的字符串,实际上也不是json。我猜这是某种以“你”开头的信息

在logcat中查找引发异常的行,并将该行与从“”错误解析数据org.JSON.JSONException返回的预期JSON格式一起发布:类型为java.lang.String的值无法转换为JSONObject。类listquest.php:只是一些关于正确Java编程的注释:您的JSONParser实际上是一个助手函数/类,它使用一个应该是静态的方法从远程位置获取一些JSON数据。此外,静态类属性可能应该是方法中的局部变量。字符串比较
method==“POST”
在Java中不起作用。您必须使用
equals()
方法。@njzk2我打电话给您;)aka:这只是部分正确,请这样读,因为
方法
参数是字符串文字,它确实有效。然而,你指出这一点是对的,因为它很容易引起问题。你能进一步解释一下吗?我认为,无论你使用什么源来获取JSON数据,都会给你带来一些非JSON的东西。例如,它可能会向您发送错误消息。不管是什么,当解析器试图解释它时,它失败了,因为文本字符串不是有效的JSON。@user3597728如果您没有将请求的真实结果添加到问题中,则该结果不包含任何“You”。使用与Java程序中完全相同的参数来获得
listquest.php
的结果。请注意,“您”很可能来自SQL错误消息(通常是“您的SQL语法有错误”),因为PHP脚本使用
die
语言结构将SQL错误直接输出到返回消息体中。生成的回复将不是有效的JSON。我修改了类ListQUest.java,但当我对应用程序进行分级时,JSON的结果显示在logCat中,但在ADV中,我只得到第二个响应
           public class ListQuest extends ListActivity {

// Progress Dialog
private ProgressDialog pDialog;

// Creating JSON Parser object
JSONParser jParser = new JSONParser();

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

              // url to get all products list
                 private static String url_all_quests = 
                      "http://10.0.2.2/android_connect/listquest.php";

// JSON Node names
private static final String TAG_SUCCESS = "success";
private static final String TAG_QUEST = "Question";
private static final String TAG_REP = "Reponse";
private static final String TAG_IDE = "idenq";
private static final String TAG_IDQ = "idquest";
private static final String TAG_LIBQ = "libquest";
private static final String TAG_LIBR = "librep";


// products JSONArray

String idenq;
String idquest;
String libquest,librep;

@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.list_quest);
    Intent i = getIntent();
    idenq = i.getStringExtra(TAG_IDE);
    idquest = i.getStringExtra(TAG_IDQ);


    final CheckBox checkBox = (CheckBox) findViewById(R.id.chkIos);

    // Hashmap for ListView
    questsList = new ArrayList<HashMap<String, String>>();

    // Loading products in Background Thread
    new LoadAllProducts().execute();

    // Get listview
    ListView lv = getListView();

    // on seleting single product
    // launching Edit Product Screen
    lv.setOnItemClickListener(new OnItemClickListener() {

        @Override
        public void onItemClick(AdapterView<?> parent, View view,
                int position, long id) {
            // getting values from selected ListItem
    String idquest = ((TextView) view.findViewById(R.id.idquest)).getText()
                    .toString();

            // Starting new intent
            Intent in = new Intent(getApplicationContext(),
                    test.class);
            // sending pid to next activity
            in.putExtra(TAG_IDQ, idquest);

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

}

// Response from Edit Product Activity
@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 Load all product by making HTTP Request
 * */
class LoadAllProducts extends AsyncTask<String, String, String> {

    /**
     * Before starting background thread Show Progress Dialog
     * */
    @Override
    protected void onPreExecute() {
        super.onPreExecute();
        pDialog = new ProgressDialog(ListQuest.this);
        pDialog.setMessage("Loading products. 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>();
        params.add(new BasicNameValuePair("idenq", idenq));
        params.add(new BasicNameValuePair("idquest", idquest));

        params.add(new BasicNameValuePair("libquest", libquest));

        params.add(new BasicNameValuePair("librep", librep));
        // getting JSON string from URL
    JSONObject json = jParser.makeHttpRequest(url_all_quests, "GET", params);

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

        try {




                // products found
                // Getting Array of Products
                JSONArray  Question = json.getJSONArray(TAG_QUEST);

                // looping through All Products
                for (int i = 0; i < Question.length(); i++) {


                    // creating new HashMap
        HashMap<String, String> map = new HashMap<String, String>();
                    // Storing each json item in variable
                    JSONObject c=Question.getJSONObject(i);
                    String libquest = c.getString(TAG_LIBQ);
                    JSONArray Reponse =c.getJSONArray(TAG_REP);


                    map.put(TAG_LIBQ, libquest);

                    // adding HashList to ArrayList

                    // looping through All Products

                    for (int k =0 ; k < Reponse.length(); k++) {
                        HashMap<String, String> map1 = new
                        HashMap<String, String>();
            JSONObject r=Reponse.getJSONObject(k);
                String librep = r.getString(TAG_LIBR);
                        map.put(TAG_LIBR, librep);

                    }
                    questsList.add(map);
                }


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

        return null;
    }

    /**
     * After completing background task Dismiss the progress dialog
     * **/
    protected void onPostExecute(String file_url) {
        // dismiss the dialog after getting all products
        pDialog.dismiss();
        // updating UI from Background Thread
        runOnUiThread(new Runnable() {
            public void run() {
                /**     
                 * Updating parsed JSON data into ListView
                 * */


                ListAdapter adapter = new SimpleAdapter(
                        ListQuest.this, questsList,
                        R.layout.list_quest, new String[] { 
                                TAG_LIBQ,TAG_LIBR},
                        new int[] {  R.id.libquest ,
                                         R.id.librep});
                // updating listview
                setListAdapter(adapter);



            }
        });

    }

}

}
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) {
                sb.append(line + "\n");

            }
            is.close();
            json = sb.toString().substring(0, sb.toString().length()-1);
        } 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;

    }
}
        {"Question":[{"idquest":"17","libquest":"avez vous visité 
                       tunis?","Reponse":[{"librep":"oui"},{"librep":"non"}]},
             {"idquest":"50","libquest":"quel est votre       spécialité","Reponse":  
              [{"librep":"MP"},{"librep":"PC"}]},{"idquest":"51","libquest":"quel est 
                       votre équipe préféré","Reponse":[]}]}