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.
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.
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();
Assume that i have a activity class named MainActivity.java. But this activity has about 3000 lines code for example.
I want to seperate code parts of this file to an external java file(class) named NecessaryThings.java. But if i run my project on emulator it stops itself after this operation.
Is there a way to seperate some lines of this activity?
I wrote mini example for better..
Also what do you think about;
Using this method is beneficial or harmful in terms of performance?
This is my MainActivity.java
public class MainActivity extends Activity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
//I want to call these lines from NecessaryThings.java
TextView genderResult = (TextView) findViewById(R.id.genderText);
genderResult.setText("Cinsiyet:");
TextView calorieResult = (TextView) findViewById(R.id.remainCalorie);
String getGenderSTR = getIntent().getStringExtra("GENDER");
genderResult.setText(getGenderSTR);
String calorieResultSTR = getIntent().getStringExtra("CALORIECHOOSED");
calorieResult.setText(calorieResultSTR);
/*
.....
.....
*/
}
Aftet I take above code, then I want to store it in NecessaryThings.java
like this..
//All necessary imports here. There is no problem about those.
public class NecessaryThings extends Activity {
public void myPersonalMethod() {
TextView genderResult = (TextView) findViewById(R.id.genderText);
genderResult.setText("Cinsiyet:");
TextView calorieResult = (TextView) findViewById(R.id.remainCalorie);
String getGenderSTR = getIntent().getStringExtra("GENDER");
genderResult.setText(getGenderSTR);
String calorieResultSTR = getIntent().getStringExtra("CALORIECHOOSED");
calorieResult.setText(calorieResultSTR);
}
}
If I rearrange my MainActivity.java It will be like this...
public class MainActivity extends Activity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
NecessaryThings showMyMethod = new NecassaryThings();
showMyMethod.myPersonalMethod();
/*
the rest of the codes...
*/
}
But it is not working if I seperate code. Why and How can I do it?
public class MainActivity extends NecessaryThings {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
myPersonalMethod();
}
NecessaryThings extends Activity so MainActivity no long needs to extend from Activity, it should extend from NecessaryThings. One thing I need to point out is that super.onCreate(savedInstanceState); will call the onCreate(); from NecessaryThings. Since my myPersonalMethod(); is from super class, you can just call it.
All activities are regular Java classes and you can - of course, have many non-UI classes like Application, you can have helpers etc. Looking into your question, I would like to tell you that the Activity doesn't have user defined constructor and can be created only indirectly by calling startActivity method, but in other aspects it is a common Java class.
Hence, what you'll have to do is, let your NecessaryThings.java be a normal class, to which you can pass the context from your MainActivity and do all that is required.
Hope this helps.
I have the following code in which I am using the application context to retrieve needed information:
public class Data{
private boolean VarA;
public void setVarA(boolean B,Context ctx)
{
SharedPreferences CoreDataStorage = ctx.getSharedPreferences(PREFS_NAME, 0);
SharedPreferences.Editor editor = CoreDataStorage.edit();
editor.putBoolean("PrefVarA", VarA);
edit.commit();
}
}
Now I am calling the public method setVarA() from the below class
public class MyActivity extends Activity{
Data cd = new Data();
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.registration);
cd.setVarA(true,this);
}
}
In the activity above it shows me compilation error that it can't cast from MyActivity to Context. Please suggest any solution. Is the above code is not proper way to pass the context?
You need the application Context to access the shared preferences. It should be:
cd.setVarA(true,this.getApplicationContext());
in the onCreate of MyActivity.