0

What i am doing :: i am trying to close the activity using code

if (getIntent().getBooleanExtra("LOGOUT", false))
{
      SplashActivity.this.finish();
}

What is happening::

  • my control comes to that line (i am passing intent from previous activity) but the finish is not working
  • why is this happening ?
  • How can i overcome this ?

SplashActivity.java

public class SplashActivity extends FragmentActivity {
    /** Called when the activity is first created. */


    JSONObject jsonobject;  
    JSONArray jsonarray;
    private String Content;
    DatabaseAdapter databaseHelper;
    TextView txtSplashTitle,txtSplashDesc;
    Cursor cursor;
    LocationManager locationManager;
    LocationListener locationListener;
    public static String srcLatitude;
    public static String srcLongitude;
    public static String destLatitude;
    public static String destLongitude;
    public static String buffetOfferId;
    private String tag_json_obj = "jobj_req";
    private ProgressDialog pDialog;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        if (getIntent().getBooleanExtra("LOGOUT", false))
        {
            SplashActivity.this.finish();
        }

        //Remove title bar
        this.requestWindowFeature((int) Window.FEATURE_NO_TITLE);
        //Remove notification bar
        this.getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN, WindowManager.LayoutParams.FLAG_FULLSCREEN);
        //set content view AFTER ABOVE sequence (to avoid crash)
        setContentView(R.layout.splash);
        locationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
        if ( !locationManager.isProviderEnabled( LocationManager.GPS_PROVIDER ) ) {
            showDialog();
        }
        //Delete database if it exists
        SplashActivity.this.deleteDatabase(FindMyBuffetConstants.DATABASE_NAME);
        databaseHelper = new DatabaseAdapter(this);


        pDialog = new ProgressDialog(this);
        pDialog.setMessage("Loading...");
        pDialog.setCancelable(false);

        JsonObjReqWithVolly();
    }

    private void JsonObjReqWithVolly() {
        showProgressDialog();
        JsonObjectRequest jsonObjReq = new JsonObjectRequest(Method.GET,
                Const.URL_JSON_OBJECT, null,
                new Response.Listener<JSONObject>() {

            @Override
            public void onResponse(JSONObject response) {
                Log.d("VollyResponse", response.toString());
                parseBuffetTableJSON(response);
                distanceCalculation();
                parseBuffetDetailsTableJSON(response);
                hideProgressDialog();
                startingNewActivity();
            }

            private void parseBuffetTableJSON(JSONObject response) {
                //jsonobject = new JSONObject(response);
                try {
                    jsonobject = response.getJSONObject("findmybuffet");
                    jsonarray = jsonobject.getJSONArray("buffets");
                    for (int i = 0; i < jsonarray.length(); i++) {
                        HashMap<String, String> map = new HashMap<String, String>();
                        jsonobject = jsonarray.getJSONObject(i);
                        // Retrive JSON Objects
                        map.put("buf_off_id", jsonobject.getString("buf_off_id"));
                        map.put("from_time", jsonobject.getString("from_time"));
                        map.put("to_time", jsonobject.getString("to_time"));
                        map.put("online_price", jsonobject.getString("online_price"));
                        map.put("reserved_price", jsonobject.getString("reserved_price"));
                        map.put("buf_image", jsonobject.getString("buf_image"));
                        map.put("res_name", jsonobject.getString("res_name"));
                        map.put("rating", jsonobject.getString("rating"));
                        map.put("latitude", jsonobject.getString("latitude"));
                        map.put("longitude", jsonobject.getString("longitude"));
                        map.put("buf_type_name", jsonobject.getString("buf_type_name"));
                        map.put("from_date", jsonobject.getString("from_date"));
                        map.put("to_date", jsonobject.getString("to_date"));
                        map.put("city_id", jsonobject.getString("city_id"));
                        map.put("city_name", jsonobject.getString("city_name"));
                        map.put("meal_type_id", jsonobject.getString("meal_type_id"));
                        map.put("meal_type_name", jsonobject.getString("meal_type_name"));
                        map.put("buf_desc", jsonobject.getString("buf_desc"));
                        map.put("distance", jsonobject.getString("distance"));
                        //Log.d("----$$$----", map.toString());
                        //Calling database 
                        databaseHelper.addDataToBuffetTable(map);
                    }   
                } catch (JSONException e) {
                    e.printStackTrace();
                }
            }

            private void parseBuffetDetailsTableJSON(JSONObject response) {
                //jsonobject = new JSONObject(response);
                try {
                    jsonobject = response.getJSONObject("findmybuffet");
                    jsonarray = jsonobject.getJSONArray("buf_meal_det");
                    for (int i = 0; i < jsonarray.length(); i++) {
                        HashMap<String, String> map = new HashMap<String, String>();
                        jsonobject = jsonarray.getJSONObject(i);
                        // Retrive JSON Objects
                        map.put("buf_off_id", jsonobject.getString("buf_off_id"));
                        map.put("menu_type_id", jsonobject.getString("menu_type_id"));
                        map.put("menu_type_name", jsonobject.getString("menu_type_name"));
                        map.put("cuisine_type_name", jsonobject.getString("cuisine_type_name"));
                        map.put("item_name", jsonobject.getString("item_name"));
                        //Log.d("----$$$----", map.toString());
                        //Calling database 
                        databaseHelper.addDataToBuffetDetailsTable(map);
                    }   
                } catch (JSONException e) {
                    e.printStackTrace();
                }
            }

            private void distanceCalculation() {
                String myQuery="SELECT * FROM buffets";
                Cursor cursor = (Cursor) databaseHelper.getAllDataFrmBuffetTable(myQuery);
                cursor.moveToFirst();
                if(cursor.moveToFirst()){
                    do{
                        buffetOfferId=cursor.getString(cursor.getColumnIndex(cursor.getColumnName(1))); 
                        destLatitude=cursor.getString(cursor.getColumnIndex(cursor.getColumnName(9)));
                        destLongitude=cursor.getString(cursor.getColumnIndex(cursor.getColumnName(10)));
                        srcLatitude="12.918286";
                        srcLongitude="77.669493";
                        Log.d("---Source------", destLatitude+","+destLongitude);
                        Log.d("---Destination-", srcLatitude+","+srcLongitude);
                        float CalculateDistance=CalculateDistance(srcLatitude,srcLongitude,destLatitude,destLongitude);
                        Log.d("---Result---", CalculateDistance+"");
                        //round float to nearest whole number and then convert into double and converting to kilometers
                        double CalculateDistanceRounded = Math.round(CalculateDistance)/1000;
                        databaseHelper.updateSqLiteDistance(CalculateDistanceRounded,buffetOfferId);
                    }while(cursor.moveToNext());
                }
            }

            private float CalculateDistance(String srcLatitude,
                    String srcLongitude, String destLatitude, String destLongitude) {

                Location locationA = new Location("point A");
                //Convert from string to double and then process
                locationA.setLatitude(Double.parseDouble(destLatitude));
                locationA.setLongitude(Double.parseDouble(destLongitude));
                Location locationB = new Location("point B");
                locationB.setLatitude(Double.parseDouble(srcLatitude));
                locationB.setLongitude(Double.parseDouble(srcLongitude));
                return locationA.distanceTo(locationB);
            }

            private void startingNewActivity() {
                Intent intent=new Intent(SplashActivity.this,MainActivity.class);
                startActivity(intent);
            }

        }, new Response.ErrorListener() {

            @Override
            public void onErrorResponse(VolleyError error) {
                VolleyLog.d("VollyResponse", "Error: " + error.getMessage());
                hideProgressDialog();
            }
        }) {
        };
        // Adding request to request queue
        AppController.getInstance().addToRequestQueue(jsonObjReq,tag_json_obj);
        // Cancelling request
        // ApplicationController.getInstance().getRequestQueue().cancelAll(tag_json_obj);       
    }

    @Override
    protected void onStart() {
        // TODO Auto-generated method stub
        super.onStart();
        //Setting fonts for textviews
        checkForGpsAndTurnItOn();
    }

    public void showDialog(){
        //GPS-Dialog
        GpsEnablingDialog gpsAlert=new GpsEnablingDialog();
        gpsAlert.show(getSupportFragmentManager(), "GpsAlert_Tag");
    }

    private void checkForGpsAndTurnItOn() {
        locationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
        if ( !locationManager.isProviderEnabled( LocationManager.GPS_PROVIDER ) ) {
            Log.d("My-Log-Msg","$-before-showDialog-$");
            showGpsDialog();
            Log.d("My-Log-Msg","$-after-showDialog-$");
        }
    }

    public void showGpsDialog(){
        //GPS-Dialog
        GpsEnablingDialog gpsAlert;
        try {
            gpsAlert = new GpsEnablingDialog();
            gpsAlert.show(getSupportFragmentManager(), "GpsAlert_Tag");
        } catch (Exception e) {
            // TODO Auto-generated catch block
            Log.d("My-Log-Msg",e.toString());
            e.printStackTrace();
        }
    }

    private void showProgressDialog() {
        if (!pDialog.isShowing())
            pDialog.show();
    }

    private void hideProgressDialog() {
        if (pDialog.isShowing())
            pDialog.hide();
    }

}

{Edit}

Intent intent = new Intent(getActivity(), SplashActivity.class);
                intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TASK);
                intent.putExtra("LOGOUT", true);
                startActivity(intent); 
  • snippet above is from the second activity next to splash.java
  • How to launch the boolean value as true when i launch SplashActivity.java
  • All i am trying is just to close my app & return to android home screen
  • There's no point of writting `SplashActivity.this.finish();` if your code is running in `SplashActivity` context. It's sufficien to just do `finish()`; – Marcin Orlowski May 04 '14 at 11:26

2 Answers2

1

What do you mean by "does nothing"? What do you expect to happen?

finish() is async - it passes the request to the ActivityManager, which will in turn trigger the whole finish flow (finish activities which are newer on the stack -> onPause() -> onStop() -> onSaveInstance().... -> onFinish() ). It will not suddenly kill your app.

And that's a good thing.

Vaiden
  • 15,728
  • 7
  • 61
  • 91
0

Try to use getBoolean method with the Intent as:

if ( getIntent().getExtras().getBoolean("LOGOUT") ) {
    SplashActivity.this.finish();
} else {
    Log.v("Boolean LOGOUT","The value is false...");
}  

Also, make sure the value of your boolean is not "empty" (it should be true) when you launch SplashActivity. Let me know if this resolve the issue.

Blo
  • 11,903
  • 5
  • 45
  • 99
  • If you want to finish your app when you come back to *SplashActivity* @Sky, you should call another `finish()` below `startActivity(intent);` from the snippet code you shared in your edit. Something as: `getActivity().finish();` and then you call `finish()` when the boolean is true inside *SplashActivity*. This should work. – Blo May 04 '14 at 11:47
  • Thank you for your help !.... i followed this http://stackoverflow.com/questions/3724509/going-to-home-screen-programmatically post also to achieve my goal :) –  May 05 '14 at 06:19
  • Your question clearly stated that your "control" gets to that line. Now it seems that your problem was different. Next time please try and be accurate. – Vaiden May 05 '14 at 15:04
  • And to the point - getExtras() unparcels the intent's extras. – Vaiden May 05 '14 at 15:04