passing reference of class to another class android error - java

I recently asked the precursor to this question and had a great reply. However, when i was working this into my android application i am getting an unexpected error and was wondering if everyone could take a look at my code and help me see what i am doing wrong.
Link to the initial question: passing reference of class to another class
My ERROR: "The constructor ConnectDevice(new View.OnClickListener(){}) is undefined"
The above is an error detected by eclipse.
Thanks in advance!
Below are My code snippets:
public class SmartApp extends Activity
{
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.intro);
final Button connectDeviceButton = (Button) findViewById(R.id.connectDeviceButton);
connectDeviceButton.setOnClickListener(
new View.OnClickListener()
{
#Override
public void onClick(View v) {
Thread cThread = new Thread(new ConnectDevice(this));
cThread.start();
}
});
}
}
public class ConnectDevice implements Runnable {
private boolean connected;
private SmartApp smartAppRef;
private ObjectInputStream ois;
public ConnectDevice(SmartApp smartAppRef) {
this.smartAppRef = smartAppRef;
}
}

That's because you are passing an OnClickListener object, but the constructor of the ConnectDevice class expects a SmartApp object. Why? you are doing this:
new ConnectDevice(this);
In that case, this references the OnClickListener. Change it to:
new ConnectDevice(SmartApp.this);

Related

Android - Change the Activity State using another Thread is Not Working

MyThread class is used to change the value of the myValue attribute in ActivityTwo Class.
public class MyThread implements Runnable {
private ActivityTwo activity;
public MyThread(ActivityTwo activity) {
this.activity = activity;
}
#Override
public void run() {
while(true){
activity.setValue(2);
}
}
}
ActivityTwo is an AppCompatActivity activity which runs as the main Thread.
public class ActivityTwo extends AppCompatActivity {
private MyThread myThread;
private Button startLogBtn;
private int myValue;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_two);
startLogBtn = findViewById(R.id.startLogBtn);
myThread = new MyThread(this);
startLogBtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
new Thread(myThread).start();
}
});
}
public void setValue(int value){
this.myValue= value;
}
}
When I Click the startLogButton it goes to a white screen and then restart the app. What should I do? I have no idea what has gone wrong.
Thanks in advance.
The issue was I have violated the rule "Do not access the Android UI toolkit from outside the UI thread".
ref : https://developer.android.com/guide/components/processes-and-threads
As a solution I found that I can use thread communication using message passing.
ref : Communication between UI thread and other threads using handler

Access public void in another class from MainActivity (Android)

I have two public voids in a class called Flashlight, these are:
public void turnOnFlashLight()
public void turnOffFlashLight()
How can I access these within Main Activity?
I've found many guides for using another class in MainActivity but not for accessing only a specific part (in this case I'm trying to turn the flashlight on or off).
This is he contents of MainActivity
public class MainActivity extends android.support.v7.app.ActionBarActivity {
#Override
protected void onCreate(android.os.Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
httpserver();
public void httpserver() {
AsyncHttpServer server = new AsyncHttpServer();
java.util.List<WebSocket> _sockets = new java.util.ArrayList<WebSocket>();
server.listen(5000);
server.get("/flashon", new HttpServerRequestCallback() {
static final int CAMERA_PIC_REQUEST = 0;
public void onRequest(AsyncHttpServerRequest request, AsyncHttpServerResponse response) {
response.send("Ok");
Flashlight.turnOnFlashLight();
}
});
}
}
This is the Flashlight class https://stackoverflow.com/a/31289731/6696740
Thank you :)
Make sure that class is imported in MainActivity. You should be able to just use Flashlight.turnOnFlashLight() or Flashlight.turnOffFlashLight(). You might also want to create an instance of the Flashlight class like Flashlight flashlight = Flashlight.newInstance(), then flashlight.turnOnFlashLight() or Flashlight.turnOffFlashLight().
In MainActivity (Assuming FlashLight class constructor does not need any input):
import Flashlight;
...
//where you need to call those methods
Flashlight flashLight = new Flashlight();
flashlight.turnOnFlashLight();
//OR
flashlight.turnOffFlashLight();

Own Events in Java not able to modify Classobjects?

this is My Situation:
I want to make two classes communicate with each other. So MainActivity is
making a new Object of SomeOtherstrangeClass.
public class MainActivity extends AppCompatActivity implements myEventListener {
private TextView txtHelloSet;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
txtHelloSet = (TextView) findViewById(R.id.txtHello);
SomeOtherStrangeClass someOtherStrangeClass = new SomeOtherStrangeClass();
}
#Override
public void someEvent(int e) {
Log.v("[Listener]", "SomeEvent triggered. Number: " + e);
txtHelloSet.setText("Event came in!");
}
}
#
public class SomeOtherStrangeClass {
public SomeOtherStrangeClass(){
EventThrower eventThrower = new EventThrower();
MainActivity mainActivity = new MainActivity();
eventThrower.addListener(mainActivity);
Log.v("[Listener]", "Throwing event");
eventThrower.someEvent(13);
}
}
interface myEventListener extends java.util.EventListener {
void someEvent(int e);
}
public class EventThrower {
private List<myEventListener> listeners = new ArrayList<myEventListener>();
public void addListener(myEventListener toAdd){
listeners.add(toAdd);
}
public void removeListener(myEventListener toRemove){
listeners.remove(toRemove);
}
public void someEvent(int e){
for(myEventListener el : listeners)
el.someEvent(e);
}
}
So this is how I'am doing it. But the Problem is, that when an event is thrown its like I'am still calling the Methode someEvent which is in MainActivity in SomeOtherStrangeClass. So I'am not able to modify any Objects in MainActivity. It's like they are not existing. I'am getting a NPE:
Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'void android.widget.TextView.setText(java.lang.CharSequence)' on a null object reference
Why this is so?
Is there any solution for that?
MainActivity mainActivity = new MainActivity();
You are doing something wrong here. It is not supposed to create Activity objects like this. You should rethink about your application logic.
You need to reference the instance of MainActivity that is currently in foreground in order to recognize any callbacks in it.
Try changing the constructor for SomeOtherStrangeClass like this:
public SomeOtherStrangeClass(myEventListener listener) {
EventThrower eventThrower = new EventThrower();
eventThrower.addListener(listener);
Log.v("[Listener]", "Throwing event");
eventThrower.someEvent(13);
}
Then, in onCreate() of your activity,
SomeOtherStrangeClass someOtherStrangeClass = new SomeOtherStrangeClass(this);

Android - How to pass interface to AsyncTask

I'm trying to figure out how to create an AsyncTask that runs my php API code in the background then alerts my MainActivity once it completes. I've been reading tutorials and trying things for hours now and I'm just frustrated at this point as I can't find anywhere that answers my question.
I create the AsyncTask and it runs successfully and I can log the returned information from my API in the onPostExecute but I cannot figure out how to alert the MainActivity that the task was completed. I do not know what to pass into the creation of the APICall. Every tutorial I read shows that the AsyncTask constructor takes the interface as an argument as shown in my code below, but how do you pass an interface as an argument?
MainActivity.java (implements OnTaskCompleted)
myButton4.setOnClickListener(new OnClickListener(){
public void onClick(View v){
APICall api = new APICall( ???What do I put here?? );
api.execute("users");
}});
....
#Override
public void onTaskCompleted() {
Log.v("Play","Main Activity ON Task completed!");
OnTaskCompleted.java
public interface OnTaskCompleted {
public void onTaskCompleted();
}
APICall.java (extends AsyncTask)
public APICall(OnTaskCompleted listener){
this.listener = listener;
}
....
protected void onPostExecute(JSONObject j)
{
listener.onTaskCompleted();
}
You should pass the reference of your listener to the APICall class:
APICall api = new APICall(MainActivity.this);
Simple you can use anonymous interface instance like this.
myButton4.setOnClickListener(new OnClickListener(){
public void onClick(View v){
APICall api = new APICall(new OnTaskCompleted() {
#Override
public void onTaskCompleted() {
}
});
api.execute("users");
}});
OR you can Implement interface at class level like this
public class MainActivity extends Activity implements MainActivity.OnTaskCompleted {
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
myButton4.setOnClickListener(new OnClickListener(){
public void onClick(View v){
APICall api = new APICall(MainActivity.this);
api.execute("users");
}});
}
#Override
public void onTaskCompleted() {
// Do your code on task complete
}
}
APICall api = new APICall( ???What do I put here?? );
What do I put here??
The one that implements your listener in this case your MainActivity
APICall api = new APICall(MainActivity.this);

Why 'this' can be used as the argument here in Java?

public class Activity01 extends Activity implements OnClickListener,
ViewFactory {
...
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
LinearLayout main_view = new LinearLayout(this);
m_Switcher = new ImageSwitcher(this);
main_view.addView(m_Switcher);
m_Switcher.setId(SWITCHER_ID);
m_Switcher.setFactory(this);
m_Switcher.setOnClickListener(this);
setContentView(main_view);
...
}
public void onClick(View v) {
...
}
}
Above code is from an Android project, and below function's argument is set as 'this', why?
m_Switcher.setOnClickListener(this);
According to the javadoc, here should be like below:
public void setOnClickListener (View.OnClickListener l)
That means the argument should be this kind: View.OnClickListener
So why 'this' can be there? Thanks!
Note: According to the answers, I gave a more complete code above.
In the class declaration you will find it either extends or implements OnClickListener. That means that the class can be used as an OnClickListener (because it is one, amongst other things). That is why you can use this here.

Categories