0

我正在尝试将 JSON 解析为列表视图

  • 我收到此错误,因为我已在 LOG cat 中发布
  • 为什么会发生错误
  • 如何解决这个问题

MY-JSON 位置::http://54.218.73.244:7002/


JSONfunctions.java

public class JSONfunctions {

    public static JSONObject getJSONfromURL(String url) {
        InputStream is = null;
        String result = "";
        JSONObject jArray = null;

        // Download JSON data from URL
        try {
            HttpClient httpclient = new DefaultHttpClient();
            HttpPost httppost = new HttpPost(url);
            HttpResponse response = httpclient.execute(httppost);
            HttpEntity entity = response.getEntity();
            is = entity.getContent();

        } catch (Exception e) {
            Log.e("log_tag", "Error in http connection " + e.toString());
        }

        // Convert response to string
        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();
            result = sb.toString();
        } catch (Exception e) {
            Log.e("log_tag", "Error converting result " + e.toString());
        }

        try {

            jArray = new JSONObject(result);
        } catch (JSONException e) {
            Log.e("log_tag", "Error parsing data " + e.toString());
        }

        return jArray;
    }
}

ListViewAdapter.java

public class ListViewAdapter extends BaseAdapter {

    // Declare Variables
    Context context;
    LayoutInflater inflater;
    ArrayList<HashMap<String, String>> data;
    ImageLoader imageLoader;
    HashMap<String, String> resultp = new HashMap<String, String>();

    public ListViewAdapter(Context context,
            ArrayList<HashMap<String, String>> arraylist) {
        this.context = context;
        data = arraylist;
        imageLoader = new ImageLoader(context);
    }

    @Override
    public int getCount() {
        return data.size();
    }

    @Override
    public Object getItem(int position) {
        return null;
    }

    @Override
    public long getItemId(int position) {
        return 0;
    }

    public View getView(final int position, View convertView, ViewGroup parent) {
        // Declare Variables
        TextView rank;
        TextView country;
        ImageView flag;

        inflater = (LayoutInflater) context
                .getSystemService(Context.LAYOUT_INFLATER_SERVICE);

        View itemView = inflater.inflate(R.layout.listview_item, parent, false);
        // Get the position
        resultp = data.get(position);

        // Locate the TextViews in listview_item.xml
        rank = (TextView) itemView.findViewById(R.id.rank);
        country = (TextView) itemView.findViewById(R.id.country);

        // Locate the ImageView in listview_item.xml
        flag = (ImageView) itemView.findViewById(R.id.flag);

        // Capture position and set results to the TextViews
        rank.setText(resultp.get(MainActivity.NAME));
        country.setText(resultp.get(MainActivity.TYPE));
        // Capture position and set results to the ImageView
        // Passes flag images URL into ImageLoader.class
        imageLoader.DisplayImage(resultp.get(MainActivity.FLAG), flag);
        // Capture ListView item click
        itemView.setOnClickListener(new OnClickListener() {

            @Override
            public void onClick(View arg0) {
                // Get the position
                resultp = data.get(position);
                Intent intent = new Intent(context, SingleItemView.class);
                // Pass all data rank
                intent.putExtra("name", resultp.get(MainActivity.NAME));
                // Pass all data country
                intent.putExtra("type", resultp.get(MainActivity.TYPE));
                // Pass all data flag
                intent.putExtra("flag", resultp.get(MainActivity.FLAG));
                // Start SingleItemView Class
                context.startActivity(intent);

            }
        });
        return itemView;
    }
}

MainActivity.java

public class MainActivity extends Activity {
    // Declare Variables
    JSONObject jsonobject;
    JSONArray jsonarray;
    ListView listview;
    ListViewAdapter adapter;
    ProgressDialog mProgressDialog;
    ArrayList<HashMap<String, String>> arraylist;
    static String NAME = "rank";
    static String TYPE = "country";
    static String FLAG = "flag";

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        // Get the view from listview_main.xml
        setContentView(R.layout.listview_main);
        // Execute DownloadJSON AsyncTask
        new DownloadJSON().execute();
    }

    // DownloadJSON AsyncTask
    private class DownloadJSON extends AsyncTask<Void, Void, Void> {

        @Override
        protected void onPreExecute() {
            super.onPreExecute();
            // Create a progressdialog
            mProgressDialog = new ProgressDialog(MainActivity.this);
            // Set progressdialog title
            mProgressDialog.setTitle("Android JSON Parse Tutorial");
            // Set progressdialog message
            mProgressDialog.setMessage("Loading...");
            mProgressDialog.setIndeterminate(false);
            // Show progressdialog
            mProgressDialog.show();
        }

        @Override
        protected Void doInBackground(Void... params) {
            // Create an array
            arraylist = new ArrayList<HashMap<String, String>>();
            // Retrieve JSON Objects from the given URL address
            jsonobject = JSONfunctions
                    .getJSONfromURL("http://54.218.73.244:7002/");

            try {
                // Locate the array name in JSON
                jsonarray = jsonobject.getJSONArray("restaurants");

                for (int i = 0; i < jsonarray.length(); i++) {
                    HashMap<String, String> map = new HashMap<String, String>();
                    jsonobject = jsonarray.getJSONObject(i);
                    // Retrive JSON Objects
                    map.put("name", jsonobject.getString("restaurantNAME"));
                    map.put("type", jsonobject.getString("restaurantTYPE"));
                    map.put("flag", jsonobject.getString("restaurantIMAGE"));
                    // Set the JSON Objects into the array
                    arraylist.add(map);
                }
            } catch (JSONException e) {
                Log.e("Error", e.getMessage());
                e.printStackTrace();
            }
            return null;
        }

        @Override
        protected void onPostExecute(Void args) {
            // Locate the listview in listview_main.xml
            listview = (ListView) findViewById(R.id.listview);
            // Pass the results into ListViewAdapter.java
            adapter = new ListViewAdapter(MainActivity.this, arraylist);
            // Set the adapter to the ListView
            listview.setAdapter(adapter);
            // Close the progressdialog
            mProgressDialog.dismiss();
        }
    }
}

日志::

09-21 19:29:33.245: W/dalvikvm(1041): threadid=6: spin on suspend #1 threadid=9 (pcf=0)
09-21 19:29:33.245: D/dalvikvm(1041): Temporarily moving tid 1051 to fg (was 0)
09-21 19:29:33.245: D/dalvikvm(1041): Temporarily raised priority on tid 1051 (10 -> 0)
09-21 19:29:33.313: W/dalvikvm(1041): threadid=6: spin on suspend resolved in 1088 msec
09-21 19:29:33.323: D/dalvikvm(1041): Restored policy of 1051 to 0
09-21 19:29:33.323: D/dalvikvm(1041): Restored priority on 1051 to 10
09-21 19:29:49.541: E/log_tag(1041): Error parsing data org.json.JSONException: Value Cannot of type java.lang.String cannot be converted to JSONObject
09-21 19:29:49.544: W/dalvikvm(1041): threadid=9: thread exiting with uncaught exception (group=0x40015560)
09-21 19:29:49.663: E/AndroidRuntime(1041): FATAL EXCEPTION: AsyncTask #1
09-21 19:29:49.663: E/AndroidRuntime(1041): java.lang.RuntimeException: An error occured while executing doInBackground()
09-21 19:29:49.663: E/AndroidRuntime(1041):     at android.os.AsyncTask$3.done(AsyncTask.java:200)
09-21 19:29:49.663: E/AndroidRuntime(1041):     at java.util.concurrent.FutureTask$Sync.innerSetException(FutureTask.java:274)
09-21 19:29:49.663: E/AndroidRuntime(1041):     at java.util.concurrent.FutureTask.setException(FutureTask.java:125)
09-21 19:29:49.663: E/AndroidRuntime(1041):     at java.util.concurrent.FutureTask$Sync.innerRun(FutureTask.java:308)
09-21 19:29:49.663: E/AndroidRuntime(1041):     at java.util.concurrent.FutureTask.run(FutureTask.java:138)
09-21 19:29:49.663: E/AndroidRuntime(1041):     at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1088)
09-21 19:29:49.663: E/AndroidRuntime(1041):     at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:581)
09-21 19:29:49.663: E/AndroidRuntime(1041):     at java.lang.Thread.run(Thread.java:1019)
09-21 19:29:49.663: E/AndroidRuntime(1041): Caused by: java.lang.NullPointerException
09-21 19:29:49.663: E/AndroidRuntime(1041):     at com.androidbegin.jsonparsetutorial.MainActivity$DownloadJSON.doInBackground(MainActivity.java:63)
09-21 19:29:49.663: E/AndroidRuntime(1041):     at com.androidbegin.jsonparsetutorial.MainActivity$DownloadJSON.doInBackground(MainActivity.java:1)
09-21 19:29:49.663: E/AndroidRuntime(1041):     at android.os.AsyncTask$2.call(AsyncTask.java:185)
09-21 19:29:49.663: E/AndroidRuntime(1041):     at java.util.concurrent.FutureTask$Sync.innerRun(FutureTask.java:306)
09-21 19:29:49.663: E/AndroidRuntime(1041):     ... 4 more
09-21 19:29:52.253: E/WindowManager(1041): Activity com.androidbegin.jsonparsetutorial.MainActivity has leaked window com.android.internal.policy.impl.PhoneWindow$DecorView@4051f980 that was originally added here
09-21 19:29:52.253: E/WindowManager(1041): android.view.WindowLeaked: Activity com.androidbegin.jsonparsetutorial.MainActivity has leaked window com.android.internal.policy.impl.PhoneWindow$DecorView@4051f980 that was originally added here
09-21 19:29:52.253: E/WindowManager(1041):  at android.view.ViewRoot.<init>(ViewRoot.java:258)
09-21 19:29:52.253: E/WindowManager(1041):  at android.view.WindowManagerImpl.addView(WindowManagerImpl.java:148)
09-21 19:29:52.253: E/WindowManager(1041):  at android.view.WindowManagerImpl.addView(WindowManagerImpl.java:91)
09-21 19:29:52.253: E/WindowManager(1041):  at android.view.Window$LocalWindowManager.addView(Window.java:424)
09-21 19:29:52.253: E/WindowManager(1041):  at android.app.Dialog.show(Dialog.java:241)
09-21 19:29:52.253: E/WindowManager(1041):  at com.androidbegin.jsonparsetutorial.MainActivity$DownloadJSON.onPreExecute(MainActivity.java:50)
09-21 19:29:52.253: E/WindowManager(1041):  at android.os.AsyncTask.execute(AsyncTask.java:391)
09-21 19:29:52.253: E/WindowManager(1041):  at com.androidbegin.jsonparsetutorial.MainActivity.onCreate(MainActivity.java:33)
09-21 19:29:52.253: E/WindowManager(1041):  at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1047)
09-21 19:29:52.253: E/WindowManager(1041):  at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:1611)
09-21 19:29:52.253: E/WindowManager(1041):  at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:1663)
09-21 19:29:52.253: E/WindowManager(1041):  at android.app.ActivityThread.access$1500(ActivityThread.java:117)
09-21 19:29:52.253: E/WindowManager(1041):  at android.app.ActivityThread$H.handleMessage(ActivityThread.java:931)
09-21 19:29:52.253: E/WindowManager(1041):  at android.os.Handler.dispatchMessage(Handler.java:99)
09-21 19:29:52.253: E/WindowManager(1041):  at android.os.Looper.loop(Looper.java:123)
09-21 19:29:52.253: E/WindowManager(1041):  at android.app.ActivityThread.main(ActivityThread.java:3683)
09-21 19:29:52.253: E/WindowManager(1041):  at java.lang.reflect.Method.invokeNative(Native Method)
09-21 19:29:52.253: E/WindowManager(1041):  at java.lang.reflect.Method.invoke(Method.java:507)
09-21 19:29:52.253: E/WindowManager(1041):  at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:839)
09-21 19:29:52.253: E/WindowManager(1041):  at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:597)
09-21 19:29:52.253: E/WindowManager(1041):  at dalvik.system.NativeStart.main(Native Method)
09-21 19:34:50.023: I/Process(1041): Sending signal. PID: 1041 SIG: 9

有任何想法吗

希望我清楚

4

1 回答 1

1

MainActivity.java 的第 63 行有一个 NPE。这条线是

jsonarray = jsonobject.getJSONArray("restaurants");

这意味着jsonobject必须null在这一点上。

于 2013-09-21T14:21:41.073 回答