How to call a Java class from an Android activity? - android

This may sound like a question asked by another user, but the solution does not work for me so I would like to try asking about my code.
I have created a folder under the res directory that contains some java classes I would like to reference/ call from one of my Activities but the import does not work and the classes do not seem to be recognised.
Calling code in the Activity file:
// Method to populate the screen with images
public void initializeWithCGImages(){
ArrayList<src.cercia.batik.app.DesignUnitViewer> mapviewers,viewerList;
ArrayList<src.cercia.batik.geometry.Population> populations;
src.cercia.batik.app.InitializePopulation initialize=new src.cercia.batik.app.InitializePopulation();
populations = initialize.getInitialGenes();
mapviewers=new ArrayList<cercia.batik.app.DesignUnitViewer>();
...
}
Code for the reference in folder: "res/src/cercia/batik/app":
package cercia.batik.app;
import cercia.batik.geometry.Population;
public class InitializePopulation {
public InitializePopulation(){
}
...
}

The res directory is for resources. Things like imaged and layouts. The compiler isn't going to look there for Java files. Move them up into your java folder.

Related

Android. How to change own code programmatically?

I have a simple button
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="#+id/button"
android:onClick="trap" />
Initial code
package com.example.a21.ii;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
public class MainActivity extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
public void trap(View view){
//click function
}
}
After clicking it must change to this code
package com.example.a21.ii;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
public class MainActivity extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
public void trap(View view){
//click function
}
private void additionalFunction(){}
}
so how to change the own code? Any suggestion is appreciate and Please let me know if more details are need. Thanks
If you want to add an additional function, you cannot do it by changing the existing code.
The ANdroid APK is read-only. You cannot write to it, so you cannot change the .java files in the APK.
However:
You can create a class that loads the new methods (NOTE Database, shared prefs or files is required) and strips the function of them, and takes appropriate action without writing the methods to the APK.
Essentially, you want to execute the method without writing it to the APK, so you need to design a class that can execute these methods.
OR:
YOu can create an external class(File only) in internal or external storage. Then you write any methods to that class. Refer this SO question to see how you can load and execute code in external .java files.
Please note that this is a workaround. You cannot write to the APK, but you can write .java files to the system and load them and execute them at runtime.
Final note
The first option (Create a class to load methods and execute them internally in the app) is extremely hard. It may even be impossible. The second option (where you create a .java file externally and load it in) is probably the easiest option around. You save a file externally and add any methods you want, and create a new instance of the external class in the class you want these methods in. This is the only way (I know of) you can create files and make them editable.
And I cannot say it enough times:
The APK is read only!
You cannot write to the APK, but you can read from it. For an instance oyu can read assets, but you cannot write to the assets.
The only way to "change" the contents of an APK is to decode the old, add whatever changes you need and create a new apk. But the process of doing this requires root, and adding the entire system to an application that does something else will add a lot of bloat to your app. Further, it will then most likely be signed with a different keystore and may make it incompatible with the store version, which may remove the option for updates in the future.
And from your comments, I apparently have to say it one more time:
You cannot change the APK like changing a text file! The APK is like a zipped file. To change it, you have to unpack it and then edit it. Meaning no matter what programming language you are thinking of, you have to unpack the APK, change it and repack it. Which, as I mentioned above, has many side effects.
And as you mentioned in another comment, if you suddenly are wondering about windows and the function there, that is a whole other topic (and a whole different set of developers who have competence on the topic). Ask another question instead of having two very distinct questions in one

Dot42 - How to populate preference fragment from a resource?

While using Dot42 it appears that I can access AddPreferencesFromResource(int) of PreferenceActivity class but the resource that gets passed to this method is not available to me. I expected the call to look like AddPreferencesFromResource(R.Xmls.Preferences), however R.Xmls does not exist. The xml folder contains preferences.xml and is stored next to layout, menu, etc. resource folders. However generated R.cs doesn't contain a class for Xmls. Included sample projects don't have any examples of usage of PreferenceActivity. Can anybody confirm whether or not preferences are supported in Dot42?
Your question is probably not so much how to populate a preference fragment from XML but more how to add an XML resource to a dot42 project and how to reference it.
You add an XML resource by adding an XML file to your Visual Studio (dot42) project as you would normally do; this is no different from adding an XML file to a non-dot42 project. Next, go to the properties of the file and set BuildAction to XmlResource.
Note that dot42 has no folder structure requirement (such as /res/xml/).
When you now compile again and type "R." you will see intellisence coming up with R.Xmls.
If you take a look at R.cs (under Properties), you will see it now includes R.Xmls with a generated member for your XML resource:
//------------------------------------------------------------------------------
// This file is automatically generated by dot42
//------------------------------------------------------------------------------
namespace PreferenceFragmentSample
{
using System;
public sealed class R
{
public sealed class Layouts
{
public const int MainLayout = 0x7f020000;
}
public sealed class Xmls
{
public const int preferences = 0x7f030000;
}
}
}

imported classes not working

I'm doing a calculator tutorial online, and there is two separate classes that need to be imported into the main class
I put the two classes in a new package in the scr folder and tried importing them into main class like so
import com.example.brkyclasses.Alertwindow;
import com.example.brkyclasses.Calculator2;
Eclipse is still asking me to create methods when the methods are in the two classes is there something else i need to do, do i need to add these two classes to manifest or something else
Those are package specific imports. You need to look in your manifest xml and see what your package name is under the package tag (should be like 3rd line). And then you will probably create some file called Alertwindow and Calculator2 and so you will import your own classes. using the package.name.Alertwindow format.
You need to add either the source code for those classes, or the .jar file that those classes are implemented in, to your project. If you included the .jar, you need to edit your project settings and specify the location of the .jar

Handling a core project and multiple derived from it in Android

I've searched around SO for this and found a few things, but I'm still not sure I fully understand, so I ask you for clarifications.
Here is what I need:
Have a project that has specific function: interrogate web service, display results in different views
Have a second, third and forth project that has exactly the same functionality as the first one, but only different graphic elements like splash screen image, icon, name, package name.
So, I have ProjectCore with activities and functionality. Project1 with a car icon and car image for splashscreen. Project2 with airplane icon and airplane image for splashscreen. Something like that. Each projects has a class with constants like'appId, appName, appServerURL"... All the web service call, data display is in Core as it's the same for all prohects, only the read is made from Constants class.
I was thinking of this approach
Make ProjectCore a Library project with a package like com.domain.core and dummy images
Make Project1, add reference to ProjectCore in it and with a package like com.domain.code.project1 and in resources folder, put images with same name as in core project
Make Project2 on the same principle like project1
Will this approach work ?
Thanks.
Later Edit. I've tried as mentioned before. For instance in Core project I had in drawable a file called splash.png. In Project1's and Project2's drawable folder I've put spash.png file with other images. This works fine. Running the Project1 and Project2 on my phone, started each app with it's own image. So far so good.
Then, because I have different constants I need to use in my App, I went into Core library project and added:
public class C {
public static String SomeConstant = "Project core!";
}
Here comes the problem, I need to have different constant values across Project1 and Project2. Because on Core project, the class is in com.domain.core.utils for instance... I can't add the same package in Project1 and Project2. How do I add the classes so I can update their values and be used on each project with particlar values ?
public class C {
public static String SomeConstant = "Project 1 constant!";
}
public class C {
public static String SomeConstant = "Project 2 constant!";
}
Thank you!
You want to create your functionality in a Library project and then have all of your Branded/OEM/3rdParty projects extend from this, overriding images and string resources where necessary.
When you need to use "Constants" you should instead have a single "run once" portion of your code (such as a splash screen) load these strings from resource files:
public static final String CONSTANT_ONE;
public void onCreate() { CONSTANT_ONE = getResources().getString(R.String.CONSTANT_ONE); }
EDIT
I'm unsure on how initialising a final value on onCreate() will perform. If final doesn't work well and you're worried about changing the variable during program execution then make the variable private (so only that class can assign to it) and then create a public static String getConstantOne() function.
Yes. Library projects are ideal for this, especially if only resources differ. I've used the exact approach that you've outlined with success...
Yes this should work fine. I did something a bit similar and I found occasionally you may have some circumstances where you want to call out from your library project to your application project. In these cases I used interfaces/abstract classes defined in the library project but implemented in application project...

eclipse error with android: id cannot be resolved or is not a field

I just started playing around with android development, and already with just an attempt at making a button, I have encountered a problem.
The error I'm given in the following code is right on "R.id.button1".
It says id cannot be resolved or is not a field.
Do I need to manually reference every single object I make in the layout xml file? I found that this did work, but it does seem to be a bit much for every button I want to make...
package com.example.helloandroid;
import android.app.Activity;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
public class HelloAndroid extends Activity {
/** Called when the activity is first created. */
private Button button1;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
button1 = (Button)findViewById(R.id.button1);
button1.setOnClickListener(new OnClickListener()
{
public void onClick(View v)
{
finish();
}
});
}
}
I've been wasting a lot of time (two weeks) because of the same problem until I discovered the problem wasn't mine but Eclipse's.
I guess there's a lot of people with the same problem.
Just try this: Save your project, close Eclipse and then open it again. So simple.
Do I need to manually reference every single object I make in the layout xml file
Yes, otherwise you won't be able to do anything with those views. It's not that bad actually. So, each time you create a view in your XML, and you want to reference it, put an ID:
<View
android:id="#+id/the_id"/>
And then, from your code you can reference it using the R class. You can type, in the example, R.id.the_id and then Ctrl+Shift+O to make Eclipse auto import the needed files.
You can speed up your productivity by using frameworks like Roboguice; I think it's for lazy people, though.
This answer is not applicable to this question (looking at code you have provided). Just adding it if someone else stumbles here and above mentioned answers do not help.
If cleaning (Project --> clean) doesn't helps or saving and restarting eclipse doesn't help either, check for the following incorrect import.
import android.R;
Which Eclipse sometimes add by mistake on auto-import (Ctrl+Shift+O).
Remove that line (import) and it's done :D
Following this EXCELLENT tutorial , I encountered the same problem. After reading Carmello's answer (Sept 17, 2011. 07:23) I simply clicked File->Save All, and voila, 'button0' was automagically defined, and even syntax highlighted.
If "R.id.button1" is not defined, then you'll get a compile error, just as you saw. If you don't define this in the layout, then it won't be defined.
You don't have to specify every object you create in the layout, but you do if you try to reference it from "R.*". You can manually create buttons and other objects that are not specified in the layout.
I ran through the same issues for time being. Plz, do not forget to define as follows:
<View
android:id="#+id/button1" />
if you are using the id in your .java class.
Button b =(Button) findViewById(R.id.button1);
Being said that, the id defined in xml file must match with the id in findViewById().
Go to the 'R.java' file under the 'gen' folder and check whether your 'button1' is present under the class 'id'.If not,then this could be the reason you got that error.When you use the statement " R.id. " make sure that the is present under the appropriate class,in this case under the 'id' class.
R.id is a generated object that assigns int numbers to resources. Try this go to your gen/mypackage/R.java and delete the file. As you can see it is re-generated. This file provides static references where as the context is more of the dynamic state of your app. If you have syntax errors that will prevent automatic re-generation of that R.java file so you will get lots or R. errors. As everyone else has said you can click save all icon or ctl+shift+s on windows. You can clean the project project/clean and that will clean up 95% of those exceptions. Yes eclipse is buggy that way but netbeans does not support android that well. this link may help
Good luck
Do these things,anyone of this will help you
Project -> Clean,
Right click -> Fix Project Properties
Restart Eclipse
make some fake modification in manifest and save
check your console for any error message
check your drawable folder, check the image names satisfy the rules

Categories

Resources