Search code examples
androidandroid-alertdialogactivity-finish

how to achieve something like "finish" in a non-activity class in android?


This dialog asks whether you want to install some other app...so when onclicked no button it must go back to the previous screen

    downloadDialog.setNegativeButton(stringButtonNo,
            new DialogInterface.OnClickListener() {
                public void onClick(DialogInterface dialogInterface, int i) {
                         finish();
                }
            });

this gives the error:

The method finish() is undefined for the type new DialogInterface.OnClickListener(){}

how can i achieve what i wanted???

package com.Android.barcode;

import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.widget.TextView;

public class BarcodeActivity extends Activity {
    public static String upc;

    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        IntentIntegrator.initiateScan(this);
    }

    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        switch (requestCode) {
        case IntentIntegrator.REQUEST_CODE: {
            if (resultCode != RESULT_CANCELED) {
                IntentResult scanResult = IntentIntegrator.parseActivityResult(
                        requestCode, resultCode, data);
                if (scanResult != null) {
                    upc = scanResult.getContents();

                    Intent intent = new Intent(BarcodeActivity.this, BarcodeResult.class);
                    startActivity(intent);
                    // put whatever you want to do with the code here
/*                  TextView tv = new TextView(this);
                    tv.setText(upc);
                    setContentView(tv);*/
                }
            }
            break;
        }
        }
    }
}

Solution

  • Since you don't want to create that dialog from that activity : You have two options

    1) Call an Intent back to the activity you want the user to go to.

    Intent intent = new Intent(getBaseContext(), theActivity.class); 
    getApplication().startActivity(intent) ;
    

    or Else

    2) Create a constructor for that class consisting of the dialog.

    public class ABC {
        Context iContext=null;
       public ABC(Context con){
        iContext=con;
       }
     ....
    
    }
    

    Call the class with the Context of the activity. Like ABC(Cont) .And then use ((Activity)iContext).finish() within that class to finish that activity as you wish.