• After 15+ years, we've made a big change: Android Forums is now Early Bird Club. Learn more here.

How to access one onclick method for 2 buttons which are in two different activities?

nagamothu

Newbie
Hi guys can anyone please clear my doubt. i have 2 activities. activity 1 and activity 2. and each activity has a button. Now my doubt is i want to access a onclick method written for button which is in activity 1 for the button which is in activity 2. in the whole i want to access same onclick method for two buttons which are in two different activities. how can we do that?
 
Now my doubt is i want to access a onclick method written for button which is in activity 1 for the button which is in activity 2. in the whole i want to access same onclick method for two buttons which are in two different activities. how can we do that?

You could create a third class (generic, not an activity) and define your onclick method there. Then have your clickhandlers invoke that class & method. You may need to pass in some additional variables to give it the context.
 
Here's an example of something similar I did for file operations:
Code:
import android.content.Context;

import java.io.FileInputStream;
import java.io.FileOutputStream;

public class Lib {
    public static final String ERROR = "ERROR";

    private Lib() {}

    public static String loadFile(String filename, Context context) {
        FileInputStream filestream;
        String filecontents = "";
        try {
            filestream = context.openFileInput(filename);
            int c;
            while( (c=filestream.read()) != -1) {
                filecontents += Character.toString((char)c);
            }
            filestream.close();
        }
        catch (Exception e) {
            filecontents = ERROR;
        }
        return filecontents;
    }

    public static void saveFile(String filename, String str, Context context) {
        FileOutputStream filestream;
        try {
            filestream = context.openFileOutput(filename, Context.MODE_PRIVATE);
            filestream.write(str.getBytes());
            filestream.close();
        }
        catch (Exception e) {
            e.printStackTrace();
        }
    }
}
Hope that helps!
 
You could create a third class (generic, not an activity) and define your onclick method there. Then have your clickhandlers invoke that class & method. You may need to pass in some additional variables to give it the context.
Good answer 23tony, what you said is the right way. ;)
Basically, a utility class that holds some reusable methods(objects) to reuse anywhere in the app as oppose to rewriting the same code over each time it's needed.
 
Here's an example of something similar I did for file operations:
Code:
import android.content.Context;

import java.io.FileInputStream;
import java.io.FileOutputStream;

public class Lib {
    public static final String ERROR = "ERROR";

    private Lib() {}

    public static String loadFile(String filename, Context context) {
        FileInputStream filestream;
        String filecontents = "";
        try {
            filestream = context.openFileInput(filename);
            int c;
            while( (c=filestream.read()) != -1) {
                filecontents += Character.toString((char)c);
            }
            filestream.close();
        }
        catch (Exception e) {
            filecontents = ERROR;
        }
        return filecontents;
    }

    public static void saveFile(String filename, String str, Context context) {
        FileOutputStream filestream;
        try {
            filestream = context.openFileOutput(filename, Context.MODE_PRIVATE);
            filestream.write(str.getBytes());
            filestream.close();
        }
        catch (Exception e) {
            e.printStackTrace();
        }
    }
}
Hope that helps!


Hi thank you for you response tried that but blank activity is opening instead of scan camera.please check this.
ScancodeActivity.java
Code:
@Override
public  void onClick(View v) {
      zXingScannerView = new ZXingScannerView( this);
    setContentView(zXingScannerView);
    zXingScannerView.setResultHandler( this );
    scan( zXingScannerView );
}

public  static void scan( View view){
    zXingScannerView.startCamera();
}


@Override
public void handleResult(Result result) {


    if (result != null) {
        //if qrcode has nothing in it
        //if qr contains data
        if (result.getText() == null) {
            Toast.makeText( this, "Result Not Found", Toast.LENGTH_LONG ).show();
        } else {
            try {
                //converting the data to json
                JSONObject obj = new JSONObject( result.getText() );
                SharedPreferences sharedPreferences = getSharedPreferences( "json_data_file", MODE_PRIVATE );
                SharedPreferences.Editor editor = sharedPreferences.edit();
                editor.putString( "user_data", obj.getString( "user_data" ) );
                editor.putString( "Question_id", obj.getString( "Question_id" ) );
                editor.putString( "paper_id", obj.getString( "paper_id" ) );
                editor.apply();

            } catch (JSONException e) {
                e.printStackTrace();
                Toast.makeText( this, result.getText(), Toast.LENGTH_LONG ).show();
            }
        }
        launchcamera();
    }

This is scancodeActivity.java class this has a button which has a button "scan QRcode". after scanning qrcode result will be displayed in display activity.

Now i want to add another button "scan another qr code" in display activity. when i click this button scan camera should open directly . but now when i click this either blank activity is opening or scancodeActivity is opening instead of scan camera.

this is display.java
Code:
@Override
public void onClick(View v) {
    zXingScannerView = new ZXingScannerView( this);
   setContentView(zXingScannerView);
   zXingScannerView.setResultHandler( (ZXingScannerView.ResultHandler) Display.this );
   ScancodeActivity.scan(zXingScannerView);
}

Please check code in both activities and tell me where am doing wrong.
 
I think you have a couple of problems with how you've structured your code. By the look of it, you still have duplicate code, and you're not calling the generic code. Also, the generic code should not be an onClick override.

You should create a separate Java class that's not an activity or view - just a generic class. Let's call it Lib. Then, in that class, you define a static function as your click handler:
Code:
import android.content.Context;
public class Lib {
    public static final String ERROR = "ERROR";

    private Lib() {}

    public static void scannerClickHandler(View v, Context context) {
        zXingScannerView = new ZXingScannerView(context);
        setContentView(zXingScannerView);
        zXingScannerView.setResultHandler( (ZXingScannerView.ResultHandler) context );
        ScancodeActivity.scan(zXingScannerView);
    }
}

Then your click handlers would both be like this:
Code:
@Override
public  void onClick(View v) {
    Lib.scannerClickHandler(v, this);
}
 
I think you have a couple of problems with how you've structured your code. By the look of it, you still have duplicate code, and you're not calling the generic code. Also, the generic code should not be an onClick override.

You should create a separate Java class that's not an activity or view - just a generic class. Let's call it Lib. Then, in that class, you define a static function as your click handler:
Code:
import android.content.Context;
public class Lib {
    public static final String ERROR = "ERROR";

    private Lib() {}

    public static void scannerClickHandler(View v, Context context) {
        zXingScannerView = new ZXingScannerView(context);
        setContentView(zXingScannerView);
        zXingScannerView.setResultHandler( (ZXingScannerView.ResultHandler) context );
        ScancodeActivity.scan(zXingScannerView);
    }
}

Then your click handlers would both be like this:
Code:
@Override
public  void onClick(View v) {
    Lib.scannerClickHandler(v, this);
}

Done in the same way but am getting error can you please see this error.
Process: com.codeexap.ews, PID: 22934
java.lang.ClassCastException: com.codeexap.ews.Display cannot be cast to me.dm7.barcodescanner.zxing.ZXingScannerView$ResultHandler
at com.codeexap.ews.ScancodeActivity$lib.scannerClickHandler(ScancodeActivity.java:263)
at com.codeexap.ews.Display.onClick(Display.java:140)
at android.view.View.performClick(View.java:4848)
at android.view.View$PerformClick.run(View.java:20299)
at android.os.Handler.handleCallback(Handler.java:815)
at android.os.Handler.dispatchMessage(Handler.java:104)
at android.os.Looper.loop(Looper.java:218)
at android.app.ActivityThread.main(ActivityThread.java:5657)
at java.lang.reflect.Method.invoke(Native Method)
at java.lang.reflect.Method.invoke(Method.java:372)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:990)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:785)


This is the code i have changed .
scancodeactivity.java
Code:
 @Override
    public void onClick(View v) {
         
       lib.scannerClickHandler( v,this );
        setContentView(zXingScannerView);
    }
public static class lib
    {
        public lib() {
        }

        public static void scannerClickHandler (View v, Context context){
        zXingScannerView = new ZXingScannerView( context );

        zXingScannerView.setResultHandler( (ZXingScannerView.ResultHandler) context );
        zXingScannerView.startCamera();
    }
    }

Display.java
Code:
@Override
public void onClick(View v) {
  
   ScancodeActivity.lib.scannerClickHandler( v,this );
    setContentView(zXingScannerView);
}
 
It looks like your context needs to have a result handler, and that's what you need to reference. So define a result handler in Display and in the activity, and use context.resultHandler
 
Back
Top Bottom