0

我正在开发一个使用片段的应用程序。在线程应用程序崩溃时调用 Web 服务。当方向改变时,日志以红色显示以下异常:

12-14 14:36:51.770: E/WindowManager(5270): Activity com.weg.ecatalogfragment.ECatalogFragmentActivity has leaked window com.android.internal.policy.impl.PhoneWindow$DecorView@41457e20 that was originally added here
12-14 14:36:51.770: E/WindowManager(5270): android.view.WindowLeaked: Activity com.weg.ecatalogfragment.ECatalogFragmentActivity has leaked window com.android.internal.policy.impl.PhoneWindow$DecorView@41457e20 that was originally added here
12-14 14:36:51.770: E/WindowManager(5270):  at android.view.ViewRootImpl.<init>(ViewRootImpl.java:345)
12-14 14:36:51.770: E/WindowManager(5270):  at android.view.WindowManagerImpl.addView(WindowManagerImpl.java:268)
12-14 14:36:51.770: E/WindowManager(5270):  at android.view.WindowManagerImpl.addView(WindowManagerImpl.java:216)
12-14 14:36:51.770: E/WindowManager(5270):  at android.view.WindowManagerImpl$CompatModeWrapper.addView(WindowManagerImpl.java:141)
12-14 14:36:51.770: E/WindowManager(5270):  at android.view.Window$LocalWindowManager.addView(Window.java:537)
12-14 14:36:51.770: E/WindowManager(5270):  at android.app.Dialog.show(Dialog.java:278)
12-14 14:36:51.770: E/WindowManager(5270):  at android.app.ProgressDialog.show(ProgressDialog.java:117)
12-14 14:36:51.770: E/WindowManager(5270):  at android.app.ProgressDialog.show(ProgressDialog.java:100)
12-14 14:36:51.770: E/WindowManager(5270):  at android.app.ProgressDialog.show(ProgressDialog.java:95)
12-14 14:36:51.770: E/WindowManager(5270):  at com.weg.ecatalogfragment.HomeScreen.syncWithServer(HomeScreen.java:416)
12-14 14:36:51.770: E/WindowManager(5270):  at com.weg.ecatalogfragment.HomeScreen.onClick(HomeScreen.java:622)
12-14 14:36:51.770: E/WindowManager(5270):  at android.view.View.performClick(View.java:3528)
12-14 14:36:51.770: E/WindowManager(5270):  at android.view.View$PerformClick.run(View.java:14235)
12-14 14:36:51.770: E/WindowManager(5270):  at android.os.Handler.handleCallback(Handler.java:605)
12-14 14:36:51.770: E/WindowManager(5270):  at android.os.Handler.dispatchMessage(Handler.java:92)
12-14 14:36:51.770: E/WindowManager(5270):  at android.os.Looper.loop(Looper.java:137)
12-14 14:36:51.770: E/WindowManager(5270):  at android.app.ActivityThread.main(ActivityThread.java:4424)
12-14 14:36:51.770: E/WindowManager(5270):  at java.lang.reflect.Method.invokeNative(Native Method)
12-14 14:36:51.770: E/WindowManager(5270):  at java.lang.reflect.Method.invoke(Method.java:511)
12-14 14:36:51.770: E/WindowManager(5270):  at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:817)
12-14 14:36:51.770: E/WindowManager(5270):  at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:584)
12-14 14:36:51.770: E/WindowManager(5270):  at dalvik.system.NativeStart.main(Native Method)

再次调用此 Activity 后,由于代码流的原因,上下文无法出现在警报框和应用程序崩溃。

12-14 14:37:16.950: E/AndroidRuntime(5270): FATAL EXCEPTION: main
12-14 14:37:16.950: E/AndroidRuntime(5270): java.lang.NullPointerException
12-14 14:37:16.950: E/AndroidRuntime(5270):     at android.app.AlertDialog.resolveDialogTheme(AlertDialog.java:142)
12-14 14:37:16.950: E/AndroidRuntime(5270):     at android.app.AlertDialog.<init>(AlertDialog.java:98)
12-14 14:37:16.950: E/AndroidRuntime(5270):     at android.app.ProgressDialog.<init>(ProgressDialog.java:78)
12-14 14:37:16.950: E/AndroidRuntime(5270):     at android.app.ProgressDialog.show(ProgressDialog.java:111)
12-14 14:37:16.950: E/AndroidRuntime(5270):     at android.app.ProgressDialog.show(ProgressDialog.java:100)
12-14 14:37:16.950: E/AndroidRuntime(5270):     at android.app.ProgressDialog.show(ProgressDialog.java:95)
12-14 14:37:16.950: E/AndroidRuntime(5270):     at com.weg.ecatalogfragment.HomeScreen$1.dispatchMessage(HomeScreen.java:141)
12-14 14:37:16.950: E/AndroidRuntime(5270):     at android.os.Looper.loop(Looper.java:137)
12-14 14:37:16.950: E/AndroidRuntime(5270):     at android.app.ActivityThread.main(ActivityThread.java:4424)
12-14 14:37:16.950: E/AndroidRuntime(5270):     at java.lang.reflect.Method.invokeNative(Native Method)
12-14 14:37:16.950: E/AndroidRuntime(5270):     at java.lang.reflect.Method.invoke(Method.java:511)
12-14 14:37:16.950: E/AndroidRuntime(5270):     at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:817)
12-14 14:37:16.950: E/AndroidRuntime(5270):     at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:584)
12-14 14:37:16.950: E/AndroidRuntime(5270):     at dalvik.system.NativeStart.main(Native Method)

要么它不应该再次调用 Activity,要么此时流应该停止。

如果使用此片段,请建议我,我应该如何处理我的网络服务。下面是我的代码:

public class HomeScreen extends Fragment implements OnClickListener,OnItemSelectedListener,IServerResponse
{

    private Handler _handler = new Handler() {
        public void dispatchMessage(Message msg) {
            switch (msg.arg2) {
            case Constant.PID_GETUPDATEDATA:
                final ProgressDialog progressDialog = ProgressDialog.show(HomeScreen.this.getActivity(),"", Constant.MSG_SYNC);
                final String msgData = (String) msg.obj;
                new Thread(new Runnable() {
                    public void run() {
                        Looper.prepare();
                        try{
                            if (msgData.equalsIgnoreCase("We apologize, no data was found.")) {

                                HomeScreen.this.getActivity().runOnUiThread(new Runnable() {
                                    public void run() {
                                        Constant.showAlertDialog(Constant.DIALOG_TITLE_ERROR,
                                                Constant.MSG_NOUPDATE, HomeScreen.this.getActivity(), false);       
                                    }
                                });

                            }else{
                                JSONObject jsonObject=new JSONObject(msgData);
                                JSONObject electricObject = jsonObject.getJSONObject("NewDataSet");
                                JSONArray electricDBArray=electricObject.getJSONArray("Electrical_DB");

                                int count=electricDBArray.length();

                                String PrivousDateTime=myPref.getString("PREVIOUS_DATETIME", "");
                                if(PrivousDateTime.equals("")||PrivousDateTime==null)
                                {                                                   
                                    _eCatalogueTable.deleteTable(ECatalogueDatabase.DATABASE_TABLE);
                                }

                                for(int j=0;j<count;j++)
                                {
                                    String productLineID=electricDBArray.getJSONObject(j).getString("id");
                                    String productLine=electricDBArray.getJSONObject(j).getString("productline");
                                    String hp = electricDBArray.getJSONObject(j).getString("outputhp");
                                    String rpm = electricDBArray.getJSONObject(j).getString("rpm");
                                    String voltage = electricDBArray.getJSONObject(j).getString("voltage");
                                    String frame = electricDBArray.getJSONObject(j).getString("frame");
                                    if(!isProductIDPresentInDb(productLineID))
                                    {                           
                                        _eCatalogueTable.InsertECatalogue(productLineID,productLine,hp, rpm, voltage, frame);
                                    }else
                                    {
                                        _eCatalogueTable.updateECatalogue(productLineID,productLine, hp, rpm, voltage, frame);
                                    }
                                }       

                                HomeScreen.this.getActivity().runOnUiThread(new Runnable() {
                                    public void run() {
                                        Constant.showAlertDialog(Constant.DIALOG_TITLE_SUCCESS,Constant.MSG_SUCCESS, HomeScreen.this.getActivity(), false); 
                                        findGMTDateTime();
                                        _mEditPref=myPref.edit();
                                        _mEditPref.putString("PREVIOUS_DATETIME", dateTimeValue);
                                        _mEditPref.commit();
                                    }
                                });
                            }
                        }catch(Exception e)
                        {
                            e.printStackTrace();
                            HomeScreen.this.getActivity().runOnUiThread(new Runnable() {
                                public void run() {
                                    Constant.showAlertDialog(Constant.DIALOG_TITLE_ERROR,
                                            Constant.MSG_SERVER_FAIL, HomeScreen.this.getActivity(), false);        
                                }
                            });

                        }
                        progressDialog.cancel();
                    }

                }).start();
                break; 
            case Constant.PID_ALERTDIGLOG:
                Constant.showAlertDialog(Constant.DIALOG_TITLE_ERROR,Constant.MSG_SERVER_FAIL, HomeScreen.this.getActivity(),false);
                break;

            }
        };
    };

    @SuppressWarnings({ "unchecked", "rawtypes" })
    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,  Bundle savedInstanceState) {
        mContentView = inflater.inflate(R.layout.home_screen , container, false);

        _eCatalogueTable=new ECatalogueDatabase(HomeScreen.this.getActivity());
        _eCatalogueTable.open();

        if (getResources().getConfiguration().orientation == Configuration.ORIENTATION_LANDSCAPE) {
            _headetRelativelayout=(RelativeLayout)mContentView.findViewById(R.id.header_layout);
            _headetRelativelayout.setVisibility(View.GONE);

        }
        if(savedInstanceState!=null)
        {
            saveState="SavedInstance";
            rotateSaveInstace=true;
            Constant.checkPdf=false;
            //Toast.makeText(this.getActivity(),"savedInstaceState", Toast.LENGTH_LONG).show();
        }else
        {
            saveStateBoolea=true;
            saveState="NoSavedInstance";
            //  Toast.makeText(this.getActivity(),"No savedInstaceState", Toast.LENGTH_LONG).show();
        }


        _productText=(TextView)mContentView.findViewById(R.id.productline_txt);
        _hpText=(TextView)mContentView.findViewById(R.id.hp_txt);
        _rpmText=(TextView)mContentView.findViewById(R.id.rpm_txt);

        _voltageText=(TextView)mContentView.findViewById(R.id.voltage_txt);
        _frameSizeText=(TextView)mContentView.findViewById(R.id.frame_txt);

        _searchBypartEditText=(EditText)mContentView.findViewById(R.id.searchpart_edittxt);

        _searchButton=(Button)mContentView.findViewById(R.id.serach_btn);
        _searchButton.setEnabled(false);
        _searchButton.setOnClickListener(this);

        _syncButton=(Button)mContentView.findViewById(R.id.sync_btn);
        _syncButton.setOnClickListener(this);

        _productSpinner=(Spinner)mContentView.findViewById(R.id.productline_spinner);
        _productSpinner.setOnItemSelectedListener(this);

        _hpSpinner=(Spinner)mContentView.findViewById(R.id.hp_spinner);
        _hpSpinner.setOnItemSelectedListener(this);

        _rpmSpinner=(Spinner)mContentView.findViewById(R.id.rpm_spinner);
        _rpmSpinner.setOnItemSelectedListener(this);

        _voltageSpinner=(Spinner)mContentView.findViewById(R.id.voltage_spinner);
        _voltageSpinner.setOnItemSelectedListener(this);

        _frameSpinner=(Spinner)mContentView.findViewById(R.id.frame_spinner);
        _frameSpinner.setOnItemSelectedListener(this);

        _productRealtiveLayout=(RelativeLayout)mContentView.findViewById(R.id.product_layout);
        _productRealtiveLayout.setOnClickListener(this);

        _hpRelativeLayout=(RelativeLayout)mContentView.findViewById(R.id.hp_layout);
        _hpRelativeLayout.setOnClickListener(this);

        _rpmRelativeLayout=(RelativeLayout)mContentView.findViewById(R.id.rpm_layout);
        _rpmRelativeLayout.setOnClickListener(this);

        _voltageRelativeLayout=(RelativeLayout)mContentView.findViewById(R.id.voltage_layout);
        _voltageRelativeLayout.setOnClickListener(this);

        _framSizeRelativeLayout=(RelativeLayout)mContentView.findViewById(R.id.frame_layout);
        _framSizeRelativeLayout.setOnClickListener(this);

        useTextwatcher();

        _mHPArrayList.add(0, getString(R.string.hp_txt));
        _mRPMArrayList.add(0, getString(R.string.rpm_txt));
        _mVoltageArrayList.add(0,getString(R.string.voltage_txt));
        _mFrameSizeLineArrayList.add(0,getString(R.string.frame_txt));

        _productSpinner.setSelection(0);
        _hpSpinner.setSelection(0);

        _rpmSpinner.setSelection(0);
        _voltageSpinner.setSelection(0);
        _frameSpinner.setSelection(0);

        fetchProductLineFromDatabase();

        _productLineArrayAdapter = new ArrayAdapter(this.getActivity(),android.R.layout.simple_spinner_dropdown_item,_mProductLineArrayList);

        _hpArrayAdapter=new ArrayAdapter(this.getActivity(),android.R.layout.simple_spinner_dropdown_item,_mHPArrayList);
        _rpmArrayAdapter = new ArrayAdapter(this.getActivity(),android.R.layout.simple_spinner_dropdown_item,_mRPMArrayList);
        _voltageArrayAdapter = new ArrayAdapter(this.getActivity(),android.R.layout.simple_spinner_dropdown_item,_mVoltageArrayList);
        _frameSizeArrayAdapter=new ArrayAdapter(this.getActivity(),android.R.layout.simple_spinner_dropdown_item,_mFrameSizeLineArrayList);

        _productSpinner.setAdapter(_productLineArrayAdapter);
        _hpSpinner.setAdapter(_hpArrayAdapter);
        _rpmSpinner.setAdapter(_rpmArrayAdapter);
        _voltageSpinner.setAdapter(_voltageArrayAdapter);
        _frameSpinner.setAdapter(_frameSizeArrayAdapter);


        // GMT Date Time
        date=new Date();
        simpleDateFormat=new SimpleDateFormat("MM/dd/yyyy HH:mm:ss");
        myPref=getActivity().getPreferences(Context.MODE_PRIVATE);
        String PrivousDateTime=myPref.getString("PREVIOUS_DATETIME", "");
        boolean firstCheckAlert=myPref.getBoolean("FIRST_ALRT", firstTimeShowAllert);
        if(!firstCheckAlert)
        {
            showMessageAlert();
        }
        if(PrivousDateTime.equals("")||PrivousDateTime==null)
        {
            dateTimeValue= "01/01/2012 00:00:00";
        }else
        {
            dateTimeValue=PrivousDateTime;
        }
        return mContentView;
    }

    private void syncWithServer() {


        if (NetworkAvailablity.checkNetworkStatus(HomeScreen.this.getActivity()))
        {

            final ProgressDialog progressDialog = ProgressDialog.show(HomeScreen.this.getActivity(),"",Constant.MSG_SYNC);
            new Thread(new Runnable() {
                public void run() {
                    String response = "";
                    SoapObject request = new SoapObject(WebServiceDetails.SERVICENAMESPACE,WebServiceDetails.METHOD_CHECKLATESTDATADATE);
                    request.addProperty("lastmodifieddate",dateTimeValue);
                    SoapSerializationEnvelope envelope = new SoapSerializationEnvelope(SoapEnvelope.VER11);
                    envelope.dotNet = true;
                    envelope.setOutputSoapObject(request);
                    AndroidHttpTransport httpTransport = new AndroidHttpTransport(WebServiceDetails.URL);
                    httpTransport.debug = true;
                    try {
                        httpTransport.call(WebServiceDetails.SOAP_CHECKLATESTDATADATE, envelope); // send

                        Object data = envelope.getResponse();
                        if (data instanceof SoapObject) {
                            SoapObject data2 = (SoapObject) data;
                            response = data2.toString();
                        } else if (data instanceof SoapPrimitive) {
                            SoapPrimitive data3 = (SoapPrimitive) data;
                            response = data3.toString();
                        } else if (data != null) {
                            response = data.toString();
                        } else if (data == null) {
                            response = "nodata";
                        }
                        serverResponse(response,Constant.PID_GETUPDATEDATA);
                    }catch (Exception e) {
                        e.printStackTrace();
                        serverResponse(null,Constant.PID_ALERTDIGLOG);
                    }
                    progressDialog.dismiss();
                }
            }).start();
        }
        else {
            Constant.showAlertDialog(Constant.DIALOG_TITLE_ERROR,Constant.MSG_INTERNETERROR, HomeScreen.this.getActivity(),false);
        }

    }


    public void onClick(View v) {
        fetchTextvalue();
        switch (v.getId()) {

        case R.id.serach_btn:
            if (NetworkAvailablity.checkNetworkStatus(HomeScreen.this.getActivity())){
                FragmentManager fm = this.getActivity().getSupportFragmentManager();
                int count=fm.getBackStackEntryCount();
                System.out.println("gdfgdgcvbccccccccccccccccccc "+count);
                for(int i = 0; i < count; ++i) {    
                    fm.popBackStack();
                }
                fetchTextvalue();


                if(!(_fetchProductText.equalsIgnoreCase(getString(R.string.product_txt))||_fetchHpText.equalsIgnoreCase( getString(R.string.hp_txt))
                        ||_fetchRPMText.equalsIgnoreCase( getString(R.string.rpm_txt))||_fetchVoltageText.equalsIgnoreCase(getString(R.string.voltage_txt))
                        ||_fetchFrameSizeText.equalsIgnoreCase(getString(R.string.frame_txt))))
                {
                    if(_mGetEditValue.equalsIgnoreCase(getString(R.string.enterpart_txt))||_mGetEditValue==null)
                    {
                        dataSheetCall();
                    }else
                    {
                        Constant.showAlertDialog(Constant.DIALOG_TITLE_ERROR, Constant.MSG_ENABLESEARCH, HomeScreen.this.getActivity(), false);
                        _searchBypartEditText.setText("");
                        _searchButton.setEnabled(true);
                        _mGetEditValue=(getString(R.string.enterpart_txt));
                    }
                }else if((!_mGetEditValue.equalsIgnoreCase(getString(R.string.enterpart_txt)))||_mGetEditValue!=null)
                {
                    if((_fetchProductText.equalsIgnoreCase(getString(R.string.product_txt))&&_fetchHpText.equalsIgnoreCase( getString(R.string.hp_txt))
                            &&_fetchRPMText.equalsIgnoreCase( getString(R.string.rpm_txt))&&_fetchVoltageText.equalsIgnoreCase(getString(R.string.voltage_txt))
                            &&_fetchFrameSizeText.equalsIgnoreCase(getString(R.string.frame_txt))))
                    {
                        dataSheetCall();
                    }
                    else
                    {
                        Constant.showAlertDialog(Constant.DIALOG_TITLE_ERROR, Constant.MSG_ENABLESEARCH, HomeScreen.this.getActivity(), false);
                        _searchBypartEditText.setText("");
                        _searchButton.setEnabled(true);
                        resetValue();

                    }
                }
            }else{
                Constant.showAlertDialog(Constant.DIALOG_TITLE_ERROR,Constant.MSG_INTERNETERROR, HomeScreen.this.getActivity(),false);
                _productSpinner.setSelection(0);
            }

            break;          



            case R.id.sync_btn:
        syncWithServer();

        break;
        default:
            break;
        }       
    }

    private void dataSheetCall()
    {
        if (getResources().getConfiguration().orientation != Configuration.ORIENTATION_LANDSCAPE) {
            Intent datasheetIntent=new Intent(this.getActivity(),DataSheetScreenActivity.class);
            datasheetIntent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
            datasheetIntent.putExtra("PRODUCTLINE", _productString);
            datasheetIntent.putExtra("HP", _hpString);
            datasheetIntent.putExtra("RPM",_rpmString);
            datasheetIntent.putExtra("VOLTAGE", _voltageString);
            datasheetIntent.putExtra("FRAMESIZE", _frameSizeString);
            datasheetIntent.putExtra("PART NUMBER", _mGetEditValue);
            Constant.putAllValue(_productString, _hpString, _rpmString, _voltageString, _frameSizeString,_mGetEditValue);
            startActivity(datasheetIntent);
        } else {

            if(saveStateBoolea)
            {
                ImageFragment rightFrag = (ImageFragment) getFragmentManager().findFragmentByTag("imageFragmentTag");
                FragmentTransaction ft = getFragmentManager().beginTransaction();
                ft.remove(rightFrag);
                ft.commit();
                saveStateBoolea=false;
            }else if(saveState.equalsIgnoreCase("SavedInstance")&&(rotateSaveInstace==true))
            {
                ImageFragment rightFrag = (ImageFragment) getFragmentManager().findFragmentByTag("imageFragmentTag");
                FragmentTransaction ft = getFragmentManager().beginTransaction();
                ft.remove(rightFrag);
                ft.commit();
                rotateSaveInstace=false;
            }

            DataSheetScreenFragment dataSheetFragment = new DataSheetScreenFragment();
            fragmentTransaction = this.getActivity().getSupportFragmentManager().beginTransaction();
            fragmentTransaction.add(R.id.top_right_datasheet_relative_layout, dataSheetFragment, "rightDrawingFragmentTag"); //First parameter is the container id
            fragmentTransaction.addToBackStack("1");
            fragmentTransaction.show(dataSheetFragment);
            fragmentTransaction.commit();

            Constant.putAllValue(_productString, _hpString, _rpmString, _voltageString, _frameSizeString,_mGetEditValue);

            _pdfIcon=(ImageButton)this.getActivity().findViewById(R.id.pdf_icon);
            _pdfIcon.setVisibility(View.VISIBLE);

            _pdfText=(TextView)this.getActivity().findViewById(R.id.pdf_txt);
            _pdfText.setVisibility(View.VISIBLE);
        }
        resetValue();
    }


    public void onNothingSelected(AdapterView<?> arg0) {
        Toast.makeText(this.getActivity(), "No select", Toast.LENGTH_LONG).show();
    }
    @Override
    public void onDestroy() {
        _eCatalogueTable.close();
        super.onDestroy();
    }
    @Override
    public void onResume() {
        super.onResume();
        if(!Constant.checkPdf)
        {
            _productSpinner.setSelection(0);
        }

    }

    public void serverResponse(String response, int processid) {
        Message msg = new Message();
        msg.arg2 = processid;
        msg.obj = response;
        _handler .sendMessage(msg);     
    }
    @Override
    public void onPause() {
        super.onPause();

    }

}
4

2 回答 2

2

可能是解决方案是在退出活动之前调用dismiss()您创建的对话框。ViewRootImpl.java

编辑:

看到你的错误在下面说:

android.view.WindowLeaked: Activity com.weg.ecatalogfragment.ECatalogFragmentActivity has leaked window com.android.internal.policy.impl.PhoneWindow$DecorView@41457e20 that was originally added here
at android.view.ViewRootImpl.<init>(ViewRootImpl.java:345)

因此,当您传递构造函数时,每个视图都有对其父上下文的引用。如果你离开一个 Activity 而不破坏 Dialogs 和其他动态创建视图的 Activity,它们仍然持有对你的 Activity 的引用(如果你使用thisas Context: like创建new ANY(this)),所以它不会被 GC 收集,从而导致内存泄漏

于 2012-12-14T09:44:35.170 回答
0

添加到 android manifest.xml 中的活动标签中

<activity android:name=".activityname"
              android:label="@string/app_name" android:configChanges="orientation"
于 2012-12-14T09:35:34.527 回答