java.lang.RuntimeException:无法销毁活动

时间:2015-02-01 03:08:27

标签: android google-maps

在我的Android应用程序中,我在溢出菜单上给出了事件选项,在事件选项上加载了地图,但是当我按下后退按钮时,应用程序不幸停止了。我也发布了代码nad logcat。

AlertActivity.java

    public class Alert_activity extends Activity implements
    OnItemSelectedListener{
    Spinner s1,s2;
    TextView t1;
        @Override
        protected void onCreate(Bundle savedInstanceState) {
            // TODO Auto-generated method stub
            super.onCreate(savedInstanceState);
            setContentView(R.layout.activity_alert_activity);
            getActionBar().setDisplayHomeAsUpEnabled(true);
            s1 = (Spinner)findViewById(R.id.spinner1);
            s2 = (Spinner)findViewById(R.id.spinner2);
            s1.setOnItemSelectedListener(this);
        }
        @Override
        public void onItemSelected(AdapterView<?> arg0, View arg1, int arg2,
                long arg3) {
            // TODO Auto-generated method stub
            String sp1= String.valueOf(s1.getSelectedItem());
          //  Toast.makeText(this, sp1, Toast.LENGTH_SHORT).show();
            if(sp1.contentEquals("Events")) {
                List<String> list = new ArrayList<String>();
                list.add("Heavy Rain(mm/hr)");
                list.add("Smoke/Fog");
                list.add("Heat/Cold Wave");
                list.add("Strong Winds");
                ArrayAdapter<String> dataAdapter = new ArrayAdapter<String>(this,R.layout.simple_spinner_item, list);
                dataAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
                dataAdapter.notifyDataSetChanged();
                s2.setAdapter(dataAdapter);

                s2.setOnItemSelectedListener(new OnItemSelectedListener() {

                    @Override
                    public void onItemSelected(AdapterView<?> adapter, View v,
                            int position, long id) {


                        // On selecting a spinner item
                        String item = adapter.getItemAtPosition(position).toString();
                        Log.d("Inside loop","inside loop");

                        // Showing selected spinner item
                        //Toast.makeText(getApplicationContext(),
                            //  "You have selected : " + item, Toast.LENGTH_LONG).show();
                        Log.d("Item",item);
                         FragmentTransaction tx = getFragmentManager()
                                    .beginTransaction();


                         if(item=="Heavy Rain(mm/hr)")
                        {
                            tx.replace(android.R.id.content, new heavyrain());
                            /*Intent in = new Intent(getApplicationContext(),
                                    MainActivity1.class);

                                startActivityForResult(in, 100);*/
                        }
                         else if(item=="Smoke/Fog")
                         {
                             tx.replace(android.R.id.content, new smoke_fog());
                         }
                         else if(item=="Heat/Cold Wave")
                         {
                             tx.replace(android.R.id.content, new smoke_fog());
                         }
                         else if(item=="Strong Winds")
                         {
                             tx.replace(android.R.id.content, new smoke_fog());
                         }
                        tx.commit();
                    }

                    @Override
                    public void onNothingSelected(AdapterView<?> arg0) {
                        // TODO Auto-generated method stub

                    }
                });

            }
            if(sp1.contentEquals("Forecast")) {
                List<String> list = new ArrayList<String>();

                list.add("Cyclone");

                ArrayAdapter<String> dataAdapter2 = new ArrayAdapter<String>(this,
                    R.layout.simple_spinner_item, list);
                dataAdapter2.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
                dataAdapter2.notifyDataSetChanged();
                s2.setAdapter(dataAdapter2);
                s2.setOnItemSelectedListener(new OnItemSelectedListener() {

                    @Override
                    public void onItemSelected(AdapterView<?> adapter, View v,
                            int position, long id) {
                        // On selecting a spinner item
                        String item = adapter.getItemAtPosition(position).toString();
                        Log.d("Inside loop","inside loop");

                        // Showing selected spinner item
                        //Toast.makeText(getApplicationContext(),
                            //  "You have selected : " + item, Toast.LENGTH_LONG).show();
                        Log.d("Item",item);
                         FragmentTransaction tx = getFragmentManager()
                                    .beginTransaction();

                        if(item=="Cyclone")
                        {
                            tx.replace(android.R.id.content, new Cyclone());
                            /*Intent in = new Intent(getApplicationContext(),
                                MapActivity.class);

                            startActivityForResult(in, 100);*/

                        }
                /*      else if(item=="Heavy Rain")
                        {
                            tx.replace(android.R.id.content, new forecast_heavyrain());

                        }
                        else if(item=="Cloudburst")
                        {
                            tx.replace(android.R.id.content, new forecast_cloudburst());

                        }*/
                        tx.commit();
                    }

                    @Override
                    public void onNothingSelected(AdapterView<?> arg0) {
                        // TODO Auto-generated method stub

                    }
                });
            }

            if(sp1.contentEquals("Nowcast")) {
                List<String> list = new ArrayList<String>();
                list.add("Heavy Rain");

                list.add("Cloudburst");
                ArrayAdapter<String> dataAdapter2 = new ArrayAdapter<String>(this,
                    R.layout.simple_spinner_item, list);
                dataAdapter2.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
                dataAdapter2.notifyDataSetChanged();
                s2.setAdapter(dataAdapter2);
                s2.setOnItemSelectedListener(new OnItemSelectedListener() {

                    @Override
                    public void onItemSelected(AdapterView<?> adapter, View v,
                            int position, long id) {
                        // On selecting a spinner item
                        String item = adapter.getItemAtPosition(position).toString();
                        Log.d("Inside loop","inside loop");

                        // Showing selected spinner item
                        //Toast.makeText(getApplicationContext(),
                            //  "You have selected : " + item, Toast.LENGTH_LONG).show();
                        Log.d("Item",item);
                         FragmentTransaction tx = getFragmentManager()
                                    .beginTransaction();

                         if(item=="Heavy Rain")
                        {
                            tx.replace(android.R.id.content, new forecast_heavyrain());
                            /*Intent in = new Intent(getApplicationContext(),
                                    MainActivity1.class);

                                startActivityForResult(in, 100);*/
                        }
                        else if(item=="Cloudburst")
                        {
                            tx.replace(android.R.id.content, new forecast_cloudburst());
                            /*Intent in = new Intent(getApplicationContext(),
                                    MainActivity1.class);

                                startActivityForResult(in, 100);*/
                        }
                        tx.commit();
                    }

                    @Override
                    public void onNothingSelected(AdapterView<?> arg0) {
                        // TODO Auto-generated method stub

                    }

                });

            }


private GoogleMap googleMap;
    PolylineOptions polylineOptions=new PolylineOptions(); 
    ArrayList<LatLng> points = new ArrayList<LatLng>();
    String lat12[] = {"30.5","31.0","31.2","31.8","30.65"};
    String long12[] = {"79.9","78.1","78.0","78.8","78.8"};
    String time11[]={"6AUG2014 20:45GMT","6AUG2014 20:45GMT","6AUG2014 20:45GMT","6AUG2014 20:45GMT","6AUG2014 22:45GMT"};
    TextView rain;
    TextView rain_lat;
    TextView rain_long;

    String[] time=new String[100];
    String[] date=new String[100];
    String[] rain_lat1=new String[100];
    String[] rain_long1=new String[100];
    String[] rad_inf1=new String[100];
    ArrayList high_rain = new ArrayList();


    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
            Bundle savedInstanceState) {
         View root = (LinearLayout) inflater.inflate(R.layout.forecast_heavyrain, container,false);
         initilizeMap();
         return root;
    }
        private void initilizeMap()
        {
            arrayPoints = new ArrayList<LatLng>();

            MapFragment fm = (MapFragment) getFragmentManager().findFragmentById(
            R.id.fragment4);
            googleMap = fm.getMap();
            googleMap.setMyLocationEnabled(true); 
            googleMap.setOnMapClickListener(this); 
            googleMap.setOnMapLongClickListener(this);


            ArrayList<NameValuePair> params = new ArrayList<NameValuePair>();
            JSONParser jsonParser = new JSONParser();
            params.add(new BasicNameValuePair("LAT", "LAT"));
            params.add(new BasicNameValuePair("LONGITUDE", "LONG"));
            Log.d("params", params.toString());
            // getting weather details by making HTTP request
            // Note that weather details url will use GET request
            JSONObject json = jsonParser.makeHttpRequest(url_Weather_details1,
                    "GET", params);
            // check your log for json response
            Log.d("Weather Details", json.toString());
            // json success tag
            int success = 0;
            try {
                success = json.getInt(TAG_SUCCESS);
            } 
            catch (JSONException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
            if (success == 1) {
                // successfully received weather details
                JSONArray stationObj = null;
                try {
                    stationObj = json.getJSONArray(TAG_WEATHER);

                    // JSON Array

                    int lengthJsonArr = stationObj.length();
                    Log.d("length",String.valueOf(lengthJsonArr));

                    for (int i = 0; i < lengthJsonArr; i++) 
                    //for (int i = 0; i < lat12.length; i++) 
                    {
                        station = stationObj.getJSONObject(i);
                        /*String time1=station.getString(TAG_time);
                        time[i]=time1;*/

                        String lat1=station.getString(TAG_rain_lat);
                        rain_lat1[i]=lat1;

                        String long1=station.getString(TAG_rain_long);
                        rain_long1[i]=long1;

                        String date_nowcast=station.getString(TAG_date);
                        date[i]=date_nowcast;

                        String time_nowcast=station.getString(TAG_time);
                        time[i]=time_nowcast;

                        String rad_inf=station.getString(TAG_rad_inf);
                        rad_inf1[i]=rad_inf;

                    }
                //  Log.d("Length",String.valueOf(time.length));
                    int i;
                    for ( i = 0; i < lengthJsonArr; i++) 
                    {
                        //for(i=0; i<time11.length;i++)
                        //{
                        //Log.d("high rain size",String.valueOf(highest_rain.length));
                        //double high_rain2=Double.parseDouble(time[i]);


                        double lat2=Double.parseDouble(rain_lat1[i]);
                        Log.d("Latitude===>",String.valueOf(lat2));

                        double long2=Double.parseDouble(rain_long1[i]);
                        Log.d("Longitude===>",String.valueOf(long2));

                        Log.d("time_nowcast==>",time[i]);

                        Log.d("Date_nowcast==>",date[i]);
                        Log.d("Radius of influence==>",rad_inf1[i]);

                        /*t1=(TextView)getView().findViewById(R.id.rain11);
                        t1.setText(String.valueOf(high_rain2));*/

                    //    double lat2=Double.parseDouble(lat12[i]);
                    //  Log.d("Latitude===>",String.valueOf(lat2));
                    /// double long2=Double.parseDouble(long12[i]);
                    //  Log.d("Longitude===>",String.valueOf(long2));
                        //double high_rain2=Double.parseDouble(time11[i]);
                    //  Log.d("time===>",String.valueOf(time11[i])); 

                        LatLng position = new LatLng(lat2, long2);
                         CameraPosition cameraPosition;// = new CameraPosition(latLng, 0, 0, 0);
                         cameraPosition = CameraPosition.fromLatLngZoom(position, (float) 14.0);


                        Marker marker =  googleMap.addMarker(new MarkerOptions().position(new LatLng(lat2, long2)) .title(" Forecast Date: "+date[i]+" Forecast Time:"+ time[i]).snippet(" Radius of Influence:"+rad_inf1[i]+" kms").icon(BitmapDescriptorFactory.fromResource(R.drawable.heavy_rain11)));

                        points.add(position);
                    //  Log.d("i inside for loop",String.valueOf(i));


                        }



                /*  polylineOptions.addAll(points);
                    polylineOptions.color(Color.RED);
                    polylineOptions.width(7); 
                    polylineOptions.width(7); 
                    googleMap.addPolyline(polylineOptions);*/

        }

                catch (Exception e) 
                {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                }
            }
            else if(success==2)
            {
                Log.d("success 2","success 2");



            }
            else if(success==3)
            {
                Log.d("success 3","success 3");

            }   
}
        @Override
        public void onMapLongClick(LatLng arg0) {
            // TODO Auto-generated method stub

        }
        @Override
        public void onMapClick(LatLng arg0) {
            // TODO Auto-generated method stub

        }
        public void onDestroyView() 
         {
                 super.onDestroyView(); 
                 Fragment fragment = (getFragmentManager().findFragmentById(R.id.fragment4));  
                 FragmentTransaction ft = getActivity().getFragmentManager().beginTransaction();
                 ft.remove(fragment);
                 ft.commit();
                 super.onDestroy();
         }
        @Override
        public void onDetach() {
            super.onDetach();

            try {
                Field childFragmentManager = Fragment.class.getDeclaredField("mChildFragmentManager");
                childFragmentManager.setAccessible(true);
                childFragmentManager.set(this, null);

            } catch (NoSuchFieldException e) {
                throw new RuntimeException(e);
            } catch (IllegalAccessException e) {
                throw new RuntimeException(e);
            }
        }

        }    
    }

    @Override
    public void onNothingSelected(AdapterView<?> arg0) {
        // TODO Auto-generated method stub

    }
    public boolean onCreateOptionsMenu(Menu menu) {
        MenuInflater inflater = getMenuInflater();
        inflater.inflate(R.menu.items, menu);

        return super.onCreateOptionsMenu(menu);

    }
    @Override
    public boolean onOptionsItemSelected(MenuItem item) {

        super.onOptionsItemSelected(item);

        switch(item.getItemId()){
            case R.id.exit:
                android.os.Process.killProcess(android.os.Process.myPid());
                System.exit(1);

            case R.id.Feedback:
                LocationFound();
                return true;

            case R.id.Events:
                Alert();
                return true;


            case android.R.id.home:
                finish();



        }

        return true;
    }
    private void LocationFound() {
        Intent in = new Intent(getApplicationContext(),Feedback.class);
        startActivityForResult(in, 100);
    }
    private void Alert() {
        Intent in = new Intent(getApplicationContext(),Alert_activity.class);
        startActivityForResult(in, 100);
    }


    @Override
    public void onBackPressed() { //here I capture the event onBackPress 
        super.onBackPressed(); 
        onStop(); //call onStop
    }

}

logcat的

    02-01 08:27:22.651: E/AndroidRuntime(12401): FATAL EXCEPTION: main
    02-01 08:27:22.651: E/AndroidRuntime(12401): Process: com.example.gpstracking, PID: 12401
    02-01 08:27:22.651: E/AndroidRuntime(12401): java.lang.RuntimeException: Unable to destroy activity {com.example.gpstracking/com.example.gpstracking.Alert_activity}: java.lang.IllegalStateException: Activity has been destroyed
    02-01 08:27:22.651: E/AndroidRuntime(12401):    at android.app.ActivityThread.performDestroyActivity(ActivityThread.java:3515)
    02-01 08:27:22.651: E/AndroidRuntime(12401):    at android.app.ActivityThread.handleDestroyActivity(ActivityThread.java:3533)
    02-01 08:27:22.651: E/AndroidRuntime(12401):    at android.app.ActivityThread.access$1400

1 个答案:

答案 0 :(得分:0)

尝试在onBackPressed()方法中使用此代码,而不是调用onStop():

@Override
    public void onBackPressed(){
        moveTaskToBack(true);
    }

希望这会有所帮助!!