Json在listView中解析 - 一个空对象引用错误

时间:2017-05-05 20:01:19

标签: android json listview nullpointerexception

我的第一个应用程序显示汇率列表。问题是,当我尝试启动应用程序时,我有一个错误。我认为我传递的参数之一== null,但我不知道哪一个

错误:

E/EGL_emulation: tid 2454: eglSurfaceAttrib(1146): error 0x3009 
(EGL_BAD_MATCH)
W/OpenGLRenderer: Failed to set EGL_SWAP_BEHAVIOR on surface 0x9e6cf540, 
error=EGL_BAD_MATCH
E/EGL_emulation: tid 2454: eglSurfaceAttrib(1146): error 0x3009 
(EGL_BAD_MATCH)
W/OpenGLRenderer: Failed to set EGL_SWAP_BEHAVIOR on surface 0x9e6cf580, 
error=EGL_BAD_MATCH
D/AndroidRuntime: Shutting down VM


              --------- beginning of crash
E/AndroidRuntime: FATAL EXCEPTION: main
              Process: com.lewin.kurswalut, PID: 2266
              java.lang.NullPointerException: Attempt to invoke virtual method 'int java.lang.String.length()' on a null object reference
                  at org.json.JSONTokener.nextCleanInternal(JSONTokener.java:116)
                  at org.json.JSONTokener.nextValue(JSONTokener.java:94)
                  at org.json.JSONObject.<init>(JSONObject.java:156)
                  at org.json.JSONObject.<init>(JSONObject.java:173)
                  at com.lewin.kurswalut.MainActivity$GetValue.onPostExecute(MainActivity.java:83)
                  at com.lewin.kurswalut.MainActivity$GetValue.onPostExecute(MainActivity.java:49)
                  at android.os.AsyncTask.finish(AsyncTask.java:660)
                  at android.os.AsyncTask.-wrap1(AsyncTask.java)
                  at android.os.AsyncTask$InternalHandler.handleMessage(AsyncTask.java:677)
                  at android.os.Handler.dispatchMessage(Handler.java:102)
                  at android.os.Looper.loop(Looper.java:154)
                  at android.app.ActivityThread.main(ActivityThread.java:6077)
                  at java.lang.reflect.Method.invoke(Native Method)
                  at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:865)
                  at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:755)

MainActivity.java

package com.lewin.kurswalut;

import android.app.ProgressDialog;
import android.os.AsyncTask;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.widget.ListAdapter;
import android.widget.ListView;
import android.widget.SimpleAdapter;
import android.widget.TextView;

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

import java.io.BufferedInputStream;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.URL;
import java.net.URLConnection;
import java.util.ArrayList;
import java.util.HashMap;


import static com.lewin.kurswalut.R.id.list;

public class MainActivity extends AppCompatActivity {

private ProgressDialog pDialog;
private ListView lv;

ArrayList<HashMap<String, String>> currencyList;

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

    currencyList = new ArrayList<>();
    lv = (ListView) this.findViewById(R.id.list);


    new GetValue().execute("http://api.nbp.pl/api/exchangerates/tables/a/?format=json");
}


private class GetValue extends AsyncTask<String, Void, String> {


    private ProgressDialog pDialog = new ProgressDialog(MainActivity.this);

    @Override
    protected void onPreExecute() {

        pDialog.setMessage("Please wait...");
        pDialog.show();

    }

    @Override
    protected String doInBackground(String... urls) {

        try {
            URL url = new URL(urls[0]);
            URLConnection connection = url.openConnection();
            InputStream in = new BufferedInputStream(connection.getInputStream());

            return streamConverter(in);

        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

    protected void onPostExecute(String result) {

        pDialog.dismiss();

        try {
            JSONObject jsonObj = new JSONObject(result);
            JSONArray currencyView = jsonObj.getJSONArray("rates");

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

                String currency = c.getString("currency");
                String code = c.getString("code");
                String mid = c.getString("mid");


                HashMap<String, String> currencyViews = new HashMap<>();

                currencyViews.put("currency", currency);
                currencyViews.put("code", code);
                currencyViews.put("mid", mid);


                currencyList.add(currencyViews);


                ListAdapter adapter = new SimpleAdapter(
                        MainActivity.this, currencyList,
                        R.layout.list_items, new String[]{"currency", "code",
                        "mid"}, new int[]{R.id.currency,
                        R.id.code, R.id.mid});

                lv.setAdapter(adapter);
            }
        } catch (JSONException e) {
            e.printStackTrace();
        }
        super.onPostExecute(result);
    }

    public String streamConverter(InputStream is) {
        BufferedReader reader = new BufferedReader(new InputStreamReader(is));
        StringBuilder builder = new StringBuilder();
        String line = null;

        try {
            while ((line = reader.readLine()) != null) {
                builder.append(line + "\n");
            }
            reader.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return builder.toString();
    }
}
}

json格式:

[
  {
    "table": "A",
    "no": "086/A/NBP/2017",
    "effectiveDate": "2017-05-05",
    "rates": [
      {
        "currency": "bat (Tajlandia)",
        "code": "THB",
        "mid": 0.1110
      },
      {
        "currency": "dolar amerykański",
        "code": "USD",
        "mid": 3.8490
      },
      {
        "currency": "dolar australijski",
        "code": "AUD",
        "mid": 2.8471
      },
      {
        "currency": "dolar Hongkongu",
        "code": "HKD",
        "mid": 0.4945
      },
      {
        "currency": "dolar kanadyjski",
        "code": "CAD",
        "mid": 2.7963
      },
      {
        "currency": "dolar nowozelandzki",
        "code": "NZD",
        "mid": 2.6545
      },
      {
        "currency": "dolar singapurski",
        "code": "SGD",
        "mid": 2.7422
      },
      {
        "currency": "euro",
        "code": "EUR",
        "mid": 4.2176
      },
      {
        "currency": "forint (Węgry)",
        "code": "HUF",
        "mid": 0.013511
      },
      {
        "currency": "frank szwajcarski",
        "code": "CHF",
        "mid": 3.8928
      },
      {
        "currency": "funt szterling",
        "code": "GBP",
        "mid": 4.9792
      },
      {
        "currency": "hrywna (Ukraina)",
        "code": "UAH",
        "mid": 0.1452
      },
      {
        "currency": "jen (Japonia)",
        "code": "JPY",
        "mid": 0.034266
      },
      {
        "currency": "korona czeska",
        "code": "CZK",
        "mid": 0.1572
      },
      {
        "currency": "korona duńska",
        "code": "DKK",
        "mid": 0.5671
      },
      {
        "currency": "korona islandzka",
        "code": "ISK",
        "mid": 0.03628
      },
      {
        "currency": "korona norweska",
        "code": "NOK",
        "mid": 0.4442
      },
      {
        "currency": "korona szwedzka",
        "code": "SEK",
        "mid": 0.4353
      },
      {
        "currency": "kuna (Chorwacja)",
        "code": "HRK",
        "mid": 0.5675
      },
      {
        "currency": "lej rumuński",
        "code": "RON",
        "mid": 0.9277
      },
      {
        "currency": "lew (Bułgaria)",
        "code": "BGN",
        "mid": 2.1565
      }
    ]
  }
]

我有另一个问题:如何获取所选项目,例如以上就像&#34;代码&#34;:&#34; USD&#34; ,&#34; EUR&#34;,&#34; NOK&#34;?

感谢您的建议

2 个答案:

答案 0 :(得分:0)

我相信你正在解析JSON错误。它是一个JSON数组,然后你有一个JSON对象,然后rates是一个JSON数组

答案 1 :(得分:0)

方法onPostExecute获取null,然后在创建新的JSONObject(结果)时捕获异常。