Call function from jar in MainActivity - android

First time I'm trying to make my own .jar file. It works, but now I want to give feedback to the MainActivity. So I want to call a function 'receiveSerial()' in the MainActivity.
So the MainActivity must always implement the function 'receiveSerial()' when including my .jar.
.jar file (part of the) code:
package com.hoeks.ma.bluetooth;
import java.util.Set;
import ...
public class Blauwe{
..
private Activity ma;
public Blauwe(Activity m){
mBluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
ma = (Activity)m;
}
..
public void sendSerial(String s) {
ma.receiveSerial(s); // This line give Eclipse error "Add cast to ma"
// When I add the cast it is not working
}
MainActivity
import com.hoeks.ma.bluetooth.Blauwe;
....
public void receiveSerial(String s) {
javascr.setSerial(s);
}
Note: I do not post the whole code because the code is a big mess right now, its not good for the readability.

1) create interface
public interface ReceiveSerialCallback{
public void receiveSerial(String s);
}
2) add interface implementation in MainActivity
public class MainActivity implements ReceiveSerialCallback{
...
public void receiveSerial(String s) {
// serial received
}
}
3) update Blauwe class
private ReceiveSerialCallback callback;
...
public void setReceiveSerialCallback(ReceiveSerialCallback callback) {
this.callback = callback;
}
...
public void sendSerial(String s) {
callback.receiveSerial(s);
}
4) set inteface callback object to Blauwe class in MainActivity
Blauwe b = new Blauwe();
b.setReceiveSerialCallback(this);

You have to cast because receiveSerial(String) is not a method of Activity, but MainActivity. I would create an interface (with method sendSerial) that MainActivity should implement, and save a reference of this interface in Blauwe class, instead of an Activity instance.

Related

How to access another activity?

Just to make it clear, this is not I want. I want to access another Activity's context.
Suppose I've two activities, MainActivity and WebActivity. In MainActivity I used oAuth2 login, and after login I start the WebActivity. In WebActivity I need to logout with the function mTencent.logout(MainActivity.this);, the question is how can I access MainActivity from WebActivity?
If I do this directly, I get the error,
MainActivity is not an enclosing class?
Considering I'm a starter of android, here may be not the exact way to implement it.
Will someone help? Thank you!
The API : void com.tencent.tauth.Tencent.logout(Context context)
Use Application context in your login and logout methods. As they will be managed at Application level.
So change mTencent.logout(MainActivity.this); to mTencent.logout(getApplicationContext());.
Also change your login method to work in application context.
Instead of using context of one activity in other which may result in crashes sometimes.
u can use libraries like EventBus to link the code.
Define a class which implements event u want to perform eg:LogOutEvent.java
public static class LogOutEvent { /* Additional fields if needed */ }
U can post events like logout from WebViewActivity.java using following command
EventBus.getDefault().post(new LogOutEvent());
and in MainActivity you first need to register event bus
#Override
public void onStart() {
super.onStart();
EventBus.getDefault().register(this);
}
#Override
public void onStop() {
super.onStop();
EventBus.getDefault().unregister(this);
}
and then in MainActivity you can subscribe for events like this
#Subscribe(threadMode = ThreadMode.MAIN)
public void onMessageEvent(LogOutEvent event) {/* Do log out here */};
There is a good practice solution to your problem which involves certain steps to be performed:
1- Define an interface:
public interface LogOutInterface {
public void logout();
}
2- Have your MainActivity implement this interface:
public class MainActivity extends ???? implements LogOutInterface {
...
#Override
public void logout(){
//your logout procedure
}
}
3- Have a public method for your WebActivity and allow it to accept LogOutInterface:
public class WebActivity ... {
private LogOutInterface logoutInterface;
...
public void setLogOut(LogOutInterface logoutInterface) {
this.logoutInterface = logoutInterface;
}
}
4- call setLogOut from MainActivity:
public class MainActivity ... {
public void yourmethod() {
...
webActivity.setLogOut(this);
}
}
5- call logout function from your WebActivity:
public class WebActivity ... {
...
public void yourmethod() {
logoutInterface.logout();
}
}
hope this helps.
This is a workable one.
In the MainActivity, public static Activity thisActivity; & thisActivity = this; then in the WebActivity mTencent.logout(MainActivity.thisActivity);
or just can put the logout function as public static function of MainActivity,
public static void logout() {
if (mTencent.isSessionValid()) {
mTencent.logout(thisActivity);
}
}
then call MainActivity.logout() from WebActivity.

How to correctly exit a Processing sketch in Android

I am currently building an app in Android Studio involving a Processing sketch.
Main class:
import android.app.Activity;
import android.app.FragmentManager;
import android.os.Bundle;
import processing.android.PFragment;
import processing.core.PApplet;
public class ClassMain extends Activity {
/**************************************************/
PApplet sketch;
/**************************************************/
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.class_main);
FragmentManager fragmentManager = getFragmentManager();
sketch = new ClassSketch();
PFragment fragment = new PFragment();
fragment.setSketch(sketch);
fragmentManager.beginTransaction().replace(R.id.container, fragment).commit();
}
/**************************************************/
#Override
public void onBackPressed()
{
//ClassMain.this.finish();
}
/**************************************************/
//It doesn't work if called from sketch...
public void exits()
{
ClassMain.this.finish();
}
/**************************************************/
}
Processing Sketch:
import android.view.KeyEvent;
import processing.core.PApplet;
public class ClassSketch extends PApplet {
/*****************************************************************************/
public void settings()
{
size(displayWidth, displayHeight);
}
/*****************************************************************************/
public void setup()
{
}
/*****************************************************************************/
public void draw()
{
keykey();
}
public void keykey()
{
if(keyPressed)
{
if (key == CODED) {
if (keyCode == KeyEvent.KEYCODE_BACK) {
//non of the following work:
//exit();
ClassMain j = new ClassMain();
j.exits();
}
}
}
}
}
Here is the problem, I want the the user, depending on some circumstances that I will add later in the sketch, to exit not only the sketch but the class that is hosting it (ClassMain).
When ever (in the sketch) something happens in my sketch, I want to be able to exit the whole MainClass, but I just happen to fail.
Thanks for the support.
This doesn't make sense:
ClassMain j = new ClassMain();
j.exits();
Here you're creating a new instance of ClassMain, and then immediately exiting. That won't do anything.
Instead, you need to tell the already-existing parent ClassMain to exit.
To do this, you need a reference to the parent ClassMain instance, which you can take into your ClassSketch constructor:
public class ClassSketch extends PApplet {
private ClassMain parent;
public ClassSketch(ClassMain parent){
this.parent = parent;
}
public void keykey(){
parent.exits();
}
}
Then to pass the instance into the constructor, you can simply use the this keyword:
protected void onCreate(Bundle savedInstanceState) {
sketch = new ClassSketch(this);
}
As a complementary note to the above, don't forget to call super.onCreate(savedInstanceState); in your onCreate() function.
You can exit directly from your sketch by accessing finish() via: this.getActivity().finish();. Notice that in API level 16 and above, you also have available this.getActivity().finishAffinity(); as commented in here.
Lastly, if you press the home button, it calls onStop(), so the app lingers in Memory. If you press the back button, then onDestroy() gets called as well. If you call finish() as described, it is guaranteed onDestroy() gets called.
My two cents...
Kf

How Send message from fragment to activity and received and use in activity?

Please please don't minus my question i confused when googling.
I used Android Tab Layout with Swipeable Views in my code for when user pressed setting button on an activity.
now I need send message from TopRatedFragment.java that extends from fragment to the activity that call the mainActivity of "Android Tab Layout with Swipeable Views".
You can do this by implementing a call back
create an interface first
public interface CommunicationInterface {
public void onSuccess();
public void onFailed();
}
then in your activity implement the interface
public class YourActivity extends ActionBarActivity implements CommunicationInterface {
//default functions
#Override
public void onSuccess() {
//stuff you want to do in the acivity
}
#Override
public void onFailed() {
//stuff you want to do in the acivity
}
}
Now in the fragment
public class yourfragment extends Fragment {
CommunicationInterface callback;
//stuffs that usually come in yor fragment and like OncreateView etc
#Override
public void onActivityCreated(#Nullable Bundle outState) {
super.onActivityCreated(outState);
//after all the stuff you want to do in your fragment then implement //call back function to communicate with the activity
callback= (CommunicationInterface) getActivity();
callback.onSuccess();//according to your purpose use where ever you like
callback.onFailed();//according to your purpose use where ever you like
}
#Override
public void onAttach(Activity activity) {
super.onAttach(activity);
callback= (CommunicationInterface) activity;
}
}
Take a close look on this reference:
Creating event callbacks to the activity
The android docs recommend using this pattern of having the parent activity implement an interface of the fragment (Basically calling methods on it)
class MyFragment extends Fragment {
interface Listener {
public void onSomeEvent();
}
private void somethingHappeninInTheFragment() {
// let the activity know
((Listener) getActivity()).onSomeEVent();
}
}
class MyActivity extends Activity implements MyFragment.Listener {
// etc
#Override
public void onSomeEvent() {
// handle the message from the fragment
}
}
Explained with a more concrete example here: http://developer.android.com/guide/components/fragments.html#EventCallbacks
Here's the solution:
Step 1 : From your fragment.
Intent i = new Intent(getActivity(), YourActivity.class);
i.putExtra("key", "Your value1");
i.putExtra("key2", "Your value2");
i.putExtra("key3", "Your value3");
getActivity().startActivity(i);
Step 2 : In your Activity where you want the result
Intent getResults = getIntent();
String firstValue = getResults.getStringExtra("key1");
String secondValue = getResults.getStringExtra("key2");
String thirdValue = getResults.getStringExtra("key3");
Use those values your needs are.
Hope this helps.. :)

Set TextView text to what is returned from function in another class

I'm new to android and I am making an app as part of an assignment, and can't get this function to return a value - the app closes and I get an error message: "Unfortunately, APP has stopped".
I have two classes, one is the MainActivity and one is a class that I am wanting to use to do arithmetic, and they are:
import com.calc.Calculation;
public class MainActivity extends Activity {
private Calculation util;
calculate = (Button) findViewById(R.id.btnCalc);
private TextView tvMultiply;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
tvMultiply = (TextView) findViewById(R.id.tvMult);
}
btnCalc.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
tvMiltiply.setText(String.valueOf(util.CalculateMult(4,6)));
}
});
}
and
package com.calc;
public class Calculation{
public int CalculateMult(int numOne, int numTwo)
{
return numOne * numTwo;
}
}
I've tried a few alternatives but to no avail. It's going to be something simple that I am not doing quite right.
Any help appreciated.
Thanks
You need to create instance to the class before acccessing the member.
private Calculation util = new Calculation()
Else make the method in the class as static and access without creating instance.
This would be done by defining the class as:
package com.calc;
public class Calculation{
public static int CalculateMult(int numOne, int numTwo)
{
return numOne * numTwo;
}
}
and calling the method as:
Calculation.CalculateMult(4,6)
You should move the line
calculate = (Button) findViewById(R.id.btnCalc);
to the onCreate() function after you have set the content view. You should also move the assignment of the onClickListener to your button to the onCreate() method.
Finally, you should initialize your Calculation object by using the new operator in onCreate(), i.e:
util = new Calculation();

Finishing an activity from a standard java class

I am currently working on an android project and I have an activity, lets call it MyActivity and this activity calls a standard Java class called MyClass.
I need MyClass to finish the MyActivity activity but I can't find out how to do this. I thought I might be able to pass the context to the standard java class and call context.finish() but this doesn't appear to be available.
How can I do this, thanks for any help you can offer.
You can pass the Context, but you will need to cast it to an Activity (or simply pass the Activity itself), although this in general seems like a bad practice.
The most secure solution uses listener and a Handler. It is complex, but ensures a non direct call to finish activity.
Your listener:
interface OnWantToCloseListener{
public void onWantToClose();
}
Class that should close activity.
class MyClass {
private OnWantToCloseListener listener;
public void setWantToCloseListener(OnWantToCloseListener listener){
this.listener = listener;
}
private void fireOnWantToClose(){
if(this.listener != null)
listener.onWantToClose();
}
}
When you want to close your activity you must call fireOnWantToClose() method.
public MyActivity extends Activity{
public void onCreate(){
final int CLOSE = 1; //number to identify what happens
MyClass my_class = new MyClass();
final Handler handler = new Handler(){
public void handleMessage(Message msg){
if(msg.what == CLOSE)
MyActivity.this.finish();
}
});
my_class.setOnWantToCloseListener(new OnWantToCloseListener(){
public void onWantToClose(){
handler.sendEmptyMessage(CLOSE);
}
});
}
}
This is secure because Activity is not finished directly by MyClass object, it is finished through a listener that orders a handler to finish activity. Even if you run MyClass object on a second thread this code will works nice.
EDIT: CLOSE var added I forget to declare and initialize this.
Pass the MyActivity to MyClass as an Activity. From there you can call myActivity.finish();
For example:
private Activity myActivity;
public MyClass(Activity myActivity){
this.myActivity = myActivity;
}
public void stopMyActivity(){
myActivity.finish();
}
And in MyActivity:
MyClass myClass = new MyClass(this);
This is risky, because you're holding a reference to an Activity, which can cause memory leaks.
If your java class is a nested inner class, you can use:
public class MyActivity extends Activity {
public static class JavaClass {
public void finishActivity() {
MyActivity.finish();
}
}
}
Otherwise you'll have to pass the java class a Context (i.e. pass it a reference to this, since Activity extends Context) and store it as a private instance variable.

Categories

Resources