You'll have to bear with me here as I'm sure this is asked all the time, but I didn't manage to search it.
If I have a minimal android application and I seemingly have to declare all my controls in an event like onCreate, how do I then refer to these controls in functions given that these controls aren't initialized until the app is 'created'?
public class MyActivity extends ActionBarActivity {
public void myFunction(){
myButton.setText("Java is hard")
}
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_my);
final button myButton = (Button) findViewById(R.id.designerbutton);
}
Do I have to pass the controls as arguments every single time I call the function? That seems a bit unwieldy.
Read up about Member variables:
There are several kinds of variables:
Member variables in a class—these are called fields.
Variables in a method or block of code—these are called local variables.
Variables in method declarations—these are called parameters.
The Bicycle class uses the following lines of code to define its fields:
public int cadence;
public int gear;
public int speed;
Field declarations are composed of three components, in order:
Zero or more modifiers, such as public or private.
The field's type.
The field's name.
The fields of Bicycle are named cadence, gear, and speed and are all of data type integer (int). The public keyword identifies these fields as public members, accessible by any object that can access the class.
You can store it as an attribute like any other Java object
public class MyActivity extends ActionBarActivity {
private Button myButton;
public void myFunction(){
myButton.setText("Java is hard")
}
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_my);
myButton = (Button) findViewById(R.id.designerbutton);
}
Related
I have created an activity named ShowPairedDevices.java in which I have a super class named ShowPairedDevices to show all bluetooth paired devices.
Then I have created another class named Demo in the same activity which extends ShowPairedDevices.
public class ShowPairedDevices extends AppCompatActivity {
ArrayList<String> pairedDevicesList = new ArrayList<>();
public static ArrayAdapter<String> storePairedDevices;
BluetoothAdapter myBluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_show_paired_devices);
ListView myListView = (ListView) findViewById(R.id.listview);
Set<BluetoothDevice> pairedDevices = myBluetoothAdapter.getBondedDevices();
for(BluetoothDevice device : pairedDevices){
pairedDevicesList.add(device.getName());
}
storePairedDevices = new ArrayAdapter< (this,android.R.layout.simple_list_item_1,pairedDevicesList);
myListView.setAdapter(storePairedDevices);
}
}
Then I try to access ArrayList of superclass named pairedDevicesList in subclass , it cannot resolve it.I even tried to create object of superclass in subclass and then call members of super class through its object, but that too doesn't work. Please help.
Here's the subclass code:
class Demo extends ShowPairedDevices{
pairedDevicesList.add("another device name");
}
The "Demo" class makes no sense.
You can't simply access variables like that in the class scope.
Wrap it in a function, or override a current function and access the data like that:
public class Demo extends ShowPairedDevices {
#Override
protected void onCreate(Bundle savedInstanceState) {
pairedDevicesList.add("another device name");
}
}
I guess you are placed your child class in different Package of ShowPairedDevices class.
In that case you MUST use Protected keyword for ArrayList pairedDevicesList. This is called access modifier in Java. Useful link to refer here https://docs.oracle.com/javase/tutorial/java/javaOO/accesscontrol.html
At some points, you will need this implementation to reuse variables or functions.
Is there any way in which I can move a bundle of data from one class to another without actually changing the layout?
For example:
I have 3 classes: class A, B and C.
Now class B has navigation drawer and bottom navigation menu implemented which can be seen on class A and C and also be used at the same time.
However, I have a button in the bottom navigation menu which takes me to class C but the data which I need to view in this is in class A.
Is there any way by which I can just send a bundle of data to class B but without using intents, then retrieve the data from class B and show it on class C?
** EDIT **
P.S : B is an AppCombatActivity extended class and A and C are Fragment extended classes.
Your question is very simple to implement but it can also become a headache. This is what you should do.
class A:
public class A extends Activity {
static A INSTANCE;
String data="A";
#Override
public void onCreate(Bundle savedInstanceState) {
INSTANCE=this;
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
}
public static A getActivityInstance()
{
return INSTANCE;
}
public String getData()
{
return this.data;
}
}
class B:
public class B extends Activity {
String data;
#Override
public void onCreate(Bundle savedInstanceState) {
data=A.getActivityInstance().getData();
}
}
The trick is to create an Instance in class A and then using that instance to access all the public elements like methods, variables etc using that Instance.
Hope this helps :)
I would suggest using a SharedPreferences file to store the data in Class A. Then you can read from the SharedPreferences file wherever you want to show the data.
Refer this page -
https://developer.android.com/training/basics/data-storage/shared-preferences.html
You could use interface for passing data, this the reference
https://stackoverflow.com/a/9977370/2951976
I would like to make a Quiz app where I want my score variable to be inherited in each Activity.
I don't know how to perform that task.
Here is my MainActivity Code where I declared the global Variable.
public class MainActivity extends AppCompatActivity {
public int score=0;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
public void start(View v)
{
Intent intent = new Intent(this,question1.class);
startActivity(intent);
}
}
Here is the class in which I want to inherit it :
public class question1 extends MainActivity {
MainActivity ma= new MainActivity();
ma.score;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_question1);
}
}
In Android it's not recommended that you use variables to store data across an application (it's also not possible to do that using inheritance), that is bad practice.
What you're trying to do:
Store some int as score in a parent class
In the sub-class inherit that score to do something
Why this is a problem:
First of all, inheriting this score will not allow you to modify it in any way in a subclass. Java doesn't allow you to override values of an inherited field. See this for info. Secondly, creating an inheritance relationship between classes just to get some data is very futile... Because inheritance will inherit everything from the parent class which is not what you need.
Solution:
Instead Android APIs have features like SharedPreferences and SQLite that give you options for storing data.
Why?
Because storing this data in SharedPreferences or SQLite can be almost seen as storing it in a global variable for you to use throughout your application whenever you need it. It's storage that gives you read/write whenever you want, and doesn't get destroyed when your application closes.
Please take a look at this for more information on the storage options Android provides.
public class RootActivity extends Activity
{
static LiLa superLayout;
#Override
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
main();
setContentView(superLayout);
}
private void main()
{
// LiLa is a class which extends LinearLayout
superLayout = new LiLa(this);
//DownloadData is an AsyncTask
DownloadData mDownloadData = new DownloadData(this);
mDownloadData.execute();
}
}
So the AsyncTask change some parts of the superLayout, for now in the AsyncTak, I do :
RootActivity.superLayout.tv.setText("hello");
Would it be better to change :
static LiLa superLayout;
to
LiLa superLayout;
and :
DownloadData mDownloadData = new DownloadData(this);
to
DownloadData mDownloadData = new DownloadData(this, superLayout);
So that it would be possible to do in the AsyncTask :
superLayout.tv.setText("hello");
So question is : is it better to access this kind of parameters (TextView tv for example) or a method to change this TextView through static way or via parameter ?
Thanks for reading me.
EDIT : btw in my code it is a bit more messy it could be more like
RootActivity.superLayout.class1.class2.tv.setText("hello");
It would be better to avoid using a static in this case, and if that means that you need to pass the value as a parameter, that's fine too. (Statics are not O-O, and are generally a bad idea in an O-O design. They also present problems in unit testing.)
It is also generally a good idea to declare all instance variables and provide getter and/or setter methods if that is required.
I don't think static access to a layout is the best way of doing it.
A better solution would be to save the layout as a private variable and then add your AsyncTask as an inner class of your activity:
public class RootActivity extends Activity
{
private LiLa superLayout;
#Override
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
main();
setContentView(superLayout);
}
private void main()
{
// LiLa is a class which extends LinearLayout
superLayout = new LiLa(this);
//DownloadData is an AsyncTask
new DownloadData().execute();
}
private class DownloadData extends AsyncTask<..., ..., ...> {
//You can reference the variable superLayout here.
//If you need the context, use RootActivity.this
}
}
I think access view in parameter is better way. SO we don't have to make any static reference for the class or activity.
Read the "A public static field/method" part of this link:
http://developer.android.com/resources/faq/framework.html#3
I hope this will help.
How do I access the method myMethod from another class?
public class controller extends Activity
{
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
}
int myMethod() {int id = 0; return id;} //arbitrary example, may also be static?
}
You pass in your controller Activity to the other class, the way you would with any other object in Java. Just be careful not to hold onto an Activity in places that might cause garbage collection issues (e.g., a service, a static data member, a custom Application object).