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.
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 have two classes - my main Android activity class, and my reflection class. I am using Android Studio.
In my main activity class I have one button. I want to make it so that when I press this button I should get the name of the button which is defined in strings.xml.
I don't want to use getText() so don't tell me to use it. I want to use reflection or any other good way.
In my reflection class I used reflection to get my field which I defined in my main activity class and put it into a string variable. When I show this value using a toast it's giving me a null value.
My Reflection Class
public class Reflection extends MyActivity
static public String Value;
public static void Cool() {
MyActivity myActivity=new MyActivity(); // Creating Android Main Activity Class Object
try {
Field field=myActivity.getClass().getField("btnFIRST"); //btnFirst Field Which i Defined In Android Main Activity Class
field.setAccessible(true);
Value=(String)field.get(myActivity);
}
catch (Exception E){
E.printStackTrace();
}
}
}
Android Main Activity Class
public class MyActivity extends Activity {
Reflection ref; // Here I Am Creating My Reflection Class Object
Button btnFIRST;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_my);
btnFIRST = (Button) findViewById(R.id.btnFIRST);
ref=new Reflection(); // Reflection Class New Object
ref.Cool(); // Here I Am Calling My Cool Method Which Define In My Reflection Class
btnFIRST.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Toast.makeText(MyActivity.this, "Found Button Name="+ref.Value, Toast.LENGTH_LONG).show();
}
});
}
}
See here: +ref.Value I want to print my button value name, which is "(Click)" defined in strings.xml. But I am getting a null value instead.
I should be getting the output "Found Button Name=Click".
When you construct an instance of MainActivity, the value of btnFIRST for the instance is null. This is because btnFIRST is assigned only in the onCreate() method, which is never called on that instance.
You might think all you have to do is call onCreate() before trying to access the field, but that won't work either: you will get an exception. This is because the instance of MainActivity has not been properly set up (e.g., it doesn't have a proper Context, it does not have a Widnow, etc), so it won't be able to inflate the layout. The Android OS is responsible for doing this setup; it's not something you can do yourself. In general it is ALWAYS a bad idea to construct Activities yourself via their constructor.
That said, I can find absolutely no reason at all you would need to use reflection to obtain the text of this button. Unless you can give us a compelling reason why this would be necessary, you should just use getText().
Alternatively, if you know the string resource ID, you can call getString(...) in your Activity.
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);
}
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).