Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/json/14.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
Android 字符串无法转换为JSONObject_Android_Json - Fatal编程技术网

Android 字符串无法转换为JSONObject

Android 字符串无法转换为JSONObject,android,json,Android,Json,在我的应用程序中,我正在使用从服务器检索数据。服务器代码是用php编写的。 在检索数据时,它会抛出错误,例如字符串不能在JSONObject中转换。 我试过了,但没有找到合适的解决办法 提前谢谢 下面是我的代码 package com.example.isaaa; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import org.apache.http.NameValuePair

在我的应用程序中,我正在使用从服务器检索数据。服务器代码是用php编写的。 在检索数据时,它会抛出错误,例如字符串不能在JSONObject中转换。 我试过了,但没有找到合适的解决办法

提前谢谢

下面是我的代码

package com.example.isaaa;



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

import org.apache.http.NameValuePair;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import android.app.ListActivity;
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.ListAdapter;
import android.widget.SimpleAdapter;

public class Notification extends ListActivity 
{
     // Progress Dialog
    private ProgressDialog pDialog;
     // Creating JSON Parser object
    JSONParser jParser = new JSONParser(); 
    ArrayList<HashMap<String, String>> productsList;

    // url to get all products list
    private static String url_all_products = "http://XYZ/notifications.php";

    // JSON Node names
    private static final String TAG_SUCCESS = "success";
    private static final String TAG_NOTI = "noti";
    private static final String TAG_NOTIFICATION = "title";
    //private static final String TAG_URL = "pdflink";


    // products JSONArray
    JSONArray noti = null;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_notification);

        // Hashmap for ListView
        productsList = 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 pid = ((TextView) view.findViewById(R.id.pid)).getText()
                        .toString();

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

                // 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(Notification.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>();
            // getting JSON string from URL
            JSONObject json = jParser.makeHttpRequest(url_all_products, "GET", params);

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

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

                if (success == 1) {
                    // products found
                    // Getting Array of Products
                    noti = json.getJSONArray(TAG_NOTI);

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

                        // Storing each json item in variable
                        String notification = c.getString(TAG_NOTIFICATION);
                        //String url = c.getString(TAG_URL);

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

                        // adding each child node to HashMap key => value
                        map.put(TAG_NOTIFICATION, notification);
                       // map.put(TAG_URL, url);

                        // adding HashList to ArrayList
                        productsList.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(
                            Notification.this, productsList,
                            R.layout.simple, new String[] {TAG_NOTIFICATION},
                            new int[] { R.id.rowTextView });
                    // updating listview
                    setListAdapter(adapter);
                }
            });

        }
     }


    public void Back(View view)
    {
        Intent intent = new Intent(getApplicationContext(), Dashboard.class);
        startActivity(intent);  
         finish();

    }

}
package com.example.isaaa;
导入java.util.ArrayList;
导入java.util.HashMap;
导入java.util.List;
导入org.apache.http.NameValuePair;
导入org.json.JSONArray;
导入org.json.JSONException;
导入org.json.JSONObject;
导入android.app.ListActivity;
导入android.app.ProgressDialog;
导入android.content.Intent;
导入android.os.AsyncTask;
导入android.os.Bundle;
导入android.util.Log;
导入android.view.view;
导入android.widget.ListAdapter;
导入android.widget.simpledapter;
公共类通知扩展了ListActivity
{
//进度对话框
私人对话;
//创建JSON解析器对象
JSONParser jParser=新的JSONParser();
ArrayList productsList;
//获取所有产品列表的url
私有静态字符串url\u所有产品=”http://XYZ/notifications.php";
//JSON节点名称
私有静态最终字符串标记_SUCCESS=“SUCCESS”;
私有静态最终字符串标记_NOTI=“NOTI”;
私有静态最终字符串TAG_NOTIFICATION=“title”;
//私有静态最终字符串标记\u URL=“pdflink”;
//产品JSONArray
JSONArray noti=null;
@凌驾
创建时的公共void(Bundle savedInstanceState){
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_通知);
//ListView的Hashmap
productsList=新的ArrayList();
//在后台线程中加载产品
新建LoadAllProducts().execute();
//获取列表视图
/*ListView lv=getListView();
//论单产品的选择
//启动编辑产品屏幕
lv.setOnItemClickListener(新的OnItemClickListener(){
@凌驾
public void onItemClick(AdapterView父级、视图、,
内部位置,长id){
//从选定的ListItem获取值
字符串pid=((TextView)view.findViewById(R.id.pid)).getText()
.toString();
//开始新的意图
Intent in=新的Intent(getApplicationContext(),
EditProductActivity.class);
//将pid发送到下一个活动
in.putExtra(标签号PID,PID);
//开始新的活动并期望得到一些响应
startActivityForResult(in,100);
}
});*/
}
//编辑产品活动的响应
@凌驾
受保护的void onActivityResult(int请求代码、int结果代码、意图数据){
super.onActivityResult(请求代码、结果代码、数据);
//如果结果代码为100
如果(结果代码==100){
//如果收到结果代码100
//指用户编辑/删除的产品
//重新加载此屏幕
Intent=getIntent();
完成();
星触觉(意向);
}
}
/**
*通过发出HTTP请求加载所有产品的后台异步任务
* */
类LoadAllProducts扩展了AsyncTask{
/**
*在启动后台线程显示进度对话框之前
* */
@凌驾
受保护的void onPreExecute(){
super.onPreExecute();
pDialog=newprogressdialog(Notification.this);
pDialog.setMessage(“正在加载产品。请稍候…”);
pDialog.setUndeterminate(假);
pDialog.setCancelable(假);
pDialog.show();
}
/**
*从url获取所有产品
* */
受保护的字符串doInBackground(字符串…args){
//建筑参数
List params=new ArrayList();
//从URL获取JSON字符串
JSONObject json=jParser.makeHttpRequest(url_all_products,“GET”,params);
//检查日志cat中的JSON响应
Log.d(“所有产品:,json.toString());
试一试{
//检查成功标签
int success=json.getInt(TAG_success);
如果(成功==1){
//发现的产品
//获取一系列产品
noti=json.getJSONArray(TAG_noti);
//在所有产品中循环
对于(int i=0;ivalue
地图放置(标签通知、通知);
//map.put(TAG_URL,URL);
//将哈希列表添加到ArrayList
productsList.add(地图);
}
} 
}捕获(JSONException e){
e、 printStackTrace();
}
返回null;
}
/**
*完成后台任务后,关闭“进度”对话框
* **/
受保护的void onPostExecute(字符串文件\u url){
//获取所有产品后关闭对话框
pDialog.disclose();
//从后台线程更新UI
runOnUiThread(新的Runnable(){
公开募捐{
/**
*将解析的JSON数据更新到ListView中
* */
ListAdapter=新的SimpleDap
<?php
    $hostname_localhost = "localhost";
    $database_localhost = "aa";
    $username_localhost = "bb";
    $password_localhost = "cc";

    $localhost = mysql_connect($hostname_localhost,$username_localhost,$password_localhost) or trigger_error(mysql_error(),E_USER_ERROR); 
    mysql_select_db($database_localhost, $localhost);

$response = array();


$result = mysql_query("SELECT notify_id,title,pdflink FROM notifications ORDER BY notify_id DESC")

if (mysql_num_rows($result) > 0) {

    $response["noti"] = array();

    while ($row = mysql_fetch_array($result)) {

        $noti = array();
        $noti = array();
        $noti['notify_id'] = $row['notify_id'];
        $noti['title'] = $row['title'];
        $noti['pdflink'] = $row['pdflink'];
         array_push($response["noti"], $noti);
    }

    $response["success"] = 1;
    echo json_encode($response);
} 
?>
package com.example.isaaa;

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 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();
        } 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;

    }
}