Android:JSON解析错误没有出现

时间:2016-05-19 14:08:39

标签: java android json mobile

我正在尝试解析JSON,我之前已经在那里完成了,但这种方式并不安静。我花了好几个小时试图解决问题,但我不知道代码有什么问题。我附加了活动,Web请求类和布局的整个代码。任何帮助将不胜感激。

我收到此错误

java.io.FileNotFoundException: /data/system/users/sdp_engine_list.xml: open failed: ENOENT (No such file or directory)
05-19 18:17:27.427 3450-3450/? W/System.err: Caused by: android.system.ErrnoException: open failed: ENOENT (No such file or directory)
05-19 18:17:28.232 3450-3592/? W/DisplayManagerService: Failed to notify process 20004 that displays changed, assuming it died.

这是活动交易类。

import android.app.ListActivity;
import android.app.ProgressDialog;
import android.os.AsyncTask;
import android.os.Bundle;
import android.util.Log;
import android.widget.ListAdapter;
import android.widget.SimpleAdapter;

import com.rectuca.iyzicodemo.Classes.Transaction;
import com.rectuca.iyzicodemo.Library.WebRequest;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

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


    public class Transactions extends ListActivity {

        // URL to get contacts JSON
        private static String url = "http://www.mocky.io/v2/573dbd243700005f194dcdcc";

        // JSON Node names
        private static final String TAG_PAYMENTS= "payments";
        private static final String TAG_PAYMENT_ID = "paymentId";
        private static final String TAG_SENT_BY = "sentBy";
        private static final String TAG_DATE_TIME = "dateTime";
        private static final String TAG_SENT_TO = "sentTo";
        private static final String TAG_BANK_NAME = "bankName";
        private static final String TAG_INSTALLMENTS = "installments";
        private static final String TAG_AMOUNT = "amount";
        private static final String TAG_3DS = "threeDs";
        private static final String TAG_CANCELLED = "cancelled";
        private static final String TAG_RETURNED = "returned";
        private static final String TAG_TRANSACTION_STATUS = "transactionStatus";
        private static final String TAG_BLOCKAGE_AMOUNT = "blockage_amount";
        private static final String TAG_BLOCKAGE_RELEASE_DATE = "blockageReleaseDate";


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

// Calling async task to get json
            new GetInfo().execute();
        }
        /**
         * Async task class to get json by making HTTP call
         */
        private class GetInfo extends AsyncTask<Void, Void, Void> {

            // Hashmap for ListView
            ArrayList<HashMap<String, String>> transactionInfoList;
            ProgressDialog proDialog;

            @Override
            protected void onPreExecute() {
                super.onPreExecute();
// Showing progress loading dialog
                proDialog = new ProgressDialog(Transactions.this);
                proDialog.setMessage("Please Wait...");
                proDialog.setCancelable(false);
                proDialog.show();
            }
            @Override
            protected Void doInBackground(Void... arg0) {
// Creating service handler class instance
                WebRequest webReq = new WebRequest();

// Making a request to url and getting response
                String jsonStr = webReq.makeWebServiceCall(url, WebRequest.GET);

                Log.d("Response: ", "> " + jsonStr);

                transactionInfoList = ParseJSON(jsonStr);

                return null;
            }
            @Override
            protected void onPostExecute(Void requestresult) {
                super.onPostExecute(requestresult);
// Dismiss the progress dialog
                if (proDialog.isShowing())
                    proDialog.dismiss();
/**
 * Updating received data from JSON into ListView
 * */
                transactionInfoList=new ArrayList<HashMap<String, String>>();
                ListAdapter adapter = new SimpleAdapter(
                        Transactions.this, transactionInfoList,
                        R.layout.row_layout, new String[]{TAG_SENT_TO,TAG_DATE_TIME
                        ,TAG_BANK_NAME,TAG_AMOUNT,TAG_3DS, TAG_CANCELLED,
                        TAG_RETURNED},
                        new int[]{R.id.name,R.id.dateTime ,R.id.bankName,R.id.amount,
                        R.id.threeDS, R.id.cancelled, R.id.returned});

                setListAdapter(adapter);
            }

        }
        private ArrayList<HashMap<String, String>> ParseJSON(String json) {
            if (json != null) {
                try {
// Hashmap for ListView
                    ArrayList<HashMap<String, String>> paymentList = new ArrayList<HashMap<String, String>>();

                    JSONObject jsonObj = new JSONObject(json);

// Getting JSON Array node
                    JSONArray payments = jsonObj.getJSONArray(TAG_PAYMENTS);

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

                        String dateTime =c.getString(TAG_DATE_TIME);
                        String sentTo =c.getString(TAG_SENT_TO);
                        String bankName =c.getString(TAG_BANK_NAME)+" ( "+c.getString(TAG_INSTALLMENTS)+" ) " ;
                        String amount =c.getString(TAG_AMOUNT);
                        String threeDS =c.getString(TAG_3DS);
                        String cancelled =c.getString(TAG_CANCELLED);
                        String returned =c.getString(TAG_RETURNED);



// temporary hashmap for a single payment
                        HashMap<String, String> payment = new HashMap<String, String>();

// adding every child node to HashMap key => value
                        payment.put(TAG_DATE_TIME, dateTime);
                        payment.put(TAG_SENT_TO, sentTo);
                        payment.put(TAG_BANK_NAME, bankName);
                        payment.put(TAG_AMOUNT, amount);
                        payment.put(TAG_3DS, threeDS);
                        payment.put(TAG_CANCELLED, cancelled);
                        payment.put(TAG_RETURNED, returned);






// adding student to students list
                        paymentList.add(payment);
                    }
                    return paymentList;
                } catch (JSONException e) {
                    e.printStackTrace();
                    return null;
                }
            } else {
                Log.e("ServiceHandler", "No data received from HTTP Request");
                return null;
            }
        }
    }

这是WebRequest类

package com.rectuca.iyzicodemo.Library;
        import java.io.BufferedReader;
        import java.io.BufferedWriter;
        import java.io.InputStreamReader;
        import java.io.OutputStream;
        import java.io.OutputStreamWriter;
        import java.net.HttpURLConnection;
        import java.net.URL;
        import java.net.URLEncoder;
        import java.util.HashMap;
        import java.util.Map;

        import javax.net.ssl.HttpsURLConnection;

public class WebRequest {

    static String response = null;
    public final static int GET = 1;
    public final static int POST = 2;

    //Constructor with no parameter
    public WebRequest() {

    }

    /**
     * Making web service call
     *
     * @url - url to make request
     * @requestmethod - http request method
     */
    public String makeWebServiceCall(String url, int requestmethod) {
        return this.makeWebServiceCall(url, requestmethod, null);
    }

    /**
     * Making service call
     *
     * @url - url to make request
     * @requestmethod - http request method
     * @params - http request params
     */
    public String makeWebServiceCall(String urladdress, int requestmethod,
                                     HashMap<String, String> params) {
        URL url;
        String response = "";
        try {
            url = new URL(urladdress);

            HttpURLConnection conn = (HttpURLConnection) url.openConnection();
            conn.setReadTimeout(15000);
            conn.setConnectTimeout(15000);
            conn.setDoInput(true);
            conn.setDoOutput(true);

            if (requestmethod == POST) {
                conn.setRequestMethod("POST");
            } else if (requestmethod == GET) {
                conn.setRequestMethod("GET");
            }

            if (params != null) {
                OutputStream os = conn.getOutputStream();
                BufferedWriter writer = new BufferedWriter(
                        new OutputStreamWriter(os, "UTF-8"));

                StringBuilder result = new StringBuilder();
                boolean first = true;
                for (Map.Entry<String, String> entry : params.entrySet()) {
                    if (first)
                        first = false;
                    else
                        result.append("&");

                    result.append(URLEncoder.encode(entry.getKey(), "UTF-8"));
                    result.append("=");
                    result.append(URLEncoder.encode(entry.getValue(), "UTF-8"));
                }

                writer.write(result.toString());

                writer.flush();
                writer.close();
                os.close();
            }

            int responseCode = conn.getResponseCode();

            if (responseCode == HttpsURLConnection.HTTP_OK) {
                String line;
                BufferedReader br = new BufferedReader(new InputStreamReader(conn.getInputStream()));
                while ((line = br.readLine()) != null) {
                    response += line;
                }
            } else {
                response = "";
            }
        } catch (Exception e) {
            e.printStackTrace();
        }

        return response;
    }

}

这就是我想要做的事情

http://lh3.googleusercontent.com/JqcySZU2Pz067NutlDvPP5Zq_3n_WSAllIuEdjQjOjyeGkKguaMNCrltaKbjBCi16g=h900-rw

1 个答案:

答案 0 :(得分:1)

我建议你使用 谷歌的VOLLEY网络库

您应该尝试使用Volley JSONOBJECTREQUEST()并且在解析之后您将不会遇到任何问题。

将此添加到应用的依赖项部分

function convertImgToDataURLviaCanvas(url){
    var img = new Image();
    img.crossOrigin = 'Anonymous';
    img.onload = function(){
        var canvas = document.createElement('CANVAS');
        var ctx = canvas.getContext('2d');
        var dataURL;
        canvas.height = this.height;
        canvas.width = this.width;
        ctx.drawImage(this, 0, 0);
        dataURL = canvas.toDataURL("image/png");
        canvas = null; 
    };
    img.src = url;
}

function convertFileToDataURLviaFileReader(url){
    var xhr = new XMLHttpRequest();
    xhr.responseType = 'blob';
    xhr.onload = function() {
        var reader  = new FileReader();
        reader.onloadend = function () {
            console.log(reader.result);
        }
        reader.readAsDataURL(xhr.response);
    };
    xhr.open('GET', url);
    xhr.send();
}