【问题标题】:Activity has leaked windows that was originally added hereActivity 泄露了原本在这里添加的窗口
【发布时间】:2013-04-04 03:10:44
【问题描述】:

基本上我得到了这个错误,我不确定是代码的哪一部分导致它,只是寻找一些关于错误的建议,谢谢。 .

   public class ViewHole extends ListActivity {

// Progress Dialog
private ProgressDialog pDialog;

// Creating JSON Parser object
JSONParser jParser = new JSONParser();

ArrayList<HashMap<String, String>> holesList;


// url to get all products list
private static String url_all_holes = "http://localhost/realdeal/get_hole_details.php";

// JSON Node names
private static final String TAG_SUCCESS = "success";
private static final String TAG_COURSEONE = "courseone";
private static final String TAG_HOLENUMBER = "holenumber";
private static final String TAG_INDEX = "index";
private static final String TAG_YARDAGE = "yardage";
private static final String TAG_PAR = "par";

// products JSONArray
JSONArray courseone = null;

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

    // Hashmap for ListView
    holesList = new ArrayList<HashMap<String, String>>();

    // Loading products in Background Thread
    new loadallholes().execute();



/**
 * Background Async Task to Load all holes by making HTTP Request
 * */
class loadallholes extends AsyncTask<String, String, String> {

    /**
     * Before starting background thread Show Progress Dialog
     * */
    @Override
    protected void onPreExecute() {
        super.onPreExecute();
        pDialog = new ProgressDialog(ViewHole.this);
        pDialog.setMessage("Loading holes. Please wait...");
        pDialog.setIndeterminate(false);
        pDialog.setCancelable(false);
        pDialog.show();
    }

    /**
     * getting All holes 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_holes, "GET", params);

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

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

            if (success == 1) {
                // holes found
                // Getting Array of hole numbers
                courseone = json.getJSONArray(TAG_COURSEONE);

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

                    // Storing each json item in variable
                    String holenumber = c.getString(TAG_HOLENUMBER);
                    String index = c.getString(TAG_INDEX);
                    String yardage = c.getString(TAG_YARDAGE);
                    String par = c.getString(TAG_PAR);




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

                    // adding each child node to HashMap key => value
                    map.put(TAG_HOLENUMBER, holenumber);
                    map.put(TAG_INDEX, index);
                    map.put(TAG_YARDAGE, yardage);
                    map.put(TAG_PAR, par);





                    // adding HashList to ArrayList
                    holesList.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(
                        ViewHole.this, holesList,
                        R.layout.list_item, new String[] { TAG_HOLENUMBER, TAG_INDEX, TAG_YARDAGE, TAG_PAR},                            
                        new int[] { R.id.holenumber, R.id.index, R.id.yardage, R.id.par });

                // updating listview
                setListAdapter(adapter);
            }
        });

    }

}
}

Logcat 错误 -

01-27 04:11:57.228: E/WindowManager(3566): Activity com.example.golfapp.ViewHole has leaked window com.android.internal.policy.impl.PhoneWindow$DecorView{40cdf768 V.E..... R.....ID 0,0-684,192} that was originally added here
01-27 04:11:57.228: E/WindowManager(3566): android.view.WindowLeaked: Activity com.example.golfapp.ViewHole has leaked window com.android.internal.policy.impl.PhoneWindow$DecorView{40cdf768 V.E..... R.....ID 0,0-684,192} that was originally added here
01-27 04:11:57.228: E/WindowManager(3566):  at android.view.ViewRootImpl.<init>(ViewRootImpl.java:354)
01-27 04:11:57.228: E/WindowManager(3566):  at android.view.WindowManagerGlobal.addView(WindowManagerGlobal.java:216)
01-27 04:11:57.228: E/WindowManager(3566):  at android.view.WindowManagerImpl.addView(WindowManagerImpl.java:69)
01-27 04:11:57.228: E/WindowManager(3566):  at android.app.Dialog.show(Dialog.java:281)
01-27 04:11:57.228: E/WindowManager(3566):  at com.example.golfapp.ViewHole$loadallholes.onPreExecute(ViewHole.java:121)
01-27 04:11:57.228: E/WindowManager(3566):  at android.os.AsyncTask.executeOnExecutor(AsyncTask.java:586)
01-27 04:11:57.228: E/WindowManager(3566):  at android.os.AsyncTask.execute(AsyncTask.java:534)
01-27 04:11:57.228: E/WindowManager(3566):  at com.example.golfapp.ViewHole.onCreate(ViewHole.java:61)
01-27 04:11:57.228: E/WindowManager(3566):  at android.app.Activity.performCreate(Activity.java:5104)
01-27 04:11:57.228: E/WindowManager(3566):  at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1080)
01-27 04:11:57.228: E/WindowManager(3566):  at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2144)
01-27 04:11:57.228: E/WindowManager(3566):  at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2230)
01-27 04:11:57.228: E/WindowManager(3566):  at android.app.ActivityThread.access$600(ActivityThread.java:141)
01-27 04:11:57.228: E/WindowManager(3566):  at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1234)
01-27 04:11:57.228: E/WindowManager(3566):  at android.os.Handler.dispatchMessage(Handler.java:99)
01-27 04:11:57.228: E/WindowManager(3566):  at android.os.Looper.loop(Looper.java:137)
01-27 04:11:57.228: E/WindowManager(3566):  at android.app.ActivityThread.main(ActivityThread.java:5039)
01-27 04:11:57.228: E/WindowManager(3566):  at java.lang.reflect.Method.invokeNative(Native Method)
01-27 04:11:57.228: E/WindowManager(3566):  at java.lang.reflect.Method.invoke(Method.java:511)
01-27 04:11:57.228: E/WindowManager(3566):  at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:793)
01-27 04:11:57.228: E/WindowManager(3566):  at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:560)
01-27 04:11:57.228: E/WindowManager(3566):  at dalvik.system.NativeStart.main(Native Method)

JSON 类 -

      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 method
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;

}
}

【问题讨论】:

  • 为什么在 onPostExecute 中使用 runOnUiThread?

标签: android


【解决方案1】:

我认为这里不需要使用runOnUIThread()

onPostExecute

protected void onPostExecute(String file_url) {
        // dismiss the dialog after getting all products
        if(pDialog.isShowing()){
             pDialog.dismiss();
        }

        ListAdapter adapter = new SimpleAdapter(
                 ViewHole.this, holesList,
                 R.layout.list_item, new String[] { TAG_HOLENUMBER, TAG_INDEX, TAG_YARDAGE, TAG_PAR},                            
                 new int[] { R.id.holenumber, R.id.index, R.id.yardage, R.id.par });

                // updating listview
                setListAdapter(adapter);
    }

并像这样取消onDestroy()中的pDialog

if(pDialog != null ){
     pDialog.cancel(); 
}

希望对你有帮助。

【讨论】:

  • 感谢您的建议,但当我尝试您的建议时,我得到了一个 FATAL EXCEPTION :AsyncTask #1 in doInBackground()
  • 你在holeList中获取数据吗?
  • 我也收到这些错误 - 01-27 05:21:41.248: E/Buffer Error(4291): Error conversion result java.lang.NullPointerException: lock == null 01-27 05: 21:41.328:E/JSON 解析器(4291):解析数据时出错 org.json.JSONException:在字符 0 处结束输入
  • 哦,解析错误,这就是你的 doInBackground() 不起作用的原因。你能把你的 json.toString() 放在这里吗?
  • 好的,我把 JSONParser 类放在原帖的底部
【解决方案2】:

onPostExecute() 是 UI 线程。所以 runOnUIThread() 是错误的。另外,我会考虑将您的 AsyncTask 与其所在的 Activity 分开。将来它的可重用性会大大提高。

【讨论】:

    【解决方案3】:
     try {
                    HttpClient httpclient = new DefaultHttpClient();
                    HttpPost httppost = new HttpPost(
                            url_all_holes);
    
                List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(2);
    
                httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
                ResponseHandler<String> responseHandler = new BasicResponseHandler();
    
                String yourReponseInJSONStr = httpclient.execute(httppost,
                        responseHandler);
                //you will get json string here
                Log.d("yourReponseInJSONStr ", yourReponseInJSONStr );
    
                //check here your getting json string in logcat.
               JSONObject yourJsonObj = new JSONObject(yourReponseInJSONStr);
    
               JSONArray results = jObject.getJSONArray(TAG_COURSEONE);
    
               for (int i = 0; i < results.length(); i++) {
                  //your parsing snippet
               }
            }
    } catch (Exception e) {
                e.printStackTrace();
            }
    

    【讨论】:

    • 我应该把这段代码放在哪里,我应该删除任何东西吗?
    • 将此代码放在第一行的 doInBackground() 中,并保持 for 循环不变。但首先检查你从 server.Log.d() 得到的响应,如果你没有得到响应服务器,那么它会抛出 json 解析错误。
    • 代码给我带来了很多问题,有什么办法可以把文件发给你吗?
    • 发送到我的电子邮件 amolsawant88@gmail.com
    • 在转发代码中更改一行:JSONObject jObject = new JSONObject(jsonResponse);
    猜你喜欢
    • 2017-06-02
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-02-20
    • 1970-01-01
    • 1970-01-01
    • 2015-01-31
    相关资源
    最近更新 更多