Android中的JSON解析遇到了麻烦

时间:2014-05-11 12:17:17

标签: android json android-asynctask

我在从本地服务器解析json时遇到了麻烦。

我的代码看起来像这样。

--MainActivity--
package com.mihajlo.http;

import java.util.ArrayList;
import java.util.HashMap;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import android.app.ListActivity;
import android.app.ProgressDialog;
import android.content.Context;
import android.os.AsyncTask;
import android.os.Bundle;
import android.widget.ListAdapter;
import android.widget.ListView;
import android.widget.SimpleAdapter;

public class MainActivity extends ListActivity {
    private Context context;
    private static String url = "http://10.0.2.2:8080/pnrs1/?CommandMsg=StudentsByGroup&MsgParam=31";
    private static final String Name = "name";
    private static final String Index = "index";
    private static final String Year = "year";

    ArrayList<HashMap<String, String>> jsonlist = new ArrayList<HashMap<String, String>>();
    ListView lv;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        new ProgressTask(MainActivity.this).execute();
    }

    private class ProgressTask extends AsyncTask<String, Void, Boolean> {
        private ProgressDialog dialog;

        private ListActivity activity;

        public ProgressTask(ListActivity activity) {
            this.activity = activity;
            context = activity;
            dialog = new ProgressDialog(context);
        }

        private Context context;

        protected void onPreExecute() {
            this.dialog.setMessage("Progress start");
            this.dialog.show();
        }

        protected void onPostExecute(final Boolean success) {
            if (dialog.isShowing()) {
                dialog.dismiss();
            }
            ListAdapter adapter = new SimpleAdapter(context, jsonlist,
                    R.layout.list_item, new String[] { Name, Index, Year },
                    new int[] { R.id.name_id, R.id.index_id, R.id.year_id });
            setListAdapter(adapter);

            // single item View
            lv = getListView();
        }

        @Override
        protected Boolean doInBackground(final String... args) {

            JSONParser jParser = new JSONParser();
            // get JSON data from URL
            JSONArray json = jParser.getJSONFromUrl(url);

            for (int i = 0; i < json.length(); i++) {
                try {
                    JSONObject c = json.getJSONObject(i);
                    String name = c.getString(Name);
                    String index = c.getString(Index);
                    String year = c.getString(Year);

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

                    // Add strings to HashMap ("key","value")
                    map.put(Name, name);
                    map.put(Index, index);
                    map.put(Year, year);
                    jsonlist.add(map);
                } catch (JSONException e) {
                    e.printStackTrace();
                }
            }
            return null;
        }
    }
}




--JSONParser--
package com.mihajlo.http;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.UnsupportedEncodingException;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.StatusLine;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import android.util.Log;

public class JSONParser {

    static InputStream iStream = null;
    static JSONArray jarray = null;
    static String json = "";

    public JSONParser() {

    }

    public JSONArray getJSONFromUrl(String url) {
        StringBuilder builder = new StringBuilder();
        HttpClient client = new DefaultHttpClient();
        HttpGet httpGet = new HttpGet(url);
        try {
            HttpResponse response = client.execute(httpGet);
            StatusLine statusLine = response.getStatusLine();
            int statusCode = statusLine.getStatusCode();
            if (statusCode == 200) {
                HttpEntity entity = response.getEntity();
                InputStream content = entity.getContent();
                BufferedReader reader = new BufferedReader(
                        new InputStreamReader(content));

                String line;
                while ((line = reader.readLine()) != null) {
                    builder.append(line);
                }
            } else {
                Log.e("TAG", "Faild to download file");

            }
        } catch (ClientProtocolException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }

        // Parse String to JSON object
        try {
            jarray = new JSONArray(builder.toString());
        } catch (JSONException e) {
            Log.e("JSON Parser", "Error parsing data" + e.toString());
        }

        // return JSON Object
        return jarray;
    }
}

我收到像这样的错误=&gt;

05-11 11:57:00.651: E/WindowManager(2653): Activity com.mihajlo.http.MainActivity has leaked window com.android.internal.policy.impl.PhoneWindow$DecorView{40cf0b50 V.E..... R.....ID 0,0-456,144} that was originally added here
05-11 11:57:00.651: E/WindowManager(2653): android.view.WindowLeaked: Activity com.mihajlo.http.MainActivity has leaked window com.android.internal.policy.impl.PhoneWindow$DecorView{40cf0b50 V.E..... R.....ID 0,0-456,144} that was originally added here
05-11 11:57:00.651: E/WindowManager(2653):  at android.view.ViewRootImpl.<init>(ViewRootImpl.java:354)
05-11 11:57:00.651: E/WindowManager(2653):  at android.view.WindowManagerGlobal.addView(WindowManagerGlobal.java:216)
05-11 11:57:00.651: E/WindowManager(2653):  at android.view.WindowManagerImpl.addView(WindowManagerImpl.java:69)
05-11 11:57:00.651: E/WindowManager(2653):  at android.app.Dialog.show(Dialog.java:281)
05-11 11:57:00.651: E/WindowManager(2653):  at com.mihajlo.http.MainActivity$ProgressTask.onPreExecute(MainActivity.java:60)
05-11 11:57:00.651: E/WindowManager(2653):  at android.os.AsyncTask.executeOnExecutor(AsyncTask.java:586)
05-11 11:57:00.651: E/WindowManager(2653):  at android.os.AsyncTask.execute(AsyncTask.java:534)
05-11 11:57:00.651: E/WindowManager(2653):  at com.mihajlo.http.MainActivity.onCreate(MainActivity.java:42)
05-11 11:57:00.651: E/WindowManager(2653):  at android.app.Activity.performCreate(Activity.java:5104)
05-11 11:57:00.651: E/WindowManager(2653):  at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1080)
05-11 11:57:00.651: E/WindowManager(2653):  at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2144)
05-11 11:57:00.651: E/WindowManager(2653):  at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2230)
05-11 11:57:00.651: E/WindowManager(2653):  at android.app.ActivityThread.access$600(ActivityThread.java:141)
05-11 11:57:00.651: E/WindowManager(2653):  at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1234)
05-11 11:57:00.651: E/WindowManager(2653):  at android.os.Handler.dispatchMessage(Handler.java:99)
05-11 11:57:00.651: E/WindowManager(2653):  at android.os.Looper.loop(Looper.java:137)
05-11 11:57:00.651: E/WindowManager(2653):  at android.app.ActivityThread.main(ActivityThread.java:5041)
05-11 11:57:00.651: E/WindowManager(2653):  at java.lang.reflect.Method.invokeNative(Native Method)
05-11 11:57:00.651: E/WindowManager(2653):  at java.lang.reflect.Method.invoke(Method.java:511)
05-11 11:57:00.651: E/WindowManager(2653):  at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:793)
05-11 11:57:00.651: E/WindowManager(2653):  at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:560)
05-11 11:57:00.651: E/WindowManager(2653):  at dalvik.system.NativeStart.main(Native Method)

1 个答案:

答案 0 :(得分:0)

我认为这是因为对话框不在UI线程, 我不太确定 但我很确定有更好的方式来展示对话, 比这样,

showDialog(int)类似,虽然它已被弃用,但我认为它可以解决您的问题。

看看here