ROS Resources: Documentation | Support | Discussion Forum | Index | Service Status | ros @ Robotics Stack Exchange
Ask Your Question
0

android listener value into a variable

asked 2014-08-07 07:31:33 -0500

stefan gravatar image

Is there a way to run a android listener and to write its value dynamically into a variable used in onCreate of the mainActivity

something like this

public MainActivity(){

public void onCreate(...){
...

int i;
i=Listener.getvalue();
//or
i=Listener.vlaue;
}
}


protected void init(NodeMainExecutor nodeMainExecutor){
listener =new Listener;
...
nodeMainExecutor.execute(listener.nodeConfiguration);
}
}

i can see the log of the value (int) of the listener in my android studio

One Problem is that the init is ran after the onCreate and so the app throws a nullpointerexception since the object Listener does not exist. Is there a way to handle this(e.g. a loop)

the value of i should change dynamically depending on the message of the Listener

Thanks

edit retag flag offensive close merge delete

1 Answer

Sort by ยป oldest newest most voted
0

answered 2014-08-14 06:48:00 -0500

stefan gravatar image

in the onCreate

final Handler handler=new Handler();
final Runnable r = new Runnable() {
        @Override
        public void run() {

            var        =listener.listenervar;
            dosomething(var);

            handler.postDelayed(this,10);

        }
    };

    Thread t = new Thread(){
        @Override
        public void run() {
            try{
                while(true){
                    sleep(1000);
                    handler.post(r);
                }
            }
            catch(InterruptedException e){e.printStackTrace();}
        }
    };
    t.start();

in the listener.java:

package org.ros.rosjava_tutorial_pubsub;

import org.apache.commons.logging.Log;
import org.ros.message.MessageListener;
import org.ros.namespace.GraphName;
import org.ros.node.AbstractNodeMain;
import org.ros.node.ConnectedNode;
import org.ros.node.NodeMain;
import org.ros.node.topic.Subscriber;

public class Listener extends AbstractNodeMain {




public int listenervar=0;


//also possible
public int getlistenervar(){
return this.listenervar;
}


  @Override
  public GraphName getDefaultNodeName() {
    return GraphName.of("HAF_APP/listener_name");
  }



  @Override
  public void onStart(ConnectedNode connectedNode) {

    final Log log = connectedNode.getLog();
    Subscriber<std_msgs.Int32> subscriber = connectedNode.newSubscriber("topic", std_msgs.Int32._TYPE);



    subscriber.addMessageListener(new MessageListener<std_msgs.Int32>() {
      @Override
      public void onNewMessage(std_msgs.Int32 message) {
    listenervar=message.getData();

      }
    });
  }
}
edit flag offensive delete link more

Question Tools

1 follower

Stats

Asked: 2014-08-07 07:31:33 -0500

Seen: 1,209 times

Last updated: Aug 14 '14