0

我的布局上有后退按钮,每次点击都会调用对话框。单击时,我首先检查进度对话框是否可见,即异步任务是否正在运行,如果是,则比单击是按钮单击对话框时,我正在调用新活动。它工作正常,但我反复收到错误,例如单击此后退按钮时 Activity has Memory Leak。请提出一些解决方法来克服这个问题。这里是片段

public class LatestTab extends Activity {

    Activity context;
    ArrayList<String> contentList,slugList,latestData,imgLinks;
    ArrayList<HashMap<String, String>> mylist;
    JSONObject json, obj,img,thumb;
    JSONArray  latest, attachment;
    ImageView bck;
    String shareUrl = "-- url ----";
    String jString;
    ProgressBar showProgress;
    NetworkCheck netCheck;
    File externalFile       = new File(Environment.getExternalStorageDirectory(),"Latest.txt");
    ListView listView;
    String imgStr;

    ImageLoader loader;
    LazyAdapter lazyAdapter;
    String latestUrl = "---url--";
    Bundle bundle;
    boolean isFinish = true;



    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        /*this.requestWindowFeature(Window.FEATURE_NO_TITLE);*/
        setContentView(R.layout.activity_latest_tab);

        context     =       this;
        bck         =       (ImageView) findViewById(R.id.bckbtn);
        showProgress=       (ProgressBar)findViewById(R.id.showProgress);
        netCheck    =       new NetworkCheck(context);
        listView    =       (ListView) findViewById(R.id.latestList);
        latestData  =       new ArrayList<String>();
        imgLinks    =       new ArrayList<String>();
        mylist      =       new ArrayList<HashMap<String, String>>();
        contentList =       new ArrayList<String>();
        slugList    =       new ArrayList<String>();

        bundle = getIntent().getExtras();
        if(bundle != null){
            isFinish = bundle.getBoolean("finishAct");
        }
        MyAsyncTask my =    new MyAsyncTask();
        if(netCheck.isNetworkAvailable()){
            showProgress.setVisibility(View.VISIBLE);
            my.execute(latestUrl);
        }else{
            //Toast.makeText(context, "No Internet Connection", Toast.LENGTH_SHORT).show();

            try {
                FileInputStream filename                = null;
                Document xmldoc                         = null;
                DocumentBuilderFactory doc_build_fact   = null;
                DocumentBuilder doc_builder             = null;
                filename = new FileInputStream("/sdcard/MadhuriLatest.txt");

                if(externalFile.exists()){
                    //      Toast.makeText(context, "File Excits", Toast.LENGTH_SHORT).show();
                    FileChannel fc = filename.getChannel();
                    MappedByteBuffer bb = fc.map(FileChannel.MapMode.READ_ONLY, 0, fc.size());
                    jString = Charset.defaultCharset().decode(bb).toString();
                    json = new JSONObject(jString); 
                    latest = json.getJSONArray("posts");
                    imgLinks.clear();
                    latestData.clear();
                    for(int i=0;i<latest.length();i++){

                        HashMap<String, String> map = new HashMap<String, String>();    
                        JSONObject e = latest.getJSONObject(i);

                        String name = e.getString("title_plain");
                        String content = e.getString("content");

                        attachment = e.getJSONArray("attachments");
                        for(int p=0; p<attachment.length();p++){
                            obj = attachment.getJSONObject(p);
                            img = obj.getJSONObject("images");
                            thumb = img.getJSONObject("thumbnail");
                            imgStr = thumb.getString("url");
                        }


                        Log.d("--------------",imgStr);
                        contentList.add(content);
                        String chng = "&#8211;";
                        String  fnl_Str = name.replace(chng, "");
                        latestData.add(fnl_Str);
                        imgLinks.add(imgStr);
                        String slug = e.getString("slug");
                        slugList.add(slug);
                        map.put("id",  String.valueOf(i));
                        map.put("name", fnl_Str);
                        map.put("date", e.getString("date"));


                        mylist.add(map);            
                    }       
                }


                lazyAdapter = new LazyAdapter(context, imgLinks, latestData);
                listView.setAdapter(lazyAdapter);
                lazyAdapter.notifyDataSetChanged();

                listView.setOnItemClickListener(new OnItemClickListener() {
                    public void onItemClick(AdapterView<?> parent, View view, int position, long id) {              


                        Intent intent=new Intent(context,WebViewActivity.class);
                        intent.putExtra("content", contentList.get(position));
                        intent.putExtra("shareUrl", shareUrl+slugList.get(position));
                        intent.putExtra("tab_value", 1);
                        startActivity(intent);
                        overridePendingTransition(R.anim.lefttorightslide,R.anim.righttoleftslide);

                    }
                });
            }catch(JSONException e)        {
                Log.e("log_tag", "Error parsing data "+e.toString());

            } catch (ParseException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            } catch (IOException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }catch (Exception e){
                Log.e("Error: ", " "+e.getMessage());
            }
        }


        bck.setOnClickListener(new OnClickListener() {

            @Override
            public void onClick(View v) {

                if(showProgress.isShown()){
                    final Dialog dialog = new Dialog(context, android.R.style.Theme_Translucent_NoTitleBar);
                    //final Dialog dialog = new Dialog(LAtestTab.this);
                    dialog.requestWindowFeature(Window.FEATURE_NO_TITLE);
                    /*dialog.getWindow().setBackgroundDrawableResource(R.drawable.alert_box);*/
                    dialog.setContentView(R.layout.alertbox);

                    ImageView yes = (ImageView) dialog.findViewById(R.id.yesbtn);
                    ImageView no = (ImageView) dialog.findViewById(R.id.nobtn);
                    dialog.show();

                    yes.setOnClickListener(new OnClickListener()
                    {
                        @Override
                        public void onClick(View v) 
                        {
                                                            if(isFinish){
                                Intent intent = new Intent(context,MadhuriHomeScreen.class);
                                startActivity(intent);
                                overridePendingTransition(R.anim.slide_out_left,R.anim.slide_out_right);
                                finish();
                            }else{
                                finish();
                            }
                        }
                    });

                    no.setOnClickListener(new OnClickListener()
                    {


                        @Override
                        public void onClick(View v) {
                            // TODO Auto-generated method stub
                            dialog.dismiss();  
                        }
                    });


                }
                else{
                    finish();
                }
            }
        });


    }

    class MyAsyncTask extends AsyncTask<String, Integer, ArrayList<HashMap<String, String>> > {

        @Override
        protected ArrayList<HashMap<String, String>> doInBackground(
                String... params) {
            // TODO Auto-generated method stub
            int count;
            mylist = new ArrayList<HashMap<String, String>>();
            contentList=new ArrayList<String>();
            slugList=new ArrayList<String>();
            /*json = new JSONObject();*/
            json = JSONfunctions.getJSONfromURL(latestUrl);


            try{

                URL url = new URL(params[0]);
                URLConnection connection = url.openConnection();
                connection.connect();

                // getting file length
                int lenghtOfFile = connection.getContentLength();

                // input stream to read file - with 8k buffer
                InputStream input = new BufferedInputStream(url.openStream(), 8192);

                // Output stream to write file
                FileOutputStream output = new FileOutputStream("/sdcard/MadhuriLatest.txt");


                byte data[] = new byte[1024];

                long total = 0;
                while (   ((count = input.read(data)) != -1)  ) {
                    total += count;

                    // publishing the progress....
                    // After this onProgressUpdate will be called
                    /*  publishProgress(""+(int)((total*100)/lenghtOfFile));
                     */
                    // writing data to file
                    output.write(data, 0, count);
                }

                output.flush();
                // closing streams
                output.close();
                input.close();

                latest = json.getJSONArray("posts");
                imgLinks.clear();
                for(int i=0;i<latest.length();i++){ 

                    HashMap<String, String> map = new HashMap<String, String>();    
                    JSONObject e = latest.getJSONObject(i);

                    String name = e.getString("title_plain");
                    String content = e.getString("content");



                    attachment = e.getJSONArray("attachments");
                    for(int p=0; p<attachment.length();p++){
                        obj = attachment.getJSONObject(p);
                        img = obj.getJSONObject("images");
                        thumb = img.getJSONObject("thumbnail");
                        imgStr = thumb.getString("url");
                    }

                    Log.d("--------------",imgStr);
                    contentList.add(content);
                    String chng = "&#8211;";

                    String  fnl_Str = name.replace(chng, "");
                    String slug = e.getString("slug");

                    slugList.add(slug);
                    latestData.add(fnl_Str);
                    imgLinks.add(imgStr);

                    map.put("id",  String.valueOf(i));
                    map.put("name", fnl_Str);
                    map.put("date", e.getString("date"));

                    mylist.add(map);            
                }

            }catch(ConnectionClosedException con){
                Toast.makeText(context, "Connextion Closed", Toast.LENGTH_SHORT).show();
            }catch(ConnectTimeoutException timeOut){
                Toast.makeText(context, "Connextion Time out", Toast.LENGTH_SHORT).show();
                Log.d("******************", "connection time out");
            }catch(JSONException e){
                Log.e("log_tag", "Error parsing data "+e.toString());
            } catch (ParseException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }catch (IOException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
            catch (Exception e){
                Log.e("Error: ", " "+e.getMessage());
            }

            return mylist;
        }

        @Override
        protected void onPostExecute(ArrayList<HashMap<String, String>> result) {


            showProgress.setVisibility(View.GONE);


            lazyAdapter = new LazyAdapter(context, imgLinks, latestData);
            listView.setAdapter(lazyAdapter);
            lazyAdapter.notifyDataSetChanged();

            listView.setOnItemClickListener(new OnItemClickListener() {
                public void onItemClick(AdapterView<?> parent, View view, int position, long id) {              


                    Intent intent=new Intent(context,WebViewActivity.class);
                    intent.putExtra("content", contentList.get(position));
                    intent.putExtra("shareUrl", shareUrl+slugList.get(position));
                    intent.putExtra("tab_value", 1);
                    startActivity(intent);
                    overridePendingTransition(R.anim.lefttorightslide,R.anim.righttoleftslide);

                }
            });

        }

        @Override
        protected void onPreExecute() {
            // TODO Auto-generated method stub
            super.onPreExecute();
            showProgress.setVisibility(View.VISIBLE);
        }

        @Override
        protected void onProgressUpdate(Integer... values) {
            // TODO Auto-generated method stub

            super.onProgressUpdate(values);
            showProgress.setVisibility(View.VISIBLE);
        }



    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        getMenuInflater().inflate(R.menu.activity_latest_tab, menu);
        return true;
    }


    @Override
    public void onBackPressed() {
        // TODO Auto-generated method stub

        if(isFinish){
            Intent intent = new Intent(context,MadhuriHomeScreen.class);
            startActivity(intent);
            overridePendingTransition(R.anim.slide_out_left,R.anim.slide_out_right);

            finish();
        }else{
            super.onBackPressed();
            overridePendingTransition(R.anim.slide_out_left,R.anim.slide_out_right);

        }


    }


}

这是LogTrace ..

12-17 13:00:36.964: E/WindowManager(9512): Activity com.phonethics.example.LatestTab has leaked window com.android.internal.policy.impl.PhoneWindow$DecorView@2c444278 that was originally added here
12-17 13:00:36.964: E/WindowManager(9512): android.view.WindowLeaked: Activity com.phonethics.madhuridixitnene.DanceTab has leaked window com.android.internal.policy.impl.PhoneWindow$DecorView@2c444278 that was originally added here
12-17 13:00:36.964: E/WindowManager(9512):  at android.view.ViewRootImpl.<init>(ViewRootImpl.java:344)
12-17 13:00:36.964: E/WindowManager(9512):  at android.view.WindowManagerImpl.addView(WindowManagerImpl.java:267)
12-17 13:00:36.964: E/WindowManager(9512):  at android.view.WindowManagerImpl.addView(WindowManagerImpl.java:215)
12-17 13:00:36.964: E/WindowManager(9512):  at android.view.WindowManagerImpl$CompatModeWrapper.addView(WindowManagerImpl.java:140)
12-17 13:00:36.964: E/WindowManager(9512):  at android.view.Window$LocalWindowManager.addView(Window.java:537)
12-17 13:00:36.964: E/WindowManager(9512):  at android.app.Dialog.show(Dialog.java:278)
12-17 13:00:36.964: E/WindowManager(9512):  at com.phonethics.example.LatestTab.onClick(LatestTab.java:243)
12-17 13:00:36.964: E/WindowManager(9512):  at android.view.View.performClick(View.java:3534)
12-17 13:00:36.964: E/WindowManager(9512):  at android.view.View$PerformClick.run(View.java:14263)
12-17 13:00:36.964: E/WindowManager(9512):  at android.os.Handler.handleCallback(Handler.java:605)
12-17 13:00:36.964: E/WindowManager(9512):  at android.os.Handler.dispatchMessage(Handler.java:92)
12-17 13:00:36.964: E/WindowManager(9512):  at android.os.Looper.loop(Looper.java:137)
12-17 13:00:36.964: E/WindowManager(9512):  at android.app.ActivityThread.main(ActivityThread.java:4441)
12-17 13:00:36.964: E/WindowManager(9512):  at java.lang.reflect.Method.invokeNative(Native Method)
12-17 13:00:36.964: E/WindowManager(9512):  at java.lang.reflect.Method.invoke(Method.java:511)
12-17 13:00:36.964: E/WindowManager(9512):  at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:784)
12-17 13:00:36.964: E/WindowManager(9512):  at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:551)
12-17 13:00:36.964: E/WindowManager(9512):  at dalvik.system.NativeStart.main(Native Method)
4

3 回答 3

0

点击是按钮试试这个。我认为它解决了你的问题

yes.setOnClickListener(new OnClickListener() {
    @Override
    public void onClick(View v) {
        if(isFinish){
            dialog.dismiss();
            dialog=null;
            Intent intent = new Intent(context,MadhuriHomeScreen.class);
            startActivity(intent);
            overridePendingTransition(R.anim.slide_out_left,R.anim.slide_out_right);
            finish();
        } else {
            finish();
        }
    }
});
于 2012-12-17T07:47:25.010 回答
0

您必须在完成活动之前关闭对话框。

yes.setOnClickListener(new OnClickListener() {
    @Override
    public void onClick(View v) {
        if(isFinish){
           dialog.dismiss();  
           Intent intent = new Intent(context,MadhuriHomeScreen.class);
           startActivity(intent);
           overridePendingTransition(R.anim.slide_out_left,R.anim.slide_out_right);
           finish();
       }else{
           dialog.dismiss();  
           finish();
       }
   }
});

我希望它会有所帮助

于 2012-12-17T07:47:32.023 回答
0

退出创建对话框的活动时,您必须关闭对话框。

所以,点击是按钮调用

dialog.dismiss();

然后调用

Intent intent = new Intent(context,MadhuriHomeScreen.class);
startActivity(intent); 

overridePendingTransition(R.anim.slide_out_left,R.anim.slide_out_right);
finish();

不仅是这种情况,而且当您离开当前活动时,请关闭对话框。

于 2012-12-17T07:47:52.810 回答