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();
Related
I am trying to extend Main Activity in another class so that i can use objects already created in the Main Activity.
if i have a main activity:
public class MainActivity extends AppCompatActivity {
public ImageView jani;
public Context main;
public classextended janitest = new classextended();
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
jani = findViewById(R.id.jani);
main=this;
janitest.janiaha();
Log.d("jani","FAK");
}
}
enter code here
And then a new class that extends MainActivitiy:
enter code here
public class classextended extends MainActivity {
public void janiaha(){
jani.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Toast.makeText(main, "YES YOU KNOW YOUR JAVA!!!", Toast.LENGTH_SHORT).show();
}
});
}
}
How can i acces the public void janiaha() ? Or am i doing it all wrong : ) ?
Al i get is crashes--- yes i could use static classes but as far as i know memory leaks would be a reall problem.
You can't call methods of a subclass that aren't defined on the main class. If you mean to have multiple classes descended from MainActivity, make it a protected function on MainActivity that's either abstract or has a default implementation, then override it in the subclass. If you aren't planning on having multiple child classes, then I question the value of even having one.
U cant call a method from child class to a parent class. If u want to have a function do similar work like it then, U can create a normal class to do it. or u can do this in this class. u just have to make the method 'static'..
public static void janiaha(ImageView jani){
jani.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Toast.makeText(main, "YES YOU KNOW YOUR JAVA!!!", Toast.LENGTH_SHORT).show();
}
});
}
When I need a callback from Activity B back to Activity A I usually make the reference variable in Activity B 'static'. I realize that if the user rotates the device the Life Cycle methods will remove my reference.
Is this the only drawback and is there a better way to register without a static reference. Is it better to simply put all data in the Application class ? - Thank you.
public class MainActivity extends Activity implements InterfaceMainActivityTwo {
static Main2Activity main2Activity;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
main2Activity = new Main2Activity();
main2Activity.setDataListener(this);
}
#Override
public void getDataMainActivityTwo(String string) {
tvTextData.setText(string);
}
}
public class Main2Activity extends Activity {
static InterfaceMainActivityTwo mGetDataInterface;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main2);
}
public void getDataSaveBtn(View v) {
if (mGetDataInterface != null)
mGetDataInterface.getDataMainActivityTwo(fullName);
else
Toast.makeText(this, "IS NULL.INTERFACE NOT INITIALIZED !!!!", Toast.LENGTH_SHORT).show();
}
/////////// interface setup
interface InterfaceMainActivityTwo {
void getDataMainActivityTwo(String string);
}
public void setDataListener(InterfaceMainActivityTwo listener) {
this.mGetDataInterface = listener;
}
}
You should never need a callback between two activities. You're doing something wrong if you do. If you need to pass data from A to B, pass it in the bundle. If you need to pass it back from B to A, use startActivityForResult and pass it in the result. If you need to share data between many activities, it should be held in some globally accessible data structure, either in memory or on disk.
public class MainActivity extends AppCompatActivity {
public ShareData SD = new ShareData();
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
SD.set_numb(5);
}
// when button clicked
public void noviEkran(View view){
Intent i = new Intent(this,klasaB.class);
startActivity(i);
}
}
public class ShareData {
private int number;
public ShareData(){
this.number=0;
}
public void set_numb(int num){
number = num;
}
public int get_numb(){
return number;
}
}
public class klasaB extends Activity{
ShareData sd;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
int i =sd.get_numb();
System.out.println("Saved numb:" + i);
}
}
My question is, if i declare object in 1st class, and set its parameter number to 5, how to acces this number from other class because now my apk crashes when reading " int i =sd.get_numb(); " in class "klasaB".
Any suggestion how to make this work?
ps: i dont want to use static variables, or putExtra with Intents.
If data is simple/primitive then use Intent to pass data from one activity to another. That is what Intent is for.
If it is not (some sort of complex data structure or object), I would extend Application, by making a custom sub class. Application class (as the name implies) is accessible to all Activities, even when app transitions from one to another. Below is a very simple example, just to show you the idea. You can modify/adjust that to your needs.
public class MyApplication extends Application {
private X x;
public static void setX(X x) { ... }
public static X getX() { ... }
}
public class ActivityA extends Activity {
...
MyApplication.setX(x);
}
public class ActivityB extends Activity {
...
X x = MyApplication.getX();
}
You may have mixed up Activity/MainActivity/AppCombatActivity inheritance... I suspect that the reason you are seeing the error -- by the way, please look into "how to ask" and include a bit more information next time -- is that sd in klasaB is never initialized.
MainActivity.SD will hold that 5 after its onCreate(), whereas klasaB.sd is never set to anything.
You never reference or instantiate SD in class B. To get the data to ClassB you will need to set the data as an extra in the intent. Most classes cannot be sent in the intent, so for your case you should pass the primitive types of the object, then create the object.
// when button clicked
public void noviEkran(View view){
Intent i = new Intent(this,klasaB.class);
i.putExtra("TAG", SD.get_num());
startActivity(i);
And then in Class B
ShareData SD = new ShareData();
SD.set_num(getIntent.getIntExtra("TAG", 0);
You can access your class object either using implements Serializable or Parcelable
1.Implement serializable into your ShareData class
public class ShareData implements Serializable{
private int number;
public ShareData(){
this.number=0;
}
public void set_numb(int num){
number = num;
}
public int get_numb(){
return number;
}
}
2.create object of SharedData and share with intent to classB
public class MainActivity extends AppCompatActivity {
public ShareData SD = new ShareData();
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
SD.set_numb(5);
}
// when button clicked
public void noviEkran(View view){
Intent i = new Intent(this,klasaB.class);
i.putExtras("key", SD)
startActivity(i);
}
}
3.Access in classB
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
ShareData sd = (ShareData)getIntent().getSerializableExtra("key").
System.out.println("Saved numb:" + sd.get_num());
}
Use a singleton class
Declare an instance in ShareData class:
public class ShareData {
private static ShareData sdInstance = null;
...}
add this method in ShareData class:
public static ShareData getInstance(){
if(sdInstance == null){
sdInstance = new ShareData();
}
return sdInstance;
}
To get same object in other classes , use this
ShareData sd = ShareData.getInstance();
now you will receive same sd.get_numb()
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);
I want to call a method from a android library class which i have imported as a androidlib.jar. As i am able to call a whole class of library but i dont want it, but i want to call a particular method of library class.
I tried something like this, but it is showing java.lang.Nullpointer exception
This is my library class (AndroidLiB.class), where i have imported its jar file
public class AndroidLiB extends Activity {
#Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.android_li_b);
startGPS();
}
public void startGPS()
{
Toast.makeText(getApplicationContext(),"Your GPS started",Toast.LENGTH_LONG).show();
}
}
This is my application class where i want to call a method from above class
public class AndLib1 extends Activity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.and_lib1);
AndroidLiB abc = new AndroidLiB();
abc.startGPS();
}
}
But it is not working
If you want simply a method from jar, then why you need to extends Activity. My suggestion is remove extends Activity will fix the NPE error.
Try this,
public class AndroidLiB {
Activity activity;
AndroidLiB(Activity activity){
this.activity = activity;
}
public void startGPS()
{
Toast.makeText(activity,"Your GPS started",Toast.LENGTH_LONG).show();
}
}
And In your main class call like
AndroidLiB lib = new AndroidLiB (this);
lib.startGPS();
I would do something like this:
public class Tool {
private Tool() {
// no direct instantiation
}
public static void startGPS(final Context context) {
Toast.makeText(context, "Your GPS started", Toast.LENGTH_LONG).show();
}
}
then
public class AndroidLiB extends Activity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.android_li_b);
Tool.startGPS(this);
}
}
and
public class AndLib1 extends Activity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.and_lib1);
Tool.startGPS(this);
}
}
You can extend library class. For example:
public class YourActivity extends AndroidLib
{
super.onCreate(savedInstanceState);
setContentView(R.layout.and_lib1);
startGPS();
}
What you're trying to do isn't really the best way to do things, but I'm assuming that the question being asked is how to import the jar correctly. If so:
If using eclipse,
Make sure the androidlib.jar file is in the libs folder.
Right click on androidlib.jar and select Build Path > Add to Build Path
Right click on your project folder, go to Properties > Java Build Path > Order and Export and then make sure androidlib.jar is selected.
The problem with your current code is that when you call getApplicationContext(), the Activity hasn't been started yet, therefore there is no context. A quick and dirty solution would be to rewrite the startGPS() method like this:
public static void startGps(Context context, String message) {
Toast.makeText(context, message, Toast.LENGTH_LONG).show();
}
But I would much rather put that method inside some sort of Utilities class or even inside a parent Activity class.